<?php
// ========================================
// مدیریت نقش‌ها و دسترسی‌ها (نسخه نهایی - رفع خطای تکراری اسلاگ)
// پروژه فروشگاه کیف‌لند
// ========================================
require_once '../config/database.php';
require_once '../config/settings.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

Auth::requireAdmin();
$db = Database::getInstance()->getConnection();
$pageTitle = 'مدیریت نقش‌ها | کیف‌لند';

$error = '';
$success = '';
$table_ready = false;
$has_role_column = false;

// بررسی ساختار دیتابیس
try {
    $db->query("SELECT id FROM roles LIMIT 1");
    $table_ready = true;
    
    $col_check = $db->query("SHOW COLUMNS FROM users LIKE 'role_id'");
    $has_role_column = $col_check->rowCount() > 0;
    
    if (!$has_role_column) {
        $error = '⚠️ ستون <code>role_id</code> در جدول <code>users</code> وجود ندارد. لطفاً کوئری زیر را در phpMyAdmin اجرا کنید:<br><code>ALTER TABLE `users` ADD COLUMN `role_id` INT UNSIGNED DEFAULT NULL;</code>';
    }
} catch (Exception $e) {
    $error = 'جدول roles در دیتابیس یافت نشد. لطفاً جدول را بسازید.';
}

// تعریف ماژول‌ها و دسترسی‌های استاندارد
$permission_groups = [
    'داشبورد' => ['view'],
    'محصولات' => ['view', 'add', 'edit', 'delete'],
    'سفارشات' => ['view', 'edit_status', 'cancel', 'delete'],
    'کاربران' => ['view', 'add', 'edit', 'delete'],
    'دسته‌بندی‌ها' => ['view', 'add', 'edit', 'delete'],
    'نظرات' => ['view', 'approve', 'delete'],
    'گزارشات' => ['view', 'export'],
    'تنظیمات' => ['view', 'edit']
];

$perm_labels = [
    'view' => 'مشاهده', 'add' => 'افزودن', 'edit' => 'ویرایش', 'delete' => 'حذف',
    'approve' => 'تایید', 'cancel' => 'لغو', 'edit_status' => 'تغییر وضعیت', 'export' => 'خروجی'
];

