<?php
// ===============================================
// قسم الإعدادات والتحقق من الصلاحيات
// ===============================================
$pageTitle = 'إدارة المستخدمين';
include '../../includes/header.php';

checkLogin();
if (!hasPermission('view_users')) {
    $_SESSION['error_message'] = 'ليس لديك صلاحية لعرض هذه الصفحة.';
    header('Location: ../../index.php');
    exit();
}

$db = getDB();

// ===============================================
// قسم معالجة طلبات الإجراءات (نفس منطقك الأصلي تماماً)
// ===============================================

// 1. حذف المستخدم
if (isset($_GET['delete']) && hasPermission('delete_users')) {
    $userId = (int)$_GET['delete'];
    if ($userId !== $_SESSION['user_id']) {
        try {
            $db->beginTransaction();
            $db->update("UPDATE employees SET user_id = NULL WHERE user_id = ?", [$userId]);
            $db->delete("DELETE FROM document_tracking WHERE tracked_by_user_id = ?", [$userId]);
            $db->delete("DELETE FROM user_roles WHERE user_id = ?", [$userId]);
            $db->delete("DELETE FROM users WHERE id = ?", [$userId]);
            $db->commit();
            $_SESSION['success_message'] = 'تم حذف المستخدم بنجاح.';
        } catch (Exception $e) { $db->rollBack(); }
    }
    header('Location: index.php'); exit();
}

// 2. تفعيل/تعطيل
if (isset($_GET['toggle_active']) && hasPermission('edit_users')) {
    $userId = (int)$_GET['toggle_active'];
    if ($userId !== $_SESSION['user_id']) {
        $user = $db->selectOne("SELECT is_active FROM users WHERE id = ?", [$userId]);
        if ($user) {
            $db->update("UPDATE users SET is_active = ? WHERE id = ?", [!$user['is_active'], $userId]);
            $_SESSION['success_message'] = 'تم تغيير حالة النشاط بنجاح.';
        }
    }
    header('Location: index.php'); exit();
}

// 3. إظهار/إخفاء
if (isset($_GET['toggle_hidden']) && hasPermission('hide_users')) {
    $userId = (int)$_GET['toggle_hidden'];
    if ($userId !== $_SESSION['user_id']) {
        $user = $db->selectOne("SELECT is_hidden FROM users WHERE id = ?", [$userId]);
        if ($user) {
            $db->update("UPDATE users SET is_hidden = ? WHERE id = ?", [!$user['is_hidden'], $userId]);
            $_SESSION['success_message'] = 'تم تغيير حالة الإخفاء بنجاح.';
        }
    }
    header('Location: index.php'); exit();
}

// ===============================================
// قسم جلب البيانات
// ===============================================
$search = $_GET['search'] ?? '';
$hiddenStatus = $_GET['hidden_status'] ?? 'visible';
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 10;
$offset = ($page - 1) * $limit;

$whereClause = '1';
$params = [];
if (!empty($search)) {
    $whereClause .= " AND (u.username LIKE ? OR u.full_name LIKE ? OR u.email LIKE ?)";
    $searchTerm = "%{$search}%";
    $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm]);
}
if ($hiddenStatus === 'visible') $whereClause .= " AND u.is_hidden = 0";
elseif ($hiddenStatus === 'hidden') $whereClause .= " AND u.is_hidden = 1";

$users = $db->select("SELECT u.*, GROUP_CONCAT(r.role_name SEPARATOR ', ') as roles FROM users u LEFT JOIN user_roles ur ON u.id = ur.user_id LEFT JOIN roles r ON ur.role_id = r.id WHERE {$whereClause} GROUP BY u.id ORDER BY u.created_at DESC LIMIT {$limit} OFFSET {$offset}", $params);
$totalUsers = $db->selectOne("SELECT COUNT(DISTINCT u.id) as count FROM users u WHERE {$whereClause}", $params)['count'];
$totalPages = ceil($totalUsers / $limit);
?>

