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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: " . (isset($_SERVER["HTTPS"]) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER["SCRIPT_NAME"]), "/\\") . "/" . "index.php");
    exit();
}

// Check if user is admin
if ($_SESSION['role'] !== 'admin') {
    header("Location: " . (isset($_SERVER["HTTPS"]) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER["SCRIPT_NAME"]), "/\\") . "/" . "access_denied.php");
    exit();
}

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

$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'];
        
        // Get permissions
        $can_view_dashboard = isset($_POST['can_view_dashboard']) ? 1 : 0;
        $can_view_records = isset($_POST['can_view_records']) ? 1 : 0;
        $can_add_records = isset($_POST['can_add_records']) ? 1 : 0;
        $can_edit_records = isset($_POST['can_edit_records']) ? 1 : 0;
        $can_delete_records = isset($_POST['can_delete_records']) ? 1 : 0;
        $can_export = isset($_POST['can_export']) ? 1 : 0;
        $can_print = isset($_POST['can_print']) ? 1 : 0;
        $can_manage_users = isset($_POST['can_manage_users']) ? 1 : 0;
        $can_manage_antibiotics = isset($_POST['can_manage_antibiotics']) ? 1 : 0;
        $can_manage_patients = isset($_POST['can_manage_patients']) ? 1 : 0;
        $can_view_reports = isset($_POST['can_view_reports']) ? 1 : 0;
        $can_add_reports = isset($_POST['can_add_reports']) ? 1 : 0;
        $can_edit_reports = isset($_POST['can_edit_reports']) ? 1 : 0;
        $can_delete_reports = isset($_POST['can_delete_reports']) ? 1 : 0;
        $can_view_icu = isset($_POST['can_view_icu']) ? 1 : 0;
        $can_manage_icu = isset($_POST['can_manage_icu']) ? 1 : 0;
        $can_view_pharmacy = isset($_POST['can_view_pharmacy']) ? 1 : 0;
        $can_manage_pharmacy = isset($_POST['can_manage_pharmacy']) ? 1 : 0;
        $can_view_kpi = isset($_POST['can_view_kpi']) ? 1 : 0;
        $can_access_advanced_search = isset($_POST['can_access_advanced_search']) ? 1 : 0;
        $can_view_activity_log = isset($_POST['can_view_activity_log']) ? 1 : 0;
        $can_create_backup = isset($_POST['can_create_backup']) ? 1 : 0;
        
        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
                $stmt = $conn->prepare("INSERT INTO users (username, email, password, full_name, role, is_active, 
                    can_view_dashboard, can_view_records, can_add_records, can_edit_records, can_delete_records,
                    can_export, can_print, can_manage_users, can_manage_antibiotics, can_manage_patients,
                    can_view_reports, can_add_reports, can_edit_reports, can_delete_reports,
                    can_view_icu, can_manage_icu, can_view_pharmacy, can_manage_pharmacy, can_view_kpi,
                    can_access_advanced_search, can_view_activity_log, can_create_backup) 
                    VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$username, $email, $password, $full_name, $role,
                    $can_view_dashboard, $can_view_records, $can_add_records, $can_edit_records, $can_delete_records,
                    $can_export, $can_print, $can_manage_users, $can_manage_antibiotics, $can_manage_patients,
                    $can_view_reports, $can_add_reports, $can_edit_reports, $can_delete_reports,
                    $can_view_icu, $can_manage_icu, $can_view_pharmacy, $can_manage_pharmacy, $can_view_kpi,
                    $can_access_advanced_search, $can_view_activity_log, $can_create_backup]);
                
                logActivity($conn, $_SESSION['user_id'], 'إضافة مستخدم جديد', 'users', $conn->lastInsertId());
                $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;
        
        // Get permissions
        $can_view_dashboard = isset($_POST['can_view_dashboard']) ? 1 : 0;
        $can_view_records = isset($_POST['can_view_records']) ? 1 : 0;
        $can_add_records = isset($_POST['can_add_records']) ? 1 : 0;
        $can_edit_records = isset($_POST['can_edit_records']) ? 1 : 0;
        $can_delete_records = isset($_POST['can_delete_records']) ? 1 : 0;
        $can_export = isset($_POST['can_export']) ? 1 : 0;
        $can_print = isset($_POST['can_print']) ? 1 : 0;
        $can_manage_users = isset($_POST['can_manage_users']) ? 1 : 0;
        $can_manage_antibiotics = isset($_POST['can_manage_antibiotics']) ? 1 : 0;
        $can_manage_patients = isset($_POST['can_manage_patients']) ? 1 : 0;
        $can_view_reports = isset($_POST['can_view_reports']) ? 1 : 0;
        $can_add_reports = isset($_POST['can_add_reports']) ? 1 : 0;
        $can_edit_reports = isset($_POST['can_edit_reports']) ? 1 : 0;
        $can_delete_reports = isset($_POST['can_delete_reports']) ? 1 : 0;
        $can_view_icu = isset($_POST['can_view_icu']) ? 1 : 0;
        $can_manage_icu = isset($_POST['can_manage_icu']) ? 1 : 0;
        $can_view_pharmacy = isset($_POST['can_view_pharmacy']) ? 1 : 0;
        $can_manage_pharmacy = isset($_POST['can_manage_pharmacy']) ? 1 : 0;
        $can_view_kpi = isset($_POST['can_view_kpi']) ? 1 : 0;
        $can_access_advanced_search = isset($_POST['can_access_advanced_search']) ? 1 : 0;
        $can_view_activity_log = isset($_POST['can_view_activity_log']) ? 1 : 0;
        $can_create_backup = isset($_POST['can_create_backup']) ? 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'];
                    $stmt = $conn->prepare("UPDATE users SET username=?, email=?, password=?, full_name=?, role=?, is_active=?,
                        can_view_dashboard=?, can_view_records=?, can_add_records=?, can_edit_records=?, can_delete_records=?,
                        can_export=?, can_print=?, can_manage_users=?, can_manage_antibiotics=?, can_manage_patients=?,
                        can_view_reports=?, can_add_reports=?, can_edit_reports=?, can_delete_reports=?,
                        can_view_icu=?, can_manage_icu=?, can_view_pharmacy=?, can_manage_pharmacy=?, can_view_kpi=?,
                        can_access_advanced_search=?, can_view_activity_log=?, can_create_backup=? WHERE id=?");
                    $stmt->execute([$username, $email, $password, $full_name, $role, $is_active,
                        $can_view_dashboard, $can_view_records, $can_add_records, $can_edit_records, $can_delete_records,
                        $can_export, $can_print, $can_manage_users, $can_manage_antibiotics, $can_manage_patients,
                        $can_view_reports, $can_add_reports, $can_edit_reports, $can_delete_reports,
                        $can_view_icu, $can_manage_icu, $can_view_pharmacy, $can_manage_pharmacy, $can_view_kpi,
                        $can_access_advanced_search, $can_view_activity_log, $can_create_backup, $id]);
                } else {
                    $stmt = $conn->prepare("UPDATE users SET username=?, email=?, full_name=?, role=?, is_active=?,
                        can_view_dashboard=?, can_view_records=?, can_add_records=?, can_edit_records=?, can_delete_records=?,
                        can_export=?, can_print=?, can_manage_users=?, can_manage_antibiotics=?, can_manage_patients=?,
                        can_view_reports=?, can_add_reports=?, can_edit_reports=?, can_delete_reports=?,
                        can_view_icu=?, can_manage_icu=?, can_view_pharmacy=?, can_manage_pharmacy=?, can_view_kpi=?,
                        can_access_advanced_search=?, can_view_activity_log=?, can_create_backup=? WHERE id=?");
                    $stmt->execute([$username, $email, $full_name, $role, $is_active,
                        $can_view_dashboard, $can_view_records, $can_add_records, $can_edit_records, $can_delete_records,
                        $can_export, $can_print, $can_manage_users, $can_manage_antibiotics, $can_manage_patients,
                        $can_view_reports, $can_add_reports, $can_edit_reports, $can_delete_reports,
                        $can_view_icu, $can_manage_icu, $can_view_pharmacy, $can_manage_pharmacy, $can_view_kpi,
                        $can_access_advanced_search, $can_view_activity_log, $can_create_backup, $id]);
                }
                
                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 {
                $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
                $stmt->execute([$id]);
                
                logActivity($conn, $_SESSION['user_id'], 'حذف مستخدم', 'users', $id);
                $message = 'تم حذف المستخدم بنجاح';
            } catch (Exception $e) {
                $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]);
            
            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 = 'خطأ في جلب البيانات';
}

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

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

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