// ========================================
// پردازش POST
// ========================================
if ($table_ready && $_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['action'])) {
            $id = isset($_POST['role_id']) ? (int)$_POST['role_id'] : 0;
            
            if ($_POST['action'] === 'save_role') {
                $name = trim($_POST['name'] ?? '');
                $description = trim($_POST['description'] ?? '');
                $is_default = isset($_POST['is_default']) ? 1 : 0;
                $permissions = $_POST['permissions'] ?? [];
                
                if (empty($name)) throw new Exception('نام نقش الزامی است.');
                
                // تولید اسلاگ استاندارد
                $slug = preg_replace('/[^\w\s-]/u', '', $name);
                $slug = strtolower(trim(preg_replace('/[\s_\-]+/', '-', $slug), '-'));
                if (empty($slug)) $slug = 'role-' . time();
                
                // ✅ بررسی یکتایی اسلاگ قبل از ذخیره
                $check_slug = $db->prepare("SELECT id FROM roles WHERE slug = ?" . ($id > 0 ? " AND id != ?" : ""));
                $check_slug->execute($id > 0 ? [$slug, $id] : [$slug]);
                if ($check_slug->rowCount() > 0) {
                    throw new Exception('این نام نقش قبلاً استفاده شده است. لطفاً نام دیگری انتخاب کنید.');
                }
                
                $perm_json = json_encode($permissions, JSON_UNESCAPED_UNICODE);
                
                if ($id > 0) {
                    $stmt = $db->prepare("UPDATE roles SET name = ?, slug = ?, description = ?, permissions = ?, is_default = ?, updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$name, $slug, $description, $perm_json, $is_default, $id]);
                } else {
                    $stmt = $db->prepare("INSERT INTO roles (name, slug, description, permissions, is_default, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())");
                    $stmt->execute([$name, $slug, $description, $perm_json, $is_default]);
                }
                Auth::logActivity('role_save', "ذخیره نقش: $name");
                $success = 'نقش با موفقیت ذخیره شد.';
            } 
            elseif ($_POST['action'] === 'delete_role' && $id > 0) {
                $check = $db->prepare("SELECT is_default FROM roles WHERE id = ?");
                $check->execute([$id]);
                $role = $check->fetch();
                
                if (!$role) throw new Exception('نقش مورد نظر یافت نشد.');
                if ($role['is_default']) throw new Exception('حذف نقش‌های پیش‌فرض مجاز نیست.');
                
                if ($has_role_column) {
                    $user_count = $db->prepare("SELECT COUNT(*) FROM users WHERE role_id = ?");
                    $user_count->execute([$id]);
                    if ($user_count->fetchColumn() > 0) {
                        throw new Exception('این نقش دارای کاربر است. ابتدا کاربران را به نقش دیگری منتقل کنید.');
                    }
                }
                
                $db->prepare("DELETE FROM roles WHERE id = ?")->execute([$id]);
                Auth::logActivity('role_delete', "حذف نقش ID#$id");
                $success = 'نقش حذف شد.';
            }
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

// ========================================
// دریافت داده‌ها
// ========================================
$roles = [];
$search = trim($_GET['search'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 10;
$offset = ($page - 1) * $per_page;

if ($table_ready) {
    try {
        $count_select = $has_role_column ? "(SELECT COUNT(*) FROM users u WHERE u.role_id = r.id)" : "0";
        $sql = "SELECT r.*, $count_select as user_count FROM roles r WHERE 1=1";
        $params = [];
        
        if ($search) {
            $sql .= " AND (r.name LIKE ? OR r.slug LIKE ? OR r.description LIKE ?)";
            $p = "%$search%"; array_push($params, $p, $p, $p);
        }
        
        $count_sql = preg_replace('/SELECT r\.\*, .+ as user_count/', 'SELECT COUNT(*)', $sql);
        $stmt_count = $db->prepare($count_sql);
        $stmt_count->execute($params);
        $total_roles = $stmt_count->fetchColumn();
        $total_pages = ceil($total_roles / $per_page);
        
        $sql .= " ORDER BY r.is_default DESC, r.created_at DESC LIMIT ? OFFSET ?";
        array_push($params, (int)$per_page, (int)$offset);
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $roles = $stmt->fetchAll();
        
        $edit_role = null;
        if (isset($_GET['edit_id'])) {
            $stmt = $db->prepare("SELECT * FROM roles WHERE id = ?");
            $stmt->execute([(int)$_GET['edit_id']]);
            $edit_role = $stmt->fetch();
        }
    } catch (Exception $e) {
        $error = 'خطا در دریافت اطلاعات: ' . $e->getMessage();
    }
}

include 'includes/admin-header.php';
?>

<style>
.roles-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; flex-wrap:wrap; gap:16px; }
.stats-row { display:grid; grid-template-columns:repeat(3,1fr); gap:12px; margin-bottom:20px; }
.stat-box { background:var(--glass-bg); border:1px solid var(--glass-border); border-radius:var(--radius-sm); padding:14px; text-align:center; }
.stat-box h4 { margin:0; font-size:22px; color:var(--primary); font-weight:700; }
.stat-box p { margin:4px 0 0; font-size:12px; color:var(--text-secondary); }
.filters-bar { display:flex; gap:10px; margin-bottom:20px; background:var(--glass-bg); padding:12px; border-radius:var(--radius-sm); border:1px solid var(--glass-border); }
.filter-input { flex:1; min-width:140px; padding:9px 12px; border:1px solid var(--glass-border); border-radius:8px; background:var(--glass-bg-light); font-family:inherit; font-size:13px; color:var(--text-primary); }
.filter-input:focus { outline:none; border-color:var(--primary); box-shadow:0 0 0 3px rgba(0,122,255,0.15); }
.roles-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(340px, 1fr)); gap:16px; margin-bottom:24px; }
.role-card { background:var(--glass-bg); border:1px solid var(--glass-border); border-radius:var(--radius); padding:16px; transition:0.2s; position:relative; }
.role-card:hover { background:var(--glass-bg-light); transform:translateY(-2px); box-shadow:var(--shadow-soft); }
.role-card.default { border-left: 4px solid var(--primary); }
.role-header { display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:12px; }
.role-name { font-weight:700; font-size:16px; color:var(--text-primary); }
.role-slug { font-size:11px; color:var(--text-muted); font-family:monospace; background:rgba(0,0,0,0.05); padding:2px 6px; border-radius:4px; margin-top:4px; display:inline-block; }
.role-badge { padding:3px 8px; border-radius:12px; font-size:10px; font-weight:600; }
.badge-default { background:var(--primary-light); color:var(--primary); }
.badge-custom { background:var(--glass-hover); color:var(--text-secondary); }
.role-desc { font-size:12px; color:var(--text-secondary); line-height:1.5; margin-bottom:12px; min-height:36px; }
.role-meta { display:flex; justify-content:space-between; align-items:center; font-size:11px; color:var(--text-muted); border-top:1px solid rgba(255,255,255,0.15); padding-top:10px; }
.perm-count { display:inline-flex; align-items:center; gap:4px; background:rgba(0,122,255,0.1); color:var(--primary); padding:2px 8px; border-radius:10px; }
.role-actions { display:flex; gap:6px; margin-top:12px; }
.btn-xs { padding:5px 8px; font-size:11px; border-radius:6px; border:none; cursor:pointer; font-family:inherit; }
.btn-edit { background:var(--info); color:#fff; }
.btn-delete { background:var(--danger); color:#fff; }
.modal-overlay { position:fixed; inset:0; background:rgba(0,0,0,0.5); backdrop-filter:blur(6px); z-index:2000; display:none; align-items:center; justify-content:center; opacity:0; transition:0.2s; }
.modal-overlay.active { display:flex; opacity:1; }
.modal-box { background:var(--glass-bg-light); border:1px solid var(--glass-border); border-radius:var(--radius-lg); width:95%; max-width:600px; max-height:90vh; overflow-y:auto; box-shadow:var(--glass-shadow-lg); transform:scale(0.95); transition:0.2s; }
.modal-overlay.active .modal-box { transform:scale(1); }
.modal-head { padding:16px 20px; border-bottom:1px solid var(--glass-border); display:flex; justify-content:space-between; align-items:center; position:sticky; top:0; background:inherit; z-index:10; }
.modal-head h3 { margin:0; font-size:16px; }
.modal-close { background:none; border:none; font-size:20px; cursor:pointer; color:var(--text-muted); width:36px; height:36px; display:flex; align-items:center; justify-content:center; border-radius:50%; transition:0.2s; }
.modal-close:hover { background:rgba(255,255,255,0.3); color:var(--danger); }
.modal-body { padding:20px; }
.modal-foot { padding:16px 20px; border-top:1px solid var(--glass-border); display:flex; justify-content:flex-end; gap:8px; position:sticky; bottom:0; background:inherit; }
.form-group { margin-bottom:16px; }
.form-label { display:block; font-size:13px; font-weight:600; margin-bottom:6px; }
.form-control { width:100%; padding:10px 14px; border:1px solid var(--glass-border); border-radius:var(--radius-sm); background:var(--glass-bg); font-family:inherit; font-size:14px; color:var(--text-primary); }
.form-control:focus { outline:none; border-color:var(--primary); box-shadow:0 0 0 3px rgba(0,122,255,0.15); }
textarea.form-control { min-height:80px; resize:vertical; }
.perm-group { background:var(--glass-bg); border:1px solid var(--glass-border); border-radius:var(--radius-sm); padding:12px; margin-bottom:12px; }
.perm-group-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:8px; font-weight:600; font-size:13px; }
.perm-group-header label { display:flex; align-items:center; gap:6px; cursor:pointer; }
.perm-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(120px, 1fr)); gap:8px; }
.perm-item { display:flex; align-items:center; gap:6px; font-size:12px; }
.perm-item input { accent-color:var(--primary); width:16px; height:16px; }
.btn { display:inline-flex; align-items:center; justify-content:center; gap:6px; padding:9px 16px; border-radius:8px; font-weight:600; font-size:13px; cursor:pointer; border:none; font-family:inherit; transition:0.2s; }
.btn-primary { background:var(--primary); color:#fff; }
.btn-primary:hover { background:var(--primary-hover); transform:translateY(-1px); }
.btn-ghost { background:transparent; border:1px solid var(--glass-border); color:var(--text-secondary); }
.btn-ghost:hover { background:var(--glass-hover); }
.empty-state { text-align:center; padding:40px 20px; color:var(--text-muted); grid-column:1/-1; }
.empty-state i { font-size:48px; opacity:0.3; margin-bottom:12px; display:block; }
.alert-warning { background:rgba(255,149,0,0.15); color:#6A4000; border:1px solid rgba(255,149,0,0.3); padding:12px 16px; border-radius:10px; margin-bottom:20px; }
@media (max-width:768px) { .stats-row { grid-template-columns:1fr; } .roles-grid { grid-template-columns:1fr; } .filters-bar { flex-direction:column; } .perm-grid { grid-template-columns:1fr; } }
</style>

<main class="main-content">
    <header class="top-header">
        <button class="menu-toggle" id="menuToggle"><i class="fas fa-bars"></i></button>
        <div class="search-box"><i class="fas fa-search"></i><input type="text" placeholder="جستجو..."></div>
        <div class="header-actions">
            <button class="btn btn-primary btn-sm" onclick="openRoleModal()"><i class="fas fa-plus"></i> نقش جدید</button>
        </div>
    </header>

    <div class="dashboard-content">
        <div class="roles-header">
            <div class="page-title" style="margin:0;"><h1>مدیریت نقش‌ها و دسترسی‌ها</h1><p>تعریف سطوح دسترسی کاربران سیستم</p></div>
        </div>

        <?php if ($error): ?><div class="alert alert-warning"><i class="fas fa-exclamation-triangle"></i> <?= $error ?></div><?php endif; ?>
        <?php if ($success): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?></div><?php endif; ?>

        <?php if (!$table_ready): ?>
        <div class="glass-card" style="text-align:center; padding:30px;">
            <h3 style="color:var(--danger);">جدول roles یافت نشد</h3>
            <code style="display:block; background:#f4f4f4; padding:10px; margin:10px 0; text-align:left; direction:ltr; border-radius:6px; font-size:12px;">
            CREATE TABLE `roles` ( `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(100) NOT NULL, `slug` VARCHAR(100) NOT NULL UNIQUE, `description` TEXT, `permissions` JSON, `is_default` TINYINT(1) DEFAULT 0, `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
            </code>
        </div>
        <?php else: ?>

        <div class="stats-row">
            <div class="stat-box"><h4><?= $total_roles ?></h4><p>کل نقش‌ها</p></div>
            <div class="stat-box"><h4><?= $has_role_column ? array_sum(array_column($roles, 'user_count')) : '---' ?></h4><p>کاربران متصل</p></div>
            <div class="stat-box"><h4><?= count(array_filter($roles, fn($r) => $r['is_default'])) ?></h4><p>نقش‌های پیش‌فرض</p></div>
        </div>

        <form method="GET" class="filters-bar">
            <input type="text" name="search" class="filter-input" placeholder="جستجو در نام، اسلاگ یا توضیحات..." value="<?= htmlspecialchars($search) ?>">
            <button type="submit" class="btn btn-primary">جستجو</button>
            <?php if ($search): ?><a href="roles.php" class="btn btn-ghost">پاک کردن</a><?php endif; ?>
        </form>

        <div class="roles-grid">
            <?php foreach ($roles as $role): 
                $perms = json_decode($role['permissions'], true) ?: [];
                $perm_count = count($perms);
            ?>
            <div class="role-card <?= $role['is_default'] ? 'default' : '' ?>">
                <div class="role-header">
                    <div>
                        <div class="role-name"><?= htmlspecialchars($role['name']) ?></div>
                        <div class="role-slug"><?= htmlspecialchars($role['slug']) ?></div>
                    </div>
                    <span class="role-badge <?= $role['is_default'] ? 'badge-default' : 'badge-custom' ?>">
                        <?= $role['is_default'] ? 'پیش‌فرض' : 'سفارشی' ?>
                    </span>
                </div>
                <div class="role-desc"><?= nl2br(htmlspecialchars($role['description'] ?: 'بدون توضیحات')) ?></div>
                <div class="role-meta">
                    <span class="perm-count"><i class="fas fa-key"></i> <?= $perm_count ?> دسترسی</span>
                    <span><i class="fas fa-users"></i> <?= $role['user_count'] ?> کاربر</span>
                </div>
                <div class="role-actions">
                    <button class="btn-xs btn-edit" onclick="openRoleModal(<?= $role['id'] ?>)"><i class="fas fa-edit"></i> ویرایش</button>
                    <?php if (!$role['is_default']): ?>
                    <form method="POST" style="display:inline" onsubmit="return confirm('آیا از حذف این نقش مطمئن هستید؟')"><input type="hidden" name="action" value="delete_role"><input type="hidden" name="role_id" value="<?= $role['id'] ?>"><button type="submit" class="btn-xs btn-delete"><i class="fas fa-trash"></i> حذف</button></form>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
            <?php if (empty($roles)): ?><div class="empty-state"><i class="fas fa-user-shield"></i><p>هیچ نقشی تعریف نشده است.</p></div><?php endif; ?>
        </div>

        <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?><a href="?<?= http_build_query(array_merge($_GET, ['page'=>$page-1])) ?>" class="page-link"><i class="fas fa-chevron-right"></i></a><?php endif; ?>
            <?php for ($i=1; $i<=$total_pages; $i++): ?>
                <?php if ($i==1 || $i==$total_pages || abs($page-$i)<=2): ?>
                <a href="?<?= http_build_query(array_merge($_GET, ['page'=>$i])) ?>" class="page-link <?= $i==$page?'active':'' ?>"><?= $i ?></a>
                <?php elseif (abs($page-$i)==3): ?><span style="color:var(--text-muted); padding:0 4px;">...</span><?php endif; ?>
            <?php endfor; ?>
            <?php if ($page < $total_pages): ?><a href="?<?= http_build_query(array_merge($_GET, ['page'=>$page+1])) ?>" class="page-link"><i class="fas fa-chevron-left"></i></a><?php endif; ?>
        </div>
        <?php endif; ?>

        <?php endif; ?>
    </div>
</main>

<!-- Modal: Add/Edit Role -->
<div class="modal-overlay" id="roleModal">
    <div class="modal-box">
        <form method="POST">
            <input type="hidden" name="action" value="save_role">
            <input type="hidden" name="role_id" id="role_id">
            
            <div class="modal-head">
                <h3 id="modal_title">افزودن نقش جدید</h3>
                <button type="button" class="modal-close" onclick="closeRoleModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">نام نقش</label>
                    <input type="text" name="name" id="role_name" class="form-control" placeholder="مثال: مدیر فروشگاه" required>
                </div>
                <div class="form-group">
                    <label class="form-label">توضیحات</label>
                    <textarea name="description" id="role_desc" class="form-control" placeholder="توضیح کوتاه درباره سطح دسترسی این نقش..."></textarea>
                </div>
                
                <div class="form-group">
                    <label class="form-label">دسترسی‌های ماژول‌ها</label>
                    <?php foreach ($permission_groups as $module => $perms): ?>
                    <div class="perm-group">
                        <div class="perm-group-header">
                            <label><input type="checkbox" class="group-check" data-group="<?= $module ?>"> <?= htmlspecialchars($module) ?></label>
                            <small style="color:var(--text-muted); cursor:pointer;" onclick="toggleGroup('<?= $module ?>', true)">انتخاب همه</small>
                        </div>
                        <div class="perm-grid" id="perms-<?= $module ?>">
                            <?php foreach ($perms as $p): ?>
                            <label class="perm-item"><input type="checkbox" name="permissions[]" value="<?= $module ?>:<?= $p ?>" data-module="<?= $module ?>"> <?= $perm_labels[$p] ?? $p ?></label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <label class="perm-item" style="margin-top:12px; font-weight:600;">
                    <input type="checkbox" name="is_default" id="role_default"> این نقش پیش‌فرض باشد (قابل حذف نیست)
                </label>
            </div>
            <div class="modal-foot">
                <button type="button" class="btn btn-ghost" onclick="closeRoleModal()">انصراف</button>
                <button type="submit" class="btn btn-primary">ذخیره نقش</button>
            </div>
        </form>
    </div>
</div>

<script src="assets/js/script.js"></script>
<script>
const modal = document.getElementById('roleModal');
const permGroups = <?= json_encode($permission_groups, JSON_UNESCAPED_UNICODE) ?>;

function openRoleModal(id = null) {
    document.querySelector('form').reset();
    document.getElementById('role_id').value = '';
    document.getElementById('modal_title').textContent = 'افزودن نقش جدید';
    document.querySelectorAll('.perm-item input, .group-check').forEach(cb => cb.checked = false);

    if (id) {
        document.getElementById('modal_title').textContent = 'ویرایش نقش';
        document.getElementById('role_id').value = id;
        window.location.href = 'roles.php?edit_id=' + id;
    } else {
        modal.classList.add('active');
    }
}

function closeRoleModal() {
    modal.classList.remove('active');
    if (window.location.search.includes('edit_id=')) {
        window.history.replaceState({}, document.title, "roles.php");
    }
}

function toggleGroup(module, state) {
    document.querySelectorAll(`#perms-${module} input`).forEach(cb => cb.checked = state);
    document.querySelector(`.group-check[data-group="${module}"]`).checked = state;
}

document.querySelectorAll('.group-check').forEach(group => {
    group.addEventListener('change', function() { toggleGroup(this.dataset.group, this.checked); });
});

<?php if ($edit_role): ?>
document.getElementById('role_id').value = <?= $edit_role['id'] ?>;
document.getElementById('role_name').value = `<?= addslashes($edit_role['name']) ?>`;
document.getElementById('role_desc').value = `<?= addslashes($edit_role['description']) ?>`;
document.getElementById('role_default').checked = <?= $edit_role['is_default'] ? 'true' : 'false' ?>;

const savedPerms = <?= json_encode(json_decode($edit_role['permissions'], true) ?: []) ?>;
savedPerms.forEach(val => {
    const cb = document.querySelector(`.perm-item input[value="${val}"]`);
    if (cb) cb.checked = true;
});

Object.keys(permGroups).forEach(mod => {
    const groupPerms = permGroups[mod];
    const activeCount = groupPerms.filter(p => savedPerms.includes(`${mod}:${p}`)).length;
    if (activeCount === groupPerms.length) document.querySelector(`.group-check[data-group="${mod}"]`).checked = true;
});

window.onload = function() { modal.classList.add('active'); };
<?php endif; ?>

modal.addEventListener('click', function(e) { if (e.target === this) closeRoleModal(); });
</script>

<?php include 'includes/admin-footer.php'; ?>