<?php
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
require_once 'includes/translation.php';
require_once 'includes/page_permissions_helper.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    redirect('login.php');
}

// Set current page for permissions
$currentPage = 'users';

// Check page access permission
PagePermissions::requirePageAccess($currentPage);

$db = new Database();
$conn = $db->getConnection();

// Fix role column if it's ENUM or too short
try {
    $conn->exec("ALTER TABLE users MODIFY COLUMN role VARCHAR(50)");
} catch (Exception $e) {
    // Silently fail if we can't alter
}

// Load page permissions configuration
$pagePermissionsConfig = json_decode(file_get_contents('config/pages_permissions.json'), true);

$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action == 'add') {
        $username = trim($_POST['username']);
        $email = trim($_POST['email']);
        $password = $_POST['password'];
        $full_name = trim($_POST['full_name']);
        $role = $_POST['role'];
        
        try {
            // Check if username exists
            $stmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
            $stmt->execute([$username]);
            
            if ($stmt->rowCount() > 0) {
                $error = 'اسم المستخدم موجود بالفعل';
            } else {
                // Insert new user (without old permissions)
                $sql = "INSERT INTO users (username, email, password, full_name, role, is_active) VALUES (?, ?, ?, ?, ?, 1)";
                
                $stmt = $conn->prepare($sql);
                $stmt->execute([$username, $email, $password, $full_name, $role]);
                
                // Log activity
                $new_user_id = $conn->lastInsertId();
                
                // Save page permissions
                if (isset($_POST['page_permissions']) && is_array($_POST['page_permissions'])) {
                    $stmt_perm = $conn->prepare("INSERT INTO user_page_permissions (user_id, page_name, permission_key, granted_by) VALUES (?, ?, ?, ?)");
                    foreach ($_POST['page_permissions'] as $permission) {
                        list($page, $permKey) = explode(':', $permission);
                        $stmt_perm->execute([$new_user_id, $page, $permKey, $_SESSION['user_id']]);
                    }
                }
                
                logActivity($conn, $_SESSION['user_id'], 'إضافة مستخدم جديد', 'users', $new_user_id);
                
                $message = 'تم إضافة المستخدم بنجاح';
            }
        } catch (Exception $e) {
            $error = 'خطأ في إضافة المستخدم: ' . $e->getMessage();
        }
    }
    
    if ($action == 'edit') {
        $id = intval($_POST['user_id']);
        $username = trim($_POST['username']);
        $email = trim($_POST['email']);
        $full_name = trim($_POST['full_name']);
        $role = $_POST['role'];
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        try {
            // Check if username exists for another user
            $stmt = $conn->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
            $stmt->execute([$username, $id]);
            
            if ($stmt->rowCount() > 0) {
                $error = 'اسم المستخدم موجود بالفعل';
            } else {
                if (!empty($_POST['password'])) {
                    $password = $_POST['password'];
                    $sql = "UPDATE users SET username=?, email=?, password=?, full_name=?, role=?, is_active=? WHERE id=?";
                    $params = [$username, $email, $password, $full_name, $role, $is_active, $id];
                } else {
                    $sql = "UPDATE users SET username=?, email=?, full_name=?, role=?, is_active=? WHERE id=?";
                    $params = [$username, $email, $full_name, $role, $is_active, $id];
                }
                
                $stmt = $conn->prepare($sql);
                $stmt->execute($params);
                
                // Update page permissions
                // Delete old permissions
                $stmt_del = $conn->prepare("DELETE FROM user_page_permissions WHERE user_id = ?");
                $stmt_del->execute([$id]);
                
                // Insert new permissions
                if (isset($_POST['page_permissions']) && is_array($_POST['page_permissions'])) {
                    $stmt_perm = $conn->prepare("INSERT INTO user_page_permissions (user_id, page_name, permission_key, granted_by) VALUES (?, ?, ?, ?)");
                    foreach ($_POST['page_permissions'] as $permission) {
                        list($page, $permKey) = explode(':', $permission);
                        $stmt_perm->execute([$id, $page, $permKey, $_SESSION['user_id']]);
                    }
                }
                
                // Log activity
                logActivity($conn, $_SESSION['user_id'], 'تحديث بيانات المستخدم', 'users', $id);
                
                $message = 'تم تحديث المستخدم بنجاح';
            }
        } catch (Exception $e) {
            $error = 'خطأ في التحديث: ' . $e->getMessage();
        }
    }
    
    if ($action == 'delete') {
        $id = intval($_POST['user_id']);
        
        if ($id != $_SESSION['user_id']) {
            try {
                $conn->beginTransaction();

                // 1. Delete all dependencies first (Cascade Delete)
                $tables_to_clean = [
                    ['table' => 'antibiotic_reports', 'column' => 'reporting_pharmacist_id'],
                    ['table' => 'pharmacy_handover_forms', 'column' => 'created_by'],
                    ['table' => 'icu_daily_reports', 'column' => 'created_by'],
                    ['table' => 'nursery_pediatric_reports', 'column' => 'created_by'],
                    ['table' => 'patients', 'column' => 'created_by'],
                    ['table' => 'internal_reports', 'column' => 'created_by'],
                    ['table' => 'breakage_reports', 'column' => 'reported_by'],
                    ['table' => 'narcotic_disposal_reports', 'column' => 'reported_by'],
                    ['table' => 'expired_drugs_disposal', 'column' => 'reported_by'],
                    ['table' => 'clinical_pharmacy_forms', 'column' => 'created_by'],
                    ['table' => 'user_page_permissions', 'column' => 'user_id'],
                    ['table' => 'notifications', 'column' => 'user_id'],
                    ['table' => 'activity_log', 'column' => 'user_id']
                ];

                foreach ($tables_to_clean as $dep) {
                    $del_stmt = $conn->prepare("DELETE FROM {$dep['table']} WHERE {$dep['column']} = ?");
                    $del_stmt->execute([$id]);
                }

                // 2. Finally delete the user
                $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
                $stmt->execute([$id]);
                
                $conn->commit();
                $message = 'تم حذف المستخدم وكافة سجلاته المرتبطة بنجاح (تنظيف كامل)';
            } catch (Exception $e) {
                if ($conn->inTransaction()) {
                    $conn->rollBack();
                }
                $error = 'خطأ في الحذف الإجباري: ' . $e->getMessage();
            }
        } else {
            $error = 'لا يمكنك حذف حسابك الخاص';
        }
    }
    
    if ($action == 'toggle_status') {
        $id = intval($_POST['user_id']);
        
        try {
            $stmt = $conn->prepare("UPDATE users SET is_active = NOT is_active WHERE id = ?");
            $stmt->execute([$id]);
            
            // Log activity
            logActivity($conn, $_SESSION['user_id'], 'تغيير حالة المستخدم', 'users', $id);
            
            $message = 'تم تغيير حالة المستخدم بنجاح';
        } catch (Exception $e) {
            $error = 'خطأ في تغيير الحالة: ' . $e->getMessage();
        }
    }
}