.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;
}

.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;
}

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

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

.user-card {
    background: white;
    border-radius: 15px;
    padding: 25px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    margin-bottom: 20px;
}

.badge {
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.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; }
</style>


    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 style="color: #2c3e50; margin: 0;">👥 إدارة المستخدمين والصلاحيات</h2>
        <div style="display: flex; gap: 10px;">
            <button onclick="toggleView()" id="viewToggleBtn" class="btn btn-secondary" style="padding: 12px 20px;">
                <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">✅ <?= htmlspecialchars($message) ?></div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-danger">❌ <?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <!-- Statistics -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-number"><?= $total_users ?></div>
                <div>إجمالي المستخدمين</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card" style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);">
                <div class="stat-number"><?php
                    $active_count = 0;
                    foreach ($users as $u) if ($u['is_active']) $active_count++;
                    echo $active_count;
                ?></div>
                <div>المستخدمين النشطين</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card" style="background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%); color: #333;">
                <div class="stat-number"><?php
                    $admin_count = 0;
                    foreach ($users as $u) if ($u['role'] == 'admin') $admin_count++;
                    echo $admin_count;
                ?></div>
                <div>المديرين</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card" style="background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%); color: #333;">
                <div class="stat-number"><?php
                    $pharmacist_count = 0;
                    foreach ($users as $u) if ($u['role'] == 'pharmacist') $pharmacist_count++;
                    echo $pharmacist_count;
                ?></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-md-6 col-lg-4">
                    <div class="user-card">
                        <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">
                            <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(substr($user['full_name'], 0, 1)) ?>
                            </div>
                            <div style="flex: 1;">
                                <h4 style="margin: 0; color: #2c3e50;"><?= htmlspecialchars($user['full_name']) ?></h4>
                                <p style="margin: 5px 0 0 0; color: #7f8c8d; font-size: 14px;">@<?= htmlspecialchars($user['username']) ?></p>
                            </div>
                        </div>
                        
                        <div style="margin-bottom: 15px;">
                            <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                                <span style="color: #7f8c8d;">البريد الإلكتروني:</span>
                                <span style="color: #2c3e50; font-size: 12px;"><?= htmlspecialchars($user['email']) ?></span>
                            </div>
                            <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                                <span style="color: #7f8c8d;">الدور:</span>
                                <span class="badge badge-<?= htmlspecialchars($user['role']) ?>">
                                    <?php
                                    $roles = [
                                        'admin' => '👑 مدير', 
                                        'pharmacist' => '💊 صيدلي', 
                                        'doctor' => '👨‍⚕️ طبيب', 
                                        'nurse' => '👩‍⚕️ ممرض',
                                        'secretary' => '⌨️ سكرتارية',
                                        'pharmacy_assistant' => '💊 مساعد صيدلي'
                                    ];
                                    if (isset($roles[$user['role']])) {
                                        echo $roles[$user['role']];
                                    } else {
                                        echo !empty(trim($user['role'])) ? htmlspecialchars($user['role']) : '<span class="text-danger">⚠️ غير محدد</span>';
                                    }
                                    ?>
                                </span>
                            </div>
                            <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                                <span style="color: #7f8c8d;">الحالة:</span>
                                <span class="badge badge-<?= $user['is_active'] ? 'active' : 'inactive' ?>">
                                    <?= $user['is_active'] ? '✅ نشط' : '❌ معطل' ?>
                                </span>
                            </div>
                            <div style="display: flex; justify-content: space-between;">
                                <span style="color: #7f8c8d;">تاريخ الإنشاء:</span>
                                <span style="color: #2c3e50; font-weight: 600; font-size: 12px;"><?= date('Y/m/d', strtotime($user['created_at'])) ?></span>
                            </div>
                        </div>
                        
                        <!-- Permissions Summary -->
                        <div style="background: #f8f9fa; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
                            <h5 style="margin: 0 0 12px 0; color: #2c3e50; font-size: 14px;">🔐 الصلاحيات الممنوحة:</h5>
                            <div style="display: flex; flex-wrap: wrap; gap: 6px;">
                                <?php
                                $permissions = [
                                    'can_view_dashboard' => '📊 لوحة التحكم',
                                    'can_view_records' => '👁️ عرض السجلات',
                                    'can_add_records' => '➕ إضافة سجلات',
                                    'can_edit_records' => '✏️ تعديل سجلات',
                                    'can_delete_records' => '🗑️ حذف سجلات',
                                    'can_export' => '📤 تصدير',
                                    'can_print' => '🖨️ طباعة',
                                    'can_manage_users' => '👥 إدارة المستخدمين',
                                    'can_manage_antibiotics' => '💊 إدارة المضادات',
                                    'can_manage_patients' => '🏥 إدارة المرضى',
                                    'can_view_reports' => '📋 عرض التقارير',
                                    'can_add_reports' => '➕ إضافة تقارير',
                                    'can_edit_reports' => '✏️ تعديل تقارير',
                                    'can_delete_reports' => '🗑️ حذف تقارير',
                                    'can_view_icu' => '🏥 عرض ICU',
                                    'can_manage_icu' => '⚕️ إدارة ICU',
                                    'can_view_pharmacy' => '💊 عرض الصيدلية',
                                    'can_manage_pharmacy' => '💉 إدارة الصيدلية',
                                    'can_view_kpi' => '📊 عرض KPI',
                                    'can_access_advanced_search' => '🔍 بحث متقدم',
                                    'can_view_activity_log' => '📝 سجل النشاط',
                                    'can_create_backup' => '💾 نسخ احتياطي'
                                ];
                                $active_count = 0;
                                foreach ($permissions as $key => $label):
                                    if (isset($user[$key]) && $user[$key]):
                                        $active_count++;
                                ?>
                                    <span style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; padding: 4px 8px; border-radius: 12px; font-size: 10px; white-space: nowrap;">
                                        <?= $label ?>
                                    </span>
                                <?php 
                                    endif;
                                endforeach;
                                if ($active_count == 0):
                                ?>
                                    <span style="color: #999; font-size: 12px;">لا توجد صلاحيات</span>
                                <?php endif; ?>
                            </div>
                            <div style="margin-top: 10px; padding-top: 10px; border-top: 1px solid #e0e0e0; text-align: center;">
                                <span style="color: #667eea; font-weight: 600; font-size: 12px;">
                                    <?= $active_count ?> من <?= count($permissions) ?> صلاحية نشطة
                                </span>
                            </div>
                        </div>
                        
                        <div style="display: flex; gap: 8px;">
                            <button onclick='openEditModal(<?= json_encode($user) ?>)' class="btn btn-warning" style="flex: 1; padding: 8px; font-size: 12px;">✏️ تعديل</button>
                            <button onclick="toggleStatus(<?= $user['id'] ?>)" class="btn btn-info" style="flex: 1; padding: 8px; font-size: 12px;">
                                <?= $user['is_active'] ? '🔒 تعطيل' : '✅ تفعيل' ?>
                            </button>
                            <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                <button onclick="deleteUser(<?= $user['id'] ?>)" class="btn btn-danger" style="padding: 8px 12px; font-size: 12px;">🗑️</button>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Table View -->
    <div id="tableView" style="display: block;">
        <div class="table-wrapper">
            <table class="table">
                <thead>
                    <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>@<?= htmlspecialchars($user['username']) ?></td>
                            <td><?= htmlspecialchars($user['email']) ?></td>
                            <td>
                                <span class="badge badge-<?= htmlspecialchars($user['role']) ?>">
                                    <?php
                                    $roles = [
                                        'admin' => '👑 مدير', 
                                        'pharmacist' => '💊 صيدلي', 
                                        'doctor' => '👨‍⚕️ طبيب', 
                                        'nurse' => '👩‍⚕️ ممرض',
                                        'secretary' => '⌨️ سكرتارية',
                                        'pharmacy_assistant' => '💊 مساعد صيدلي'
                                    ];
                                    if (isset($roles[$user['role']])) {
                                        echo $roles[$user['role']];
                                    } else {
                                        echo !empty(trim($user['role'])) ? htmlspecialchars($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 style="text-align: center;">
                                <?php
                                $permissions = ['can_view_dashboard', 'can_view_records', 'can_add_records', 'can_edit_records', 
                                    'can_delete_records', 'can_export', 'can_print', 'can_manage_users', 'can_manage_antibiotics',
                                    'can_manage_patients', 'can_view_reports', 'can_add_reports', 'can_edit_reports', 
                                    'can_delete_reports', 'can_view_icu', 'can_manage_icu', 'can_view_pharmacy', 
                                    'can_manage_pharmacy', 'can_view_kpi', 'can_access_advanced_search', 'can_view_activity_log', 
                                    'can_create_backup'];
                                $active_count = 0;
                                foreach ($permissions as $perm) {
                                    if (isset($user[$perm]) && $user[$perm]) $active_count++;
                                }
                                $color = $active_count > 15 ? '#38ef7d' : ($active_count > 8 ? '#ffd700' : '#e74c3c');
                                ?>
                                <span style="background: <?= $color ?>; color: white; padding: 6px 12px; border-radius: 15px; font-weight: 600; font-size: 12px;">
                                    <?= $active_count ?> / <?= count($permissions) ?>
                                </span>
                            </td>
                            <td><?= date('Y/m/d', strtotime($user['created_at'])) ?></td>
                            <td style="text-align: center;">
                                <button onclick='openEditModal(<?= json_encode($user) ?>)' 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>

        <!-- Pagination -->
        <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 20px; padding: 20px; background: #f8f9fa; border-radius: 10px;">
            <div style="display: flex; align-items: center; gap: 10px;">
                <label style="color: #555; font-weight: 600;">عدد المستخدمين:</label>
                <select onchange="changePerPage(this.value)" style="padding: 8px 12px; border: 2px solid #ddd; border-radius: 6px;">
                    <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 style="display: flex; gap: 5px; align-items: center;">
                <span style="color: #555; margin-left: 15px;">عرض <?= $offset + 1 ?> - <?= min($offset + $per_page, $total_users) ?> من <?= $total_users ?></span>
                
                <?php if ($total_pages > 1): ?>
                    <?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; ?>
                <?php endif; ?>
            </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 style="color: red;">*</span></label>
                <input type="text" name="username" required placeholder="أدخل اسم المستخدم">
            </div>
            
            <div class="form-group">
                <label>البريد الإلكتروني <span style="color: red;">*</span></label>
                <input type="email" name="email" required placeholder="example@hospital.com">
            </div>
            
            <div class="form-group">
                <label>كلمة المرور <span style="color: red;">*</span></label>
                <input type="password" name="password" required placeholder="أدخل كلمة المرور">
            </div>
            
            <div class="form-group">
                <label>الاسم الكامل <span style="color: red;">*</span></label>
                <input type="text" name="full_name" required placeholder="أدخل الاسم الكامل">
            </div>
            
            <div class="form-group">
                <label>الدور <span style="color: red;">*</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">
                <label style="font-size: 16px; color: #2c3e50; margin-bottom: 15px; display: block;">🔐 الصلاحيات</label>
                
                <!-- Basic Permissions -->
                <div style="background: #e8f5e9; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
                    <h5 style="margin: 0 0 10px 0; color: #2e7d32; font-size: 14px;">📌 الصلاحيات الأساسية</h5>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_view_dashboard" checked style="margin-left: 8px;">
                            <span style="font-size: 13px;">📊 عرض لوحة التحكم</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_view_records" checked style="margin-left: 8px;">
                            <span style="font-size: 13px;">👁️ عرض السجلات</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_add_records" checked style="margin-left: 8px;">
                            <span style="font-size: 13px;">➕ إضافة سجلات</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_manage_patients" checked style="margin-left: 8px;">
                            <span style="font-size: 13px;">🏥 إدارة المرضى</span>
                        </label>
                    </div>
                </div>
                
                <!-- Action Permissions -->
                <div style="background: #fff3e0; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
                    <h5 style="margin: 0 0 10px 0; color: #e65100; font-size: 14px;">⚡ صلاحيات الإجراءات</h5>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_edit_records" style="margin-left: 8px;">
                            <span style="font-size: 13px;">✏️ تعديل السجلات</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_delete_records" style="margin-left: 8px;">
                            <span style="font-size: 13px;">🗑️ حذف السجلات</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_export" style="margin-left: 8px;">
                            <span style="font-size: 13px;">📤 تصدير Excel</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_print" checked style="margin-left: 8px;">
                            <span style="font-size: 13px;">🖨️ طباعة</span>
                        </label>
                    </div>
                </div>
                
                <!-- Reports Permissions -->
                <div style="background: #e3f2fd; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
                    <h5 style="margin: 0 0 10px 0; color: #0d47a1; font-size: 14px;">📋 صلاحيات التقارير</h5>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_view_reports" checked style="margin-left: 8px;">
                            <span style="font-size: 13px;">👁️ عرض التقارير</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_add_reports" checked style="margin-left: 8px;">
                            <span style="font-size: 13px;">➕ إضافة تقارير</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_edit_reports" style="margin-left: 8px;">
                            <span style="font-size: 13px;">✏️ تعديل تقارير</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_delete_reports" style="margin-left: 8px;">
                            <span style="font-size: 13px;">🗑️ حذف تقارير</span>
                        </label>
                    </div>
                </div>
                
                <!-- Medical Departments -->
                <div style="background: #f3e5f5; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
                    <h5 style="margin: 0 0 10px 0; color: #6a1b9a; font-size: 14px;">🏥 الأقسام الطبية</h5>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_view_icu" checked style="margin-left: 8px;">
                            <span style="font-size: 13px;">🏥 عرض ICU</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_manage_icu" style="margin-left: 8px;">
                            <span style="font-size: 13px;">⚕️ إدارة ICU</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_view_pharmacy" checked style="margin-left: 8px;">
                            <span style="font-size: 13px;">💊 عرض الصيدلية</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_manage_pharmacy" style="margin-left: 8px;">
                            <span style="font-size: 13px;">💉 إدارة الصيدلية</span>
                        </label>
                    </div>
                </div>
                
                <!-- Advanced Permissions -->
                <div style="background: #fce4ec; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
                    <h5 style="margin: 0 0 10px 0; color: #c2185b; font-size: 14px;">⚙️ صلاحيات متقدمة</h5>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_manage_users" style="margin-left: 8px;">
                            <span style="font-size: 13px;">👥 إدارة المستخدمين</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_manage_antibiotics" style="margin-left: 8px;">
                            <span style="font-size: 13px;">💊 إدارة المضادات</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_view_kpi" checked style="margin-left: 8px;">
                            <span style="font-size: 13px;">📊 عرض KPI</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_access_advanced_search" checked style="margin-left: 8px;">
                            <span style="font-size: 13px;">🔍 بحث متقدم</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_view_activity_log" style="margin-left: 8px;">
                            <span style="font-size: 13px;">📝 سجل النشاط</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_create_backup" style="margin-left: 8px;">
                            <span style="font-size: 13px;">💾 نسخ احتياطي</span>
                        </label>
                    </div>
                </div>
            </div>
            
            <div style="background: #f5f5f5; padding: 12px; border-radius: 8px; margin-bottom: 20px; border-right: 4px solid #667eea;">
                <p style="margin: 0; font-size: 13px; color: #555; line-height: 1.6;">
                    💡 <strong>نصيحة:</strong> تأكد من اختيار الدور المناسب للمستخدم. المدير لديه صلاحيات كاملة على النظام.
                </p>
            </div>
            
            <div style="text-align: center; margin-top: 20px;">
                <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 style="color: red;">*</span></label>
                <input type="text" name="username" id="edit_username" required>
            </div>
            
            <div class="form-group">
                <label>البريد الإلكتروني <span style="color: red;">*</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 style="color: red;">*</span></label>
                <input type="text" name="full_name" id="edit_full_name" required>
            </div>
            
            <div class="form-group">
                <label>الدور <span style="color: red;">*</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 style="display: flex; align-items: center; cursor: pointer;">
                    <input type="checkbox" name="is_active" id="edit_is_active" style="width: auto; margin-left: 10px;">
                    <span>المستخدم نشط</span>
                </label>
            </div>
            
            <div class="form-group">
                <label style="font-size: 16px; color: #2c3e50; margin-bottom: 15px; display: block;">🔐 الصلاحيات</label>
                
                <!-- Basic Permissions -->
                <div style="background: #e8f5e9; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
                    <h5 style="margin: 0 0 10px 0; color: #2e7d32; font-size: 14px;">📌 الصلاحيات الأساسية</h5>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_view_dashboard" id="edit_can_view_dashboard" style="margin-left: 8px;">
                            <span style="font-size: 13px;">📊 عرض لوحة التحكم</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_view_records" id="edit_can_view_records" style="margin-left: 8px;">
                            <span style="font-size: 13px;">👁️ عرض السجلات</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_add_records" id="edit_can_add_records" style="margin-left: 8px;">
                            <span style="font-size: 13px;">➕ إضافة سجلات</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_manage_patients" id="edit_can_manage_patients" style="margin-left: 8px;">
                            <span style="font-size: 13px;">🏥 إدارة المرضى</span>
                        </label>
                    </div>
                </div>
                
                <!-- Action Permissions -->
                <div style="background: #fff3e0; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
                    <h5 style="margin: 0 0 10px 0; color: #e65100; font-size: 14px;">⚡ صلاحيات الإجراءات</h5>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_edit_records" id="edit_can_edit_records" style="margin-left: 8px;">
                            <span style="font-size: 13px;">✏️ تعديل السجلات</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_delete_records" id="edit_can_delete_records" style="margin-left: 8px;">
                            <span style="font-size: 13px;">🗑️ حذف السجلات</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_export" id="edit_can_export" style="margin-left: 8px;">
                            <span style="font-size: 13px;">📤 تصدير Excel</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_print" id="edit_can_print" style="margin-left: 8px;">
                            <span style="font-size: 13px;">🖨️ طباعة</span>
                        </label>
                    </div>
                </div>
                
                <!-- Reports Permissions -->
                <div style="background: #e3f2fd; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
                    <h5 style="margin: 0 0 10px 0; color: #0d47a1; font-size: 14px;">📋 صلاحيات التقارير</h5>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_view_reports" id="edit_can_view_reports" style="margin-left: 8px;">
                            <span style="font-size: 13px;">👁️ عرض التقارير</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_add_reports" id="edit_can_add_reports" style="margin-left: 8px;">
                            <span style="font-size: 13px;">➕ إضافة تقارير</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_edit_reports" id="edit_can_edit_reports" style="margin-left: 8px;">
                            <span style="font-size: 13px;">✏️ تعديل تقارير</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_delete_reports" id="edit_can_delete_reports" style="margin-left: 8px;">
                            <span style="font-size: 13px;">🗑️ حذف تقارير</span>
                        </label>
                    </div>
                </div>
                
                <!-- Medical Departments -->
                <div style="background: #f3e5f5; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
                    <h5 style="margin: 0 0 10px 0; color: #6a1b9a; font-size: 14px;">🏥 الأقسام الطبية</h5>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_view_icu" id="edit_can_view_icu" style="margin-left: 8px;">
                            <span style="font-size: 13px;">🏥 عرض ICU</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_manage_icu" id="edit_can_manage_icu" style="margin-left: 8px;">
                            <span style="font-size: 13px;">⚕️ إدارة ICU</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_view_pharmacy" id="edit_can_view_pharmacy" style="margin-left: 8px;">
                            <span style="font-size: 13px;">💊 عرض الصيدلية</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_manage_pharmacy" id="edit_can_manage_pharmacy" style="margin-left: 8px;">
                            <span style="font-size: 13px;">💉 إدارة الصيدلية</span>
                        </label>
                    </div>
                </div>
                
                <!-- Advanced Permissions -->
                <div style="background: #fce4ec; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
                    <h5 style="margin: 0 0 10px 0; color: #c2185b; font-size: 14px;">⚙️ صلاحيات متقدمة</h5>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_manage_users" id="edit_can_manage_users" style="margin-left: 8px;">
                            <span style="font-size: 13px;">👥 إدارة المستخدمين</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_manage_antibiotics" id="edit_can_manage_antibiotics" style="margin-left: 8px;">
                            <span style="font-size: 13px;">💊 إدارة المضادات</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_view_kpi" id="edit_can_view_kpi" style="margin-left: 8px;">
                            <span style="font-size: 13px;">📊 عرض KPI</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_access_advanced_search" id="edit_can_access_advanced_search" style="margin-left: 8px;">
                            <span style="font-size: 13px;">🔍 بحث متقدم</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_view_activity_log" id="edit_can_view_activity_log" style="margin-left: 8px;">
                            <span style="font-size: 13px;">📝 سجل النشاط</span>
                        </label>
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 8px; background: white; border-radius: 6px;">
                            <input type="checkbox" name="can_create_backup" id="edit_can_create_backup" style="margin-left: 8px;">
                            <span style="font-size: 13px;">💾 نسخ احتياطي</span>
                        </label>
                    </div>
                </div>
            </div>
            
            <div style="text-align: center; margin-top: 20px;">
                <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 openAddModal() {
    document.getElementById('addModal').style.display = 'block';
}

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

function openEditModal(user) {
    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;
    
    // Set permissions
    const permissions = [
        'can_view_dashboard', 'can_view_records', 'can_add_records', 'can_edit_records', 'can_delete_records',
        'can_export', 'can_print', 'can_manage_users', 'can_manage_antibiotics', 'can_manage_patients',
        'can_view_reports', 'can_add_reports', 'can_edit_reports', 'can_delete_reports',
        'can_view_icu', 'can_manage_icu', 'can_view_pharmacy', 'can_manage_pharmacy', 'can_view_kpi',
        'can_access_advanced_search', 'can_view_activity_log', 'can_create_backup'
    ];
    
    permissions.forEach(perm => {
        const checkbox = document.getElementById('edit_' + perm);
        if (checkbox) {
            checkbox.checked = user[perm] == 1;
        }
    });
    
    document.getElementById('editModal').style.display = 'block';
}

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'; ?>

