<?php
require_once 'auth.php';
requireAdmin();

$search = trim($_GET['q'] ?? '');
$where = $search ? " WHERE username LIKE '%" . $conn->real_escape_string($search) . "%'" : '';
$r = @$conn->query("SHOW COLUMNS FROM users LIKE 'created_at'");
$has_created = $r && $r->num_rows > 0;
$cols = $has_created ? "id, username, is_admin, can_edit, can_delete, can_export, created_at" : "id, username, is_admin, can_edit, can_delete, can_export";
$users = $conn->query("SELECT $cols FROM users $where ORDER BY id");
$total_users = $conn->query("SELECT COUNT(*) c FROM users")->fetch_assoc()['c'];
$admin_count = $conn->query("SELECT COUNT(*) c FROM users WHERE is_admin=1")->fetch_assoc()['c'];
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <?php include 'includes/favicon.php'; ?>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>المستخدمين والصلاحيات - نظام صيانة</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <link href="assets/css/dashboard.css" rel="stylesheet">
    <style>
        .users-stat-card { border-radius: 16px; transition: all 0.3s ease; border: none; overflow: hidden; position: relative; }
        .users-stat-card:hover { transform: translateY(-4px); box-shadow: 0 12px 28px rgba(0,0,0,0.12); }
        .users-stat-card .stat-icon { width: 52px; height: 52px; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 1.4rem; }
        .users-table thead th { background: linear-gradient(135deg, #1e3a5f 0%, #0f172a 100%) !important; color: #fff !important; font-weight: 600; border: none; padding: 1rem 1.25rem; }
        .users-table tbody td { padding: 1rem 1.25rem; vertical-align: middle; }
        .users-table tbody tr { transition: background 0.2s; }
        .users-table tbody tr:hover { background: linear-gradient(90deg, #f8fafc 0%, #fff 100%); }
        .users-table .badge { font-weight: 500; padding: 0.4em 0.75em; border-radius: 10px; font-size: 0.8rem; }
        .users-table .perm-cell { min-width: 90px; text-align: center; }
        /* نوافذ المستخدمين - استايل متطور */
        .users-modal .modal-content { border-radius: 20px; overflow: hidden; border: none; }
        .users-modal .modal-header { background: linear-gradient(135deg, #1e3a5f 0%, #0f172a 100%); color: #fff; padding: 1.25rem 1.5rem; }
        .users-modal .modal-title { font-weight: 600; font-size: 1.15rem; }
        .users-modal .modal-header .btn-close { filter: brightness(0) invert(1); opacity: 0.9; }
        .users-modal .modal-header .btn-close:hover { opacity: 1; }
        .users-modal .modal-body { padding: 1.5rem; background: #fafbfc; }
        .users-modal .modal-footer { background: #fff; padding: 1rem 1.5rem; border-top: 1px solid #e2e8f0; }
        .users-modal .form-label { color: #334155; font-size: 0.9rem; }
        .users-modal .form-control { border-radius: 12px; border: 1px solid #e2e8f0; padding: 0.6rem 1rem; }
        .users-modal .form-control:focus { border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59,130,246,0.15); }
        .users-modal .form-check-input { width: 1.2em; height: 1.2em; border-radius: 6px; }
        .users-modal .form-check-input:checked { background-color: #0d6efd; }
        .modal-add-section { background: #fff; border-radius: 14px; padding: 1rem 1.25rem; margin-bottom: 1rem; border: 1px solid #e2e8f0; box-shadow: 0 1px 3px rgba(0,0,0,0.04); }
        .modal-add-section.admin-section { background: linear-gradient(135deg, #fef2f2 0%, #fff5f5 100%); border-color: #fecaca; }
        .modal-add-section.perm-section { background: linear-gradient(135deg, #f0f9ff 0%, #f8fafc 100%); border-color: #bae6fd; }
        .modal-add-section .section-title { font-size: 0.75rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; margin-bottom: 0.75rem; }
        .perm-chip { display: inline-flex; align-items: center; padding: 0.55rem 1.1rem; border-radius: 12px; border: 1px solid #e2e8f0; background: #fff; transition: all 0.2s; cursor: pointer; }
        .perm-chip:hover { border-color: #93c5fd; background: #eff6ff; }
        .perm-chip input { display: none; }
        .perm-chip:has(input:checked) { border-color: #3b82f6; background: #eff6ff; box-shadow: 0 0 0 2px rgba(59,130,246,0.2); }
        .btn-add-user { border-radius: 12px; padding: 0.65rem 1.5rem; font-weight: 600; box-shadow: 0 4px 14px rgba(13,110,253,0.4); }
        .btn-add-user:hover { box-shadow: 0 6px 20px rgba(13,110,253,0.5); transform: translateY(-1px); }
        .btn-save-modal { border-radius: 12px; padding: 0.6rem 1.5rem; font-weight: 600; }
        .users-modal .form-switch .form-check-input { width: 2.5em; height: 1.25em; border-radius: 2em; }
        .users-modal .form-switch .form-check-input:checked { background-color: #dc3545; }
        .users-search-card { border-radius: 16px; border: 1px solid #e2e8f0; }
        .users-search-card .input-group .form-control { border-radius: 0 10px 10px 0; }
        .users-search-card .input-group-text { border-radius: 10px 0 0 10px; background: #f8fafc; }
    </style>
</head>
<body class="dashboard-body">
    <?php include 'includes/header.php'; ?>
    
    <div class="main-content">
        <div class="container-fluid py-4 px-4">
            <nav aria-label="breadcrumb" class="mb-3">
                <ol class="breadcrumb mb-0">
                    <li class="breadcrumb-item"><a href="dashboard.php">الرئيسية</a></li>
                    <li class="breadcrumb-item active">المستخدمين والصلاحيات</li>
                </ol>
            </nav>

            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
                <h2 class="page-title mb-0"><i class="bi bi-people-fill me-2"></i>المستخدمين والصلاحيات</h2>
                <button type="button" class="btn btn-primary btn-add-user" data-bs-toggle="modal" data-bs-target="#addUserModal">
                    <i class="bi bi-person-plus-fill me-2"></i>إضافة مستخدم
                </button>
            </div>

            <!-- بطاقات الإحصائيات -->
            <div class="row g-3 mb-4">
                <div class="col-md-4">
                    <div class="card users-stat-card border-0 shadow-sm h-100">
                        <div class="card-body d-flex align-items-center gap-3">
                            <div class="stat-icon bg-primary bg-opacity-10 text-primary">
                                <i class="bi bi-people"></i>
                            </div>
                            <div>
                                <p class="text-muted mb-0 small">إجمالي المستخدمين</p>
                                <h3 class="mb-0 fw-bold"><?= $total_users ?></h3>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card users-stat-card border-0 shadow-sm h-100">
                        <div class="card-body d-flex align-items-center gap-3">
                            <div class="stat-icon bg-danger bg-opacity-10 text-danger">
                                <i class="bi bi-shield-lock"></i>
                            </div>
                            <div>
                                <p class="text-muted mb-0 small">المدراء</p>
                                <h3 class="mb-0 fw-bold"><?= $admin_count ?></h3>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card users-stat-card border-0 shadow-sm h-100">
                        <div class="card-body d-flex align-items-center gap-3">
                            <div class="stat-icon bg-success bg-opacity-10 text-success">
                                <i class="bi bi-person-check"></i>
                            </div>
                            <div>
                                <p class="text-muted mb-0 small">مستخدمين عاديين</p>
                                <h3 class="mb-0 fw-bold"><?= $total_users - $admin_count ?></h3>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- البحث والجدول -->
            <div class="card users-search-card border-0 shadow-sm overflow-hidden">
                <div class="card-header bg-white py-3 d-flex flex-wrap align-items-center gap-3" style="border-bottom: 1px solid #e2e8f0;">
                    <h5 class="mb-0 fw-600"><i class="bi bi-list-ul me-2"></i>قائمة المستخدمين</h5>
                    <form method="GET" class="d-flex gap-2 flex-grow-1" style="max-width: 340px;">
                        <div class="input-group">
                            <span class="input-group-text bg-white"><i class="bi bi-search text-muted"></i></span>
                            <input type="text" name="q" class="form-control" placeholder="بحث عن مستخدم..." value="<?= htmlspecialchars($search) ?>">
                        </div>
                        <button type="submit" class="btn btn-outline-primary rounded-3"><i class="bi bi-search me-1"></i>بحث</button>
                    </form>
                </div>
                <div class="card-body p-0 overflow-auto">
                    <table class="table users-table mb-0">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>اسم المستخدم</th>
                                <th>الدور</th>
                                <th class="perm-cell">تعديل</th>
                                <th class="perm-cell">حذف</th>
                                <th class="perm-cell">تصدير</th>
                                <th>تاريخ الإضافة</th>
                                <th>إجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php while ($u = $users->fetch_assoc()): ?>
                        <tr class="align-middle">
                            <td class="text-muted"><?= $u['id'] ?></td>
                            <td class="fw-600">
                                <i class="bi bi-person-circle me-2 text-muted"></i>
                                <?= htmlspecialchars($u['username']) ?>
                            </td>
                            <td>
                                <?php if ($u['is_admin']): ?>
                                <span class="badge bg-danger"><i class="bi bi-shield-fill-check me-1"></i>مدير</span>
                                <?php else: ?>
                                <span class="badge bg-light text-dark border"><i class="bi bi-person me-1"></i>مستخدم</span>
                                <?php endif; ?>
                            </td>
                            <td class="perm-cell"><?= $u['can_edit'] ? '<i class="bi bi-check-circle-fill text-success" title="مسموح"></i>' : '<i class="bi bi-x-circle text-muted" title="غير مسموح"></i>' ?></td>
                            <td class="perm-cell"><?= $u['can_delete'] ? '<i class="bi bi-check-circle-fill text-success" title="مسموح"></i>' : '<i class="bi bi-x-circle text-muted" title="غير مسموح"></i>' ?></td>
                            <td class="perm-cell"><?= $u['can_export'] ? '<i class="bi bi-check-circle-fill text-success" title="مسموح"></i>' : '<i class="bi bi-x-circle text-muted" title="غير مسموح"></i>' ?></td>
                            <td class="text-muted small"><?= !empty($u['created_at']) ? date('Y-m-d', strtotime($u['created_at'])) : '—' ?></td>
                            <td>
                                <?php if ($u['id'] != 1): ?>
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-outline-primary btn-edit-user" 
                                        data-id="<?= $u['id'] ?>" data-username="<?= htmlspecialchars($u['username']) ?>"
                                        data-admin="<?= $u['is_admin'] ?>" data-edit="<?= $u['can_edit'] ?>" data-delete="<?= $u['can_delete'] ?>" data-export="<?= $u['can_export'] ?>"
                                        title="تعديل"><i class="bi bi-pencil"></i></button>
                                    <?php if ($u['id'] != $_SESSION['user_id']): ?>
                                    <button type="button" class="btn btn-outline-danger btn-del-user" data-id="<?= $u['id'] ?>" title="حذف"><i class="bi bi-trash"></i></button>
                                    <?php endif; ?>
                                </div>
                                <?php else: ?>
                                <span class="badge bg-secondary">محمي</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <?php if ($users->num_rows == 0): ?>
                <div class="text-center py-5 text-muted">
                    <i class="bi bi-search display-4 d-block mb-2"></i>
                    <p class="mb-0"><?= $search ? 'لا توجد نتائج لـ "' . htmlspecialchars($search) . '"' : 'لا يوجد مستخدمين' ?></p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- نافذة إضافة مستخدم -->
    <div class="modal fade users-modal" id="addUserModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content shadow">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-person-plus-fill me-2"></i>إضافة مستخدم جديد</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="modal-add-section">
                        <div class="section-title"><i class="bi bi-person-badge me-1"></i>بيانات الدخول</div>
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">اسم المستخدم</label>
                                <input type="text" id="new_username" class="form-control" placeholder="مثال: ahmed" required autocomplete="username">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">كلمة المرور</label>
                                <input type="password" id="new_password" class="form-control" minlength="6" placeholder="6 أحرف على الأقل" required autocomplete="new-password">
                            </div>
                        </div>
                    </div>
                    <div class="modal-add-section admin-section">
                        <div class="section-title"><i class="bi bi-shield-lock me-1"></i>الدور</div>
                        <div class="form-check form-switch">
                            <input type="checkbox" class="form-check-input" id="new_is_admin">
                            <label class="form-check-label fw-600" for="new_is_admin">مدير النظام</label>
                            <small class="d-block text-muted mt-1" style="font-size: 0.8rem;">صلاحيات كاملة: إدارة المستخدمين والإعدادات والصلاحيات</small>
                        </div>
                    </div>
                    <div class="modal-add-section perm-section" id="new_perm_box">
                        <div class="section-title"><i class="bi bi-key me-1"></i>صلاحيات المستخدم</div>
                        <div class="d-flex flex-wrap gap-2">
                            <label class="perm-chip">
                                <input type="checkbox" id="new_can_edit" checked>
                                <span><i class="bi bi-pencil text-primary me-1"></i>تعديل</span>
                            </label>
                            <label class="perm-chip">
                                <input type="checkbox" id="new_can_delete" checked>
                                <span><i class="bi bi-trash text-danger me-1"></i>حذف</span>
                            </label>
                            <label class="perm-chip">
                                <input type="checkbox" id="new_can_export" checked>
                                <span><i class="bi bi-file-excel text-success me-1"></i>تصدير</span>
                            </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">إلغاء</button>
                    <button type="button" class="btn btn-primary btn-save-modal" id="saveNewUser"><i class="bi bi-plus-lg me-2"></i>إضافة</button>
                </div>
            </div>
        </div>
    </div>

    <!-- نافذة تعديل مستخدم -->
    <div class="modal fade users-modal" id="editUserModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content shadow">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-pencil-square me-2"></i>تعديل المستخدم</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="edit_user_id">
                    <div class="modal-add-section">
                        <div class="section-title"><i class="bi bi-person-badge me-1"></i>البيانات</div>
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">اسم المستخدم</label>
                                <input type="text" id="edit_username" class="form-control bg-light" readonly>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">كلمة مرور جديدة</label>
                                <input type="password" id="edit_password" class="form-control" minlength="6" placeholder="فارغة = لا تغيير" autocomplete="new-password">
                            </div>
                        </div>
                    </div>
                    <div class="modal-add-section admin-section">
                        <div class="section-title"><i class="bi bi-shield-lock me-1"></i>الدور</div>
                        <div class="form-check form-switch">
                            <input type="checkbox" class="form-check-input" id="edit_is_admin">
                            <label class="form-check-label fw-600" for="edit_is_admin">مدير النظام</label>
                        </div>
                    </div>
                    <div class="modal-add-section perm-section" id="edit_perm_box">
                        <div class="section-title"><i class="bi bi-key me-1"></i>صلاحيات المستخدم</div>
                        <div class="d-flex flex-wrap gap-2">
                            <label class="perm-chip">
                                <input type="checkbox" id="edit_can_edit">
                                <span><i class="bi bi-pencil text-primary me-1"></i>تعديل</span>
                            </label>
                            <label class="perm-chip">
                                <input type="checkbox" id="edit_can_delete">
                                <span><i class="bi bi-trash text-danger me-1"></i>حذف</span>
                            </label>
                            <label class="perm-chip">
                                <input type="checkbox" id="edit_can_export">
                                <span><i class="bi bi-file-excel text-success me-1"></i>تصدير</span>
                            </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">إلغاء</button>
                    <button type="button" class="btn btn-primary btn-save-modal" id="saveEditUser"><i class="bi bi-check-lg me-2"></i>حفظ</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    function togglePermBox(add) {
        const box = document.getElementById(add ? 'new_perm_box' : 'edit_perm_box');
        const admin = document.getElementById(add ? 'new_is_admin' : 'edit_is_admin');
        box.style.opacity = admin.checked ? '0.5' : '1';
        box.querySelectorAll('input[type="checkbox"]').forEach(cb => { cb.disabled = admin.checked; if (admin.checked) cb.checked = true; });
    }
    document.getElementById('new_is_admin').onchange = () => togglePermBox(true);
    document.getElementById('edit_is_admin').onchange = () => togglePermBox(false);
    document.querySelectorAll('.btn-edit-user').forEach(btn=>{
        btn.onclick = function() {
            document.getElementById('edit_user_id').value = this.dataset.id;
            document.getElementById('edit_username').value = this.dataset.username;
            document.getElementById('edit_password').value = '';
            document.getElementById('edit_is_admin').checked = !!parseInt(this.dataset.admin);
            document.getElementById('edit_can_edit').checked = !!parseInt(this.dataset.edit);
            document.getElementById('edit_can_delete').checked = !!parseInt(this.dataset.delete);
            document.getElementById('edit_can_export').checked = !!parseInt(this.dataset.export);
            togglePermBox(false);
            new bootstrap.Modal(document.getElementById('editUserModal')).show();
        };
    });
    document.getElementById('addUserModal').addEventListener('show.bs.modal', () => togglePermBox(true));
    document.getElementById('saveNewUser').onclick = function() {
        const fd = new FormData();
        fd.append('action', 'create');
        fd.append('username', document.getElementById('new_username').value.trim());
        fd.append('password', document.getElementById('new_password').value);
        if (document.getElementById('new_is_admin').checked) fd.append('is_admin', '1');
        if (document.getElementById('new_can_edit').checked) fd.append('can_edit', '1');
        if (document.getElementById('new_can_delete').checked) fd.append('can_delete', '1');
        if (document.getElementById('new_can_export').checked) fd.append('can_export', '1');
        if (window.csrfToken) fd.append('csrf_token', window.csrfToken);
        fetch('api/users.php', { method: 'POST', body: fd }).then(r=>r.json()).then(d=>{
            if (d.success) location.reload();
            else alert(d.message || 'فشل');
        });
    };
    document.getElementById('saveEditUser').onclick = function() {
        const fd = new FormData();
        fd.append('action', 'update');
        fd.append('id', document.getElementById('edit_user_id').value);
        fd.append('password', document.getElementById('edit_password').value);
        if (document.getElementById('edit_is_admin').checked) fd.append('is_admin', '1');
        if (document.getElementById('edit_can_edit').checked) fd.append('can_edit', '1');
        if (document.getElementById('edit_can_delete').checked) fd.append('can_delete', '1');
        if (document.getElementById('edit_can_export').checked) fd.append('can_export', '1');
        if (window.csrfToken) fd.append('csrf_token', window.csrfToken);
        fetch('api/users.php', { method: 'POST', body: fd }).then(r=>r.json()).then(d=>{
            if (d.success) location.reload();
            else alert(d.message || 'فشل');
        });
    };
    document.querySelectorAll('.btn-del-user').forEach(btn=>{
        btn.onclick = function() {
            if (confirm('حذف هذا المستخدم؟ سيُحرم من الدخول للنظام.')) {
                const u = 'api/users.php?action=delete&id='+this.dataset.id + (window.csrfToken ? '&csrf_token='+window.csrfToken : '');
                fetch(u).then(r=>r.json()).then(d=>{
                    if (d.success) location.reload();
                    else alert(d.message);
                });
            }
        };
    });
    </script>
    <?php include 'includes/footer.php'; ?>
</body>
</html>