// Get all users with pagination
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 20;
$offset = ($page - 1) * $per_page;

try {
    $total_stmt = $conn->query("SELECT COUNT(*) as total FROM users");
    $total_users = $total_stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    $stmt = $conn->prepare("SELECT * FROM users ORDER BY id DESC LIMIT :limit OFFSET :offset");
    $stmt->bindValue(':limit', $per_page, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $total_pages = ceil($total_users / $per_page);
} catch (Exception $e) {
    $users = [];
    $total_pages = 0;
    $error = 'خطأ في جلب البيانات';
}

// Get statistics
$stats = [];
try {
    $stmt = $conn->query("
        SELECT 
            COUNT(*) as total_users,
            SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_users,
            SUM(CASE WHEN role = 'admin' THEN 1 ELSE 0 END) as admin_count,
            SUM(CASE WHEN role = 'pharmacist' THEN 1 ELSE 0 END) as pharmacist_count,
            SUM(CASE WHEN role = 'secretary' THEN 1 ELSE 0 END) as secretary_count,
            SUM(CASE WHEN role = 'pharmacy_assistant' THEN 1 ELSE 0 END) as pharmacy_assistant_count
        FROM users
    ");
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $stats = ['total_users' => 0, 'active_users' => 0, 'admin_count' => 0, 'pharmacist_count' => 0];
}

// Set page title
$page_title = 'إدارة المستخدمين والصلاحيات - ' . __('system_name');

// Include header
include 'includes/header.php';
?>

<style>
.cursor-pointer {
    cursor: pointer;
}
.user-card {
    background: white;
    border-radius: 15px;
    padding: 25px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    margin-bottom: 20px;
    transition: transform 0.3s ease;
}

.user-card:hover {
    transform: translateY(-5px);
}

.badge-admin { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
.badge-pharmacist { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; }
.badge-doctor { background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%); color: #333; }
.badge-nurse { background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%); color: #333; }
.badge-secretary { background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%); color: #333; }
.badge-pharmacy_assistant { background: linear-gradient(135deg, #fdfcfb 0%, #e2d1c3 100%); color: #333; }
.badge-active { background: #28a745; color: white; }
.badge-inactive { background: #dc3545; color: white; }

.stat-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 15px;
    padding: 25px;
    margin-bottom: 20px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.stat-number {
    font-size: 2.5rem;
    font-weight: bold;
}

.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    overflow-y: auto;
}

.modal-content {
    background: white;
    margin: 2% auto;
    padding: 30px;
    border-radius: 15px;
    width: 95%;
    max-width: 700px;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: 0 10px 40px rgba(0,0,0,0.3);
    animation: modalSlideIn 0.3s ease;
}

@keyframes modalSlideIn {
    from {
        opacity: 0;
        transform: translateY(-50px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.modal-header {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 2px solid #ddd;
}

.modal-header h2 {
    color: #2c3e50;
    margin: 0;
}

.close {
    float: left;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
    color: #999;
    line-height: 1;
}

.close:hover { 
    color: #333; 
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: 600;
    color: #555;
}

.form-group input:not([type="checkbox"]):not([type="radio"]), .form-group select {
    width: 100%;
    padding: 12px;
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    font-size: 14px;
}

.form-group input:focus, .form-group select:focus {
    outline: none;
    border-color: #667eea;
}
@media (max-width: 768px) {
    .modal-content {
        padding: 20px 15px;
        margin: 5% auto;
        width: 95%;
    }
    .modal-header h2 {
        font-size: 1.25rem;
    }
}
</style>

<!-- Main Content -->

    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
        <h1 class="h3 mb-0">👥 إدارة المستخدمين والصلاحيات</h1>
        <div class="d-flex gap-2">
            <button onclick="toggleView()" id="viewToggleBtn" class="btn btn-secondary">
                <span id="viewIcon">🎴</span> <span id="viewText">عرض كروت</span>
            </button>
            <button onclick="openAddModal()" class="btn btn-success">➕ إضافة مستخدم جديد</button>
        </div>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            ✅ <?= htmlspecialchars($message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            ❌ <?= htmlspecialchars($error) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Statistics -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="stat-card">
                <div class="stat-number"><?= $stats['total_users'] ?></div>
                <div>إجمالي المستخدمين</div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);">
                <div class="stat-number"><?= $stats['active_users'] ?></div>
                <div>المستخدمين النشطين</div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%); color: #333;">
                <div class="stat-number"><?= $stats['admin_count'] ?></div>
                <div>المديرين</div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%); color: #333;">
                <div class="stat-number"><?= $stats['pharmacist_count'] ?></div>
                <div>الصيادلة</div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%); color: #333;">
                <div class="stat-number"><?= $stats['secretary_count'] ?? 0 ?></div>
                <div>السكرتارية</div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="background: linear-gradient(135deg, #fdfcfb 0%, #e2d1c3 100%); color: #333;">
                <div class="stat-number"><?= $stats['pharmacy_assistant_count'] ?? 0 ?></div>
                <div>مساعد صيدلي</div>
            </div>
        </div>
    </div>

    <!-- Cards View -->
    <div id="cardsView" style="display: none;">
        <div class="row">
            <?php foreach ($users as $user): ?>
                <div class="col-lg-4 col-md-6">
                    <div class="user-card">
                        <div class="d-flex align-items-center gap-3 mb-3">
                            <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; width: 60px; height: 60px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 28px; font-weight: 700;">
                                <?= strtoupper(mb_substr($user['full_name'], 0, 1)) ?>
                            </div>
                            <div class="flex-grow-1">
                                <h4 class="mb-0"><?= htmlspecialchars($user['full_name']) ?></h4>
                                <p class="text-muted small mb-0">@<?= htmlspecialchars($user['username']) ?></p>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <div class="d-flex justify-content-between mb-2">
                                <span class="text-muted">البريد الإلكتروني:</span>
                                <span class="small"><?= htmlspecialchars($user['email']) ?></span>
                            </div>
                            <div class="d-flex justify-content-between mb-2">
                                <span class="text-muted">الدور:</span>
                                <span class="badge badge-<?= $user['role'] ?>">
                                    <?php
                                    $roles = [
                                        'admin' => '👑 مدير', 
                                        'pharmacist' => '💊 صيدلي', 
                                        'doctor' => '👨‍⚕️ طبيب', 
                                        'nurse' => '👩‍⚕️ ممرض',
                                        'secretary' => '⌨️ سكرتارية',
                                        'pharmacy_assistant' => '💊 مساعد صيدلي'
                                    ];
                                    echo $roles[$user['role']] ?? ($user['role'] ?: '<span class="text-danger">⚠️ غير محدد</span>');
                                    ?>
                                </span>
                            </div>
                            <div class="d-flex justify-content-between mb-2">
                                <span class="text-muted">الحالة:</span>
                                <span class="badge badge-<?= $user['is_active'] ? 'active' : 'inactive' ?>">
                                    <?= $user['is_active'] ? '✅ نشط' : '❌ معطل' ?>
                                </span>
                            </div>
                            <div class="d-flex justify-content-between">
                                <span class="text-muted">تاريخ الإنشاء:</span>
                                <span class="fw-bold small"><?= date('Y/m/d', strtotime($user['created_at'])) ?></span>
                            </div>
                        </div>
                        
                        <!-- Permissions Summary -->
                        <div class="bg-light p-3 rounded mb-3">
                            <h6 class="mb-2">🔐 الصلاحيات الممنوحة:</h6>
                            <?php
                            // Get page permissions count
                            $stmt_page_perms = $conn->prepare("SELECT COUNT(*) as count FROM user_page_permissions WHERE user_id = ?");
                            $stmt_page_perms->execute([$user['id']]);
                            $page_perms_count = $stmt_page_perms->fetch(PDO::FETCH_ASSOC)['count'];
                            
                            // Total permissions
                            $total_page_perms = 0;
                            foreach ($pagePermissionsConfig['pages'] as $page) {
                                $total_page_perms += count($page['permissions']);
                            }
                            
                            $percentage = $total_page_perms > 0 ? ($page_perms_count / $total_page_perms) * 100 : 0;
                            $color = $percentage > 70 ? '#38ef7d' : ($percentage > 40 ? '#ffd700' : '#e74c3c');
                            ?>
                            <div class="text-center">
                                <div class="mb-2">
                                    <span class="badge" style="background: <?= $color ?>; color: white; font-size: 16px; padding: 10px 20px;">
                                        <?= $page_perms_count ?> / <?= $total_page_perms ?>
                                    </span>
                                </div>
                                <div class="progress" style="height: 20px;">
                                    <div class="progress-bar" role="progressbar" style="width: <?= $percentage ?>%; background: <?= $color ?>;" aria-valuenow="<?= $percentage ?>" aria-valuemin="0" aria-valuemax="100">
                                        <?= round($percentage, 1) ?>%
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="d-flex gap-2">
                            <button onclick='openEditModal(<?= json_encode($user, JSON_HEX_APOS | JSON_HEX_QUOT) ?>)' class="btn btn-warning btn-sm flex-fill">✏️ تعديل</button>
                            <button onclick="toggleStatus(<?= $user['id'] ?>)" class="btn btn-info btn-sm flex-fill">
                                <?= $user['is_active'] ? '🔒 تعطيل' : '✅ تفعيل' ?>
                            </button>
                            <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                <button onclick="deleteUser(<?= $user['id'] ?>)" class="btn btn-danger btn-sm">🗑️</button>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Table View -->
    <div id="tableView" style="display: block;">
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-primary">
                            <tr>
                                <th style="width: 50px;">#</th>
                                <th>الاسم الكامل</th>
                                <th>اسم المستخدم</th>
                                <th>البريد الإلكتروني</th>
                                <th>الدور</th>
                                <th>الحالة</th>
                                <th>الصلاحيات النشطة</th>
                                <th>تاريخ الإنشاء</th>
                                <th style="width: 200px;">إجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($users as $user): ?>
                                <tr>
                                    <td><?= $user['id'] ?></td>
                                    <td><strong><?= htmlspecialchars($user['full_name']) ?></strong></td>
                                    <td><code class="bg-light p-1 border rounded" style="color: #e83e8c; font-weight: bold;"><?= htmlspecialchars($user['username']) ?></code></td>
                                    <td><?= htmlspecialchars($user['email']) ?></td>
                                    <td>
                                        <span class="badge badge-<?= $user['role'] ?>">
                                            <?php
                                            $roles = [
                                                'admin' => '👑 مدير', 
                                                'pharmacist' => '💊 صيدلي', 
                                                'doctor' => '👨‍⚕️ طبيب', 
                                                'nurse' => '👩‍⚕️ ممرض',
                                                'secretary' => '⌨️ سكرتارية',
                                                'pharmacy_assistant' => '💊 مساعد صيدلي'
                                            ];
                                            echo $roles[$user['role']] ?? ($user['role'] ?: '<span class="text-danger">⚠️ غير محدد</span>');
                                            ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge badge-<?= $user['is_active'] ? 'active' : 'inactive' ?>">
                                            <?= $user['is_active'] ? '✅ نشط' : '❌ معطل' ?>
                                        </span>
                                    </td>
                                    <td class="text-center">
                                        <?php
                                        // Get page permissions count
                                        $stmt_page_perms = $conn->prepare("SELECT COUNT(*) as count FROM user_page_permissions WHERE user_id = ?");
                                        $stmt_page_perms->execute([$user['id']]);
                                        $page_perms_count = $stmt_page_perms->fetch(PDO::FETCH_ASSOC)['count'];
                                        
                                        // Total permissions
                                        $total_page_perms = 0;
                                        foreach ($pagePermissionsConfig['pages'] as $page) {
                                            $total_page_perms += count($page['permissions']);
                                        }
                                        
                                        $percentage = $total_page_perms > 0 ? ($page_perms_count / $total_page_perms) * 100 : 0;
                                        $color = $percentage > 70 ? '#38ef7d' : ($percentage > 40 ? '#ffd700' : '#e74c3c');
                                        ?>
                                        <span class="badge" style="background: <?= $color ?>; color: white; font-size: 13px;">
                                            <?= $page_perms_count ?> / <?= $total_page_perms ?>
                                        </span>
                                    </td>
                                    <td><?= date('Y/m/d', strtotime($user['created_at'])) ?></td>
                                    <td>
                                        <button onclick='openEditModal(<?= json_encode($user, JSON_HEX_APOS | JSON_HEX_QUOT) ?>)' class="btn btn-warning btn-sm">✏️</button>
                                        <button onclick="toggleStatus(<?= $user['id'] ?>)" class="btn btn-info btn-sm">
                                            <?= $user['is_active'] ? '🔒' : '✅' ?>
                                        </button>
                                        <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                            <button onclick="deleteUser(<?= $user['id'] ?>)" class="btn btn-danger btn-sm">🗑️</button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Pagination -->
        <div class="card mt-3">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                    <div class="d-flex align-items-center gap-2">
                        <label class="mb-0">عدد المستخدمين:</label>
                        <select onchange="changePerPage(this.value)" class="form-select form-select-sm" style="width: auto;">
                            <option value="20" <?= $per_page == 20 ? 'selected' : '' ?>>20</option>
                            <option value="50" <?= $per_page == 50 ? 'selected' : '' ?>>50</option>
                            <option value="100" <?= $per_page == 100 ? 'selected' : '' ?>>100</option>
                        </select>
                    </div>
                    
                    <div class="d-flex gap-2 align-items-center flex-wrap">
                        <span class="text-muted">عرض <?= $offset + 1 ?> - <?= min($offset + $per_page, $total_users) ?> من <?= $total_users ?></span>
                        
                        <?php if ($total_pages > 1): ?>
                            <div class="btn-group">
                                <?php if ($page > 1): ?>
                                    <a href="?page=1&per_page=<?= $per_page ?>" class="btn btn-sm btn-outline-secondary">الأول</a>
                                    <a href="?page=<?= $page - 1 ?>&per_page=<?= $per_page ?>" class="btn btn-sm btn-outline-secondary">السابق</a>
                                <?php endif; ?>
                                
                                <span class="btn btn-sm btn-primary"><?= $page ?></span>
                                
                                <?php if ($page < $total_pages): ?>
                                    <a href="?page=<?= $page + 1 ?>&per_page=<?= $per_page ?>" class="btn btn-sm btn-outline-secondary">التالي</a>
                                    <a href="?page=<?= $total_pages ?>&per_page=<?= $per_page ?>" class="btn btn-sm btn-outline-secondary">الأخير</a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add User Modal -->
<div id="addModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <span class="close" onclick="closeAddModal()">&times;</span>
            <h2>➕ إضافة مستخدم جديد</h2>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="add">
            
            <div class="form-group">
                <label>اسم المستخدم <span class="text-danger">*</span></label>
                <input type="text" name="username" required placeholder="أدخل اسم المستخدم">
            </div>
            
            <div class="form-group">
                <label>البريد الإلكتروني <span class="text-danger">*</span></label>
                <input type="email" name="email" required placeholder="example@hospital.com">
            </div>
            
            <div class="form-group">
                <label>كلمة المرور <span class="text-danger">*</span></label>
                <input type="password" name="password" required placeholder="أدخل كلمة المرور">
            </div>
            
            <div class="form-group">
                <label>الاسم الكامل <span class="text-danger">*</span></label>
                <input type="text" name="full_name" required placeholder="أدخل الاسم الكامل">
            </div>
            
            <div class="form-group">
                <label>الدور <span class="text-danger">*</span></label>
                <select name="role" required>
                    <option value="">-- اختر الدور --</option>
                    <option value="admin">👑 مدير</option>
                    <option value="pharmacist">💊 صيدلي</option>
                    <option value="doctor">👨‍⚕️ طبيب</option>
                    <option value="nurse">👩‍⚕️ ممرض</option>
                    <option value="secretary">⌨️ سكرتارية</option>
                    <option value="pharmacy_assistant">💊 مساعد صيدلي</option>
                </select>
            </div>
            
            <div class="form-group">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <label style="font-size: 18px; color: #2c3e50; margin-bottom: 0;">🔐 صلاحيات الصفحات</label>
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="selectAllPermissions('addModal')">✅ اختيار الكل</button>
                </div>
                
                <?php foreach ($pagePermissionsConfig['pages'] as $pageName => $pageData): ?>
                <div class="bg-light p-3 rounded mb-3" style="border-left: 4px solid #667eea;">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h6 style="color: #333; font-weight: bold; margin-bottom: 0;">
                            <?= $pageData['name_ar'] ?>
                        </h6>
                        <button type="button" class="btn btn-xs btn-link p-0 text-decoration-none" onclick="toggleSectionPermissions(this, '<?= $pageName ?>')">تحديد القسم</button>
                    </div>
                    <div class="row section-permissions" data-section="<?= $pageName ?>">
                        <?php foreach ($pageData['permissions'] as $permKey => $permInfo): ?>
                        <div class="col-md-6 mb-2">
                            <label class="d-flex align-items-center cursor-pointer p-2 bg-white rounded">
                                <input type="checkbox" name="page_permissions[]" value="<?= $pageName . ':' . $permKey ?>" class="me-2">
                                <span class="small"><?= $permInfo['icon'] ?> <?= $permInfo['name_ar'] ?></span>
                            </label>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            
            <div class="alert alert-info">
                💡 <strong>نصيحة:</strong> تأكد من اختيار الدور المناسب للمستخدم. المدير لديه صلاحيات كاملة على النظام.
            </div>
            
            <div class="text-center mt-3">
                <button type="submit" class="btn btn-success">💾 حفظ</button>
                <button type="button" onclick="closeAddModal()" class="btn btn-secondary">❌ إلغاء</button>
            </div>
        </form>
    </div>
</div>

<!-- Edit User Modal -->
<div id="editModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <span class="close" onclick="closeEditModal()">&times;</span>
            <h2>✏️ تعديل مستخدم</h2>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="edit">
            <input type="hidden" name="user_id" id="edit_user_id">
            
            <div class="form-group">
                <label>اسم المستخدم <span class="text-danger">*</span></label>
                <input type="text" name="username" id="edit_username" required>
            </div>
            
            <div class="form-group">
                <label>البريد الإلكتروني <span class="text-danger">*</span></label>
                <input type="email" name="email" id="edit_email" required>
            </div>
            
            <div class="form-group">
                <label>كلمة المرور (اتركها فارغة إذا لم ترد التغيير)</label>
                <input type="password" name="password" id="edit_password" placeholder="اترك فارغاً للإبقاء على كلمة المرور الحالية">
            </div>
            
            <div class="form-group">
                <label>الاسم الكامل <span class="text-danger">*</span></label>
                <input type="text" name="full_name" id="edit_full_name" required>
            </div>
            
            <div class="form-group">
                <label>الدور <span class="text-danger">*</span></label>
                <select name="role" id="edit_role" required>
                    <option value="admin">👑 مدير</option>
                    <option value="pharmacist">💊 صيدلي</option>
                    <option value="doctor">👨‍⚕️ طبيب</option>
                    <option value="nurse">👩‍⚕️ ممرض</option>
                    <option value="secretary">⌨️ سكرتارية</option>
                    <option value="pharmacy_assistant">💊 مساعد صيدلي</option>
                </select>
            </div>
            
            <div class="form-group">
                <label class="d-flex align-items-center cursor-pointer">
                    <input type="checkbox" name="is_active" id="edit_is_active" class="me-2">
                    <span>المستخدم نشط</span>
                </label>
            </div>
            
            <div class="form-group">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <label style="font-size: 18px; color: #2c3e50; margin-bottom: 0;">🔐 صلاحيات الصفحات</label>
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="selectAllPermissions('editModal')">✅ اختيار الكل</button>
                </div>
                
                <?php foreach ($pagePermissionsConfig['pages'] as $pageName => $pageData): ?>
                <div class="bg-light p-3 rounded mb-3" style="border-left: 4px solid #667eea;">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h6 style="color: #333; font-weight: bold; margin-bottom: 0;">
                            <?= $pageData['name_ar'] ?>
                        </h6>
                        <button type="button" class="btn btn-xs btn-link p-0 text-decoration-none" onclick="toggleSectionPermissions(this, '<?= $pageName ?>')">تحديد القسم</button>
                    </div>
                    <div class="row section-permissions" data-section="<?= $pageName ?>">
                        <?php foreach ($pageData['permissions'] as $permKey => $permInfo): ?>
                        <div class="col-md-6 mb-2">
                            <label class="d-flex align-items-center cursor-pointer p-2 bg-white rounded">
                                <input type="checkbox" name="page_permissions[]" value="<?= $pageName . ':' . $permKey ?>" class="me-2">
                                <span class="small"><?= $permInfo['icon'] ?> <?= $permInfo['name_ar'] ?></span>
                            </label>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            
            <div class="text-center mt-3">
                <button type="submit" class="btn btn-success">💾 حفظ التعديلات</button>
                <button type="button" onclick="closeEditModal()" class="btn btn-secondary">❌ إلغاء</button>
            </div>
        </form>
    </div>
</div>

<script>
let currentView = 'table';

function toggleView() {
    const cardsView = document.getElementById('cardsView');
    const tableView = document.getElementById('tableView');
    const viewIcon = document.getElementById('viewIcon');
    const viewText = document.getElementById('viewText');
    
    if (currentView === 'cards') {
        cardsView.style.display = 'none';
        tableView.style.display = 'block';
        viewIcon.textContent = '🎴';
        viewText.textContent = 'عرض كروت';
        currentView = 'table';
        localStorage.setItem('usersViewPreference', 'table');
    } else {
        cardsView.style.display = 'block';
        tableView.style.display = 'none';
        viewIcon.textContent = '📋';
        viewText.textContent = 'عرض جدول';
        currentView = 'cards';
        localStorage.setItem('usersViewPreference', 'cards');
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const savedView = localStorage.getItem('usersViewPreference');
    if (savedView === 'cards') {
        toggleView();
    }
});

function changePerPage(perPage) {
    window.location.href = '?page=1&per_page=' + perPage;
}

function selectAllPermissions(modalId) {
    const modal = document.getElementById(modalId);
    const checkboxes = modal.querySelectorAll('input[name="page_permissions[]"]');
    checkboxes.forEach(cb => cb.checked = true);
}

function toggleSectionPermissions(btn, pageName) {
    const modal = btn.closest('.modal');
    const section = modal.querySelector('.row[data-section="' + pageName + '"]');
    const checkboxes = section.querySelectorAll('input[name="page_permissions[]"]');
    
    // Check if any are unchecked
    const allChecked = Array.from(checkboxes).every(cb => cb.checked);
    checkboxes.forEach(cb => cb.checked = !allChecked);
    
    btn.textContent = allChecked ? 'تحديد القسم' : 'إلغاء القسم';
}

function openAddModal() {
    document.getElementById('addModal').style.display = 'block';
}

function closeAddModal() {
    document.getElementById('addModal').style.display = 'none';
}

function openEditModal(user) {
    console.log('Opening edit modal for user:', user.id);
    
    document.getElementById('edit_user_id').value = user.id;
    document.getElementById('edit_username').value = user.username;
    document.getElementById('edit_email').value = user.email;
    document.getElementById('edit_full_name').value = user.full_name;
    document.getElementById('edit_role').value = user.role;
    document.getElementById('edit_is_active').checked = user.is_active == 1;
    
    // Show modal first
    document.getElementById('editModal').style.display = 'block';
    
    // Get all checkboxes ONLY from edit modal
    const editModal = document.getElementById('editModal');
    const allCheckboxes = editModal.querySelectorAll('input[name="page_permissions[]"]');
    console.log('Total checkboxes found in edit modal:', allCheckboxes.length);
    
    // Uncheck all page permissions first
    allCheckboxes.forEach(cb => {
        cb.checked = false;
        cb.disabled = true; // Disable while loading
    });
    
    // Load page permissions via AJAX
    fetch('get_user_page_permissions.php?user_id=' + user.id)
        .then(response => response.text())
        .then(text => {
            // Enable all checkboxes first
            allCheckboxes.forEach(cb => { cb.disabled = false; });
            
            try {
                const data = JSON.parse(text);
                if (data.permissions && data.permissions.length > 0) {
                    data.permissions.forEach(perm => {
                        const checkbox = editModal.querySelector('input[name="page_permissions[]"][value="' + perm + '"]');
                        if (checkbox) checkbox.checked = true;
                    });
                }
            } catch(e) {
                console.error('JSON parse error:', e, 'Response was:', text);
                // لا نوقف المستخدم - الـ modal مفتوح والـ checkboxes شغالة
            }
        })
        .catch(error => {
            console.error('Fetch error:', error);
            allCheckboxes.forEach(cb => { cb.disabled = false; });
        });
}

function closeEditModal() {
    document.getElementById('editModal').style.display = 'none';
}

function deleteUser(id) {
    if (confirm('هل أنت متأكد من حذف هذا المستخدم؟ هذا الإجراء لا يمكن التراجع عنه.')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = '<input type="hidden" name="action" value="delete"><input type="hidden" name="user_id" value="' + id + '">';
        document.body.appendChild(form);
        form.submit();
    }
}

function toggleStatus(id) {
    if (confirm('هل تريد تغيير حالة هذا المستخدم؟')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = '<input type="hidden" name="action" value="toggle_status"><input type="hidden" name="user_id" value="' + id + '">';
        document.body.appendChild(form);
        form.submit();
    }
}

window.onclick = function(event) {
    if (event.target.className === 'modal') {
        event.target.style.display = 'none';
    }
}
</script>

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