<div class="content-area">
    <div class="page-header mb-4">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h2 class="page-title fw-bold text-primary">إدارة المستخدمين</h2>
                <p class="text-muted small">تحديث تلقائي عند البحث أو تغيير الحالة</p>
            </div>
            <div class="d-flex gap-2">
                <?php if (hasPermission('create_users')): ?>
                    <a href="create.php" class="btn btn-primary"><i class="fas fa-user-plus me-1"></i> إضافة مستخدم</a>
                <?php endif; ?>
                <?php if (hasPermission('view_sessions')): ?>
                    <a href="active_users.php" class="btn btn-outline-info"><i class="fas fa-history me-1"></i> الجلسات</a>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="card shadow-sm mb-4 border-0">
        <div class="card-body bg-light rounded">
            <form method="GET" id="autoFilterForm" class="row g-3">
                <div class="col-md-8">
                    <div class="input-group">
                        <span class="input-group-text bg-white"><i class="fas fa-search text-muted"></i></span>
                        <input type="text" name="search" id="searchInput" class="form-control" 
                               placeholder="ابحث بالاسم، البريد، أو اسم المستخدم..." 
                               value="<?= htmlspecialchars($search) ?>" autocomplete="off">
                    </div>
                </div>
                <div class="col-md-4">
                    <select name="hidden_status" id="statusSelect" class="form-select fw-bold">
                        <option value="visible" <?= $hiddenStatus === 'visible' ? 'selected' : '' ?>>👤 المستخدمين المرئيين</option>
                        <option value="hidden" <?= $hiddenStatus === 'hidden' ? 'selected' : '' ?>>👻 المستخدمين المخفيين</option>
                        <option value="all" <?= $hiddenStatus === 'all' ? 'selected' : '' ?>>🌍 عرض الكل</option>
                    </select>
                </div>
            </form>
        </div>
    </div>

    <div class="card shadow-sm border-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th>المستخدم</th>
                        <th>البريد</th>
                        <th>الأدوار</th>
                        <th>الحالة</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                    <tr>
                        <td>
                            <div class="d-flex align-items-center">
                                <span class="avatar-circle me-2"><?= mb_substr($user['full_name'], 0, 1, 'UTF-8') ?></span>
                                <div>
                                    <div class="fw-bold"><?= htmlspecialchars($user['full_name']) ?></div>
                                    <small class="text-muted">@<?= htmlspecialchars($user['username']) ?></small>
                                </div>
                            </div>
                        </td>
                        <td><?= htmlspecialchars($user['email']) ?></td>
                        <td>
                            <?php if ($user['roles']): ?>
                                <?php foreach (explode(', ', $user['roles']) as $role): ?>
                                    <span class="badge bg-info-subtle text-info small"><?= $role ?></span>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="badge rounded-pill <?= $user['is_active'] ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger' ?>">
                                <?= $user['is_active'] ? 'نشط' : 'معطل' ?>
                            </span>
                            <?php if ($user['is_hidden']): ?>
                                <span class="badge rounded-pill bg-secondary-subtle text-secondary small">مخفي</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                <?php if (hasPermission('edit_users')): ?>
                                    <a href="edit.php?id=<?= $user['id'] ?>" class="btn btn-outline-primary" title="تعديل"><i class="fas fa-edit"></i></a>
                                <?php endif; ?>
                                
                     

                                <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                    <?php if (hasPermission('edit_users')): ?>
                                        <button class="btn btn-outline-warning" data-bs-toggle="modal" data-bs-target="#confirmModal" 
                                                data-url="?toggle_active=<?= $user['id'] ?>" 
                                                data-msg="هل تريد <?= $user['is_active'] ? 'تعطيل' : 'تفعيل' ?> هذا الحساب؟">
                                            <i class="fas fa-<?= $user['is_active'] ? 'user-slash' : 'user-check' ?>"></i>
                                        </button>
                                    <?php endif; ?>

                                    <?php if (hasPermission('hide_users')): ?>
                                        <button class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#confirmModal" 
                                                data-url="?toggle_hidden=<?= $user['id'] ?>" 
                                                data-msg="هل تريد <?= $user['is_hidden'] ? 'إظهار' : 'إخفاء' ?> هذا المستخدم؟">
                                            <i class="fas fa-<?= $user['is_hidden'] ? 'eye' : 'eye-slash' ?>"></i>
                                        </button>
                                    <?php endif; ?>

                                    <?php if (hasPermission('delete_users')): ?>
                                        <button class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#confirmModal" 
                                                data-url="?delete=<?= $user['id'] ?>" 
                                                data-msg="سيتم حذف المستخدم وجميع سجلاته نهائياً. هل أنت متأكد؟">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="confirmModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-body text-center p-4">
                <i class="fas fa-exclamation-circle fa-3x text-warning mb-3"></i>
                <h5 id="modalMsg">هل أنت متأكد؟</h5>
                <div class="mt-4">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">إلغاء</button>
                    <a href="#" id="confirmBtn" class="btn btn-primary">تأكيد الإجراء</a>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const filterForm = document.getElementById('autoFilterForm');
    const searchInput = document.getElementById('searchInput');
    const statusSelect = document.getElementById('statusSelect');

    // التصفية التلقائية
    statusSelect.addEventListener('change', () => filterForm.submit());
    
    let typingTimer;
    searchInput.addEventListener('input', () => {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(() => filterForm.submit(), 500);
    });

    // تركيز النص
    if (searchInput.value.length > 0) {
        searchInput.focus();
        searchInput.setSelectionRange(searchInput.value.length, searchInput.value.length);
    }

    // إدارة المودال
    const confirmModal = document.getElementById('confirmModal');
    confirmModal.addEventListener('show.bs.modal', function (event) {
        const btn = event.relatedTarget;
        document.getElementById('modalMsg').textContent = btn.getAttribute('data-msg');
        document.getElementById('confirmBtn').href = btn.getAttribute('data-url');
        
        // تغيير لون زر التأكيد إذا كان حذفاً
        const isDelete = btn.getAttribute('data-url').includes('delete');
        document.getElementById('confirmBtn').className = isDelete ? 'btn btn-danger' : 'btn btn-primary';
    });
});
</script>

<style>
    .avatar-circle { width: 35px; height: 35px; background: #007bff; color: #fff; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; }
    .bg-success-subtle { background-color: #d1e7dd; color: #0f5132; }
    .bg-danger-subtle { background-color: #f8d7da; color: #842029; }
    .bg-info-subtle { background-color: #cff4fc; color: #055160; }
    .bg-secondary-subtle { background-color: #e2e3e5; color: #41464b; }
</style>

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