<?php
/**
 * إدارة المستخدمين - نسخة مطورة
 */
use App\Core\Auth;
use App\Core\Tenant;

$userTenantId = Tenant::id();
if (!($auth instanceof Auth) || !$auth->can('users.manage')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى إدارة المستخدمين';
    return;
}

$action = $_GET['action'] ?? 'index';

// معالجة الإجراءات
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $fullName = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $roleId = (int)($_POST['role_id'] ?? 0);
    $isActive = isset($_POST['is_active']) ? 1 : 0;

    if ($fullName !== '' && $username !== '' && $password !== '' && $roleId > 0) {
        // التحقق من قوة كلمة المرور
        $passwordValidation = \App\Core\Auth::validatePasswordStrength($password);
        if (!$passwordValidation['valid']) {
            $_SESSION['users_create_error'] = implode('<br>', $passwordValidation['errors']);
            header('Location: index.php?page=users&action=create');
            exit;
        }
        
        try {
            $stmt = $db->prepare('SELECT COALESCE(sp.max_users, 999) AS mx FROM tenants t LEFT JOIN subscription_plans sp ON sp.id = t.plan_id WHERE t.id = ?');
            $stmt->execute([$userTenantId]);
            $plan = $stmt->fetch();
            $maxUsers = (int)($plan['mx'] ?? 999);
            $stmt = $db->prepare('SELECT COUNT(*) FROM users WHERE tenant_id = ?');
            $stmt->execute([$userTenantId]);
            $currentUsers = (int)$stmt->fetchColumn();
            if ($currentUsers >= $maxUsers) {
                $_SESSION['users_create_error'] = 'تم الوصول لحد المستخدمين المسموح به (' . $maxUsers . '). قم بترقية الاشتراك.';
                header('Location: index.php?page=users&action=create');
                exit;
            }
        } catch (Throwable $e) {}
        $branchId = (int)($_POST['branch_id'] ?? 0);
        if ($roleId === 1) $branchId = null;
        $hash = password_hash($password, PASSWORD_BCRYPT);
        $stmt = $db->prepare(
            'INSERT INTO users (full_name, email, phone, username, password_hash, role_id, branch_id, is_active, tenant_id)
             VALUES (:name, :email, :phone, :username, :hash, :role_id, :branch_id, :active, :tid)'
        );
        $stmt->execute([
            'name' => $fullName,
            'email' => $email !== '' ? $email : null,
            'phone' => $phone !== '' ? $phone : null,
            'username' => $username,
            'hash' => $hash,
            'role_id' => $roleId,
            'branch_id' => $branchId > 0 ? $branchId : null,
            'active' => $isActive,
            'tid' => $userTenantId
        ]);
        $newId = (int)$db->lastInsertId();
        if (isset($auditLog)) {
            $auditLog->log('user_created', 'user', $newId, null, json_encode(['full_name' => $fullName, 'username' => $username], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
        }
        if ($roleId !== 1) {
            $extraBranches = isset($_POST['user_branches']) && is_array($_POST['user_branches']) ? array_map('intval', $_POST['user_branches']) : [];
            foreach ($extraBranches as $eb) {
                if ($eb > 0 && $eb !== $branchId) {
                    try {
                        $db->prepare('INSERT INTO user_branches (user_id, branch_id) VALUES (?, ?)')->execute([$newId, $eb]);
                    } catch (Throwable $e) {}
                }
            }
        }
        $_SESSION['users_msg'] = 'تم إضافة المستخدم بنجاح';
        header('Location: index.php?page=users');
        exit;
    }
}

if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Protection
    if (!\App\Core\CSRFProtection::validatePostRequest()) {
        $_SESSION['users_update_error'] = 'طلب غير صالح. يرجى المحاولة مرة أخرى.';
        header('Location: index.php?page=users');
        exit;
    }
    $id = (int)($_POST['id'] ?? 0);
    $fullName = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $roleId = (int)($_POST['role_id'] ?? 0);
    $isActive = isset($_POST['is_active']) ? 1 : 0;

    if ($id > 0 && $fullName !== '' && $roleId > 0) {
        $stmt = $db->prepare('SELECT id FROM users WHERE id = ? AND tenant_id = ?');
        $stmt->execute([$id, $userTenantId]);
        if (!$stmt->fetch()) { header('Location: index.php?page=users'); exit; }
        $branchId = (int)($_POST['branch_id'] ?? 0);
        if ($roleId === 1) $branchId = null;
        $branchVal = $branchId > 0 ? $branchId : null;
        if ($password !== '') {
            // التحقق من قوة كلمة المرور
            $passwordValidation = \App\Core\Auth::validatePasswordStrength($password);
            if (!$passwordValidation['valid']) {
                $_SESSION['users_update_error'] = implode('<br>', $passwordValidation['errors']);
                header('Location: index.php?page=users&action=edit&id=' . $id);
                exit;
            }
            $hash = password_hash($password, PASSWORD_BCRYPT);
            $stmt = $db->prepare(
                'UPDATE users
                 SET full_name = :name, email = :email, phone = :phone,
                     password_hash = :hash, role_id = :role_id, branch_id = :branch_id, is_active = :active
                 WHERE id = :id'
            );
            $stmt->execute([
                'name' => $fullName,
                'email' => $email !== '' ? $email : null,
                'phone' => $phone !== '' ? $phone : null,
                'hash' => $hash,
                'role_id' => $roleId,
                'branch_id' => $branchVal,
                'active' => $isActive,
                'id' => $id
            ]);
        } else {
            $stmt = $db->prepare(
                'UPDATE users
                 SET full_name = :name, email = :email, phone = :phone,
                     role_id = :role_id, branch_id = :branch_id, is_active = :active
                 WHERE id = :id'
            );
            $stmt->execute([
                'name' => $fullName,
                'email' => $email !== '' ? $email : null,
                'phone' => $phone !== '' ? $phone : null,
                'role_id' => $roleId,
                'branch_id' => $branchVal,
                'active' => $isActive,
                'id' => $id
            ]);
        }
        if (isset($auditLog)) {
            $auditLog->log('user_updated', 'user', $id, null, json_encode(['full_name' => $fullName, 'role_id' => $roleId], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
        }
        if ($roleId !== 1) {
            try {
                $db->prepare('DELETE FROM user_branches WHERE user_id = ?')->execute([$id]);
                $extraBranches = isset($_POST['user_branches']) && is_array($_POST['user_branches']) ? array_map('intval', $_POST['user_branches']) : [];
                foreach ($extraBranches as $eb) {
                    if ($eb > 0 && $eb !== $branchVal) {
                        $db->prepare('INSERT INTO user_branches (user_id, branch_id) VALUES (?, ?)')->execute([$id, $eb]);
                    }
                }
            } catch (Throwable $e) {}
        }
        $_SESSION['users_msg'] = 'تم تحديث المستخدم بنجاح';
        header('Location: index.php?page=users');
        exit;
    }
}

if ($action === 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    if ($id > 0 && $id !== (int)($_SESSION['user_id'] ?? 0)) {
        $stmt = $db->prepare('DELETE FROM users WHERE id = :id AND tenant_id = :tid');
        $stmt->execute(['id' => $id, 'tid' => $userTenantId]);
        if (isset($auditLog)) {
            $auditLog->log('user_deleted', 'user', $id, null, null, $_SESSION['user_id'] ?? null);
        }
        $_SESSION['users_msg'] = 'تم حذف المستخدم بنجاح';
    }
    header('Location: index.php?page=users');
    exit;
}

if ($action === 'toggle_active' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    if ($id > 0 && $id !== (int)($_SESSION['user_id'] ?? 0)) {
        try {
            $stmt = $db->prepare('SELECT is_active FROM users WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$id, $userTenantId]);
            $user = $stmt->fetch();
            if ($user) {
                $newStatus = (int)$user['is_active'] === 1 ? 0 : 1;
                $stmt = $db->prepare('UPDATE users SET is_active = ? WHERE id = ? AND tenant_id = ?');
                $stmt->execute([$newStatus, $id, $userTenantId]);
                if (isset($auditLog)) {
                    $auditLog->log('user_status_changed', 'user', $id, json_encode(['is_active' => (int)$user['is_active']], JSON_UNESCAPED_UNICODE), json_encode(['is_active' => $newStatus], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
                }
                $_SESSION['users_msg'] = 'تم تحديث حالة المستخدم بنجاح';
            }
        } catch (Throwable $e) {}
    }
    header('Location: index.php?page=users');
    exit;
}

if ($action === 'reset_password' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Protection
    if (!\App\Core\CSRFProtection::validatePostRequest()) {
        $_SESSION['users_reset_error'] = 'طلب غير صالح. يرجى المحاولة مرة أخرى.';
        header('Location: index.php?page=users');
        exit;
    }
    $id = (int)($_POST['id'] ?? 0);
    $newPassword = $_POST['new_password'] ?? '';
    
    if ($id > 0 && $newPassword !== '') {
        $stmt = $db->prepare('SELECT id FROM users WHERE id = ? AND tenant_id = ?');
        $stmt->execute([$id, $userTenantId]);
        if ($stmt->fetch()) {
            $passwordValidation = \App\Core\Auth::validatePasswordStrength($newPassword);
            if (!$passwordValidation['valid']) {
                $_SESSION['users_error'] = implode('<br>', $passwordValidation['errors']);
                header('Location: index.php?page=users&action=view&id=' . $id);
                exit;
            }
            $hash = password_hash($newPassword, PASSWORD_BCRYPT);
            $stmt = $db->prepare('UPDATE users SET password_hash = ? WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$hash, $id, $userTenantId]);
            if (isset($auditLog)) {
                $auditLog->log('password_reset', 'user', $id, null, json_encode(['reset_by' => $_SESSION['user_id'] ?? null], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
            }
            $_SESSION['users_msg'] = 'تم إعادة تعيين كلمة المرور بنجاح';
        }
    }
    header('Location: index.php?page=users&action=view&id=' . $id);
    exit;
}

$roles = [];
$users = [];
$userStats = [];

try {
    $stmt = $db->query('SELECT id, name FROM roles ORDER BY id');
    $roles = $stmt->fetchAll();
    
    // إحصائيات المستخدمين
    $userTenantAnd = '';
    try { 
        $db->query('SELECT tenant_id FROM users LIMIT 1'); 
        $userTenantAnd = ' WHERE tenant_id = ' . (int)$userTenantId; 
    } catch (Throwable $e) {}
    
    $stmt = $db->query('SELECT COUNT(*) FROM users' . $userTenantAnd);
    $userStats['total'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->query('SELECT COUNT(*) FROM users' . $userTenantAnd . ' AND is_active = 1');
    $userStats['active'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->query('SELECT COUNT(*) FROM users' . $userTenantAnd . ' AND is_active = 0');
    $userStats['inactive'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare('SELECT COUNT(*) FROM users' . $userTenantAnd . ' AND (last_login_at IS NULL OR last_login_at < DATE_SUB(NOW(), INTERVAL 30 DAY))');
    $stmt->execute();
    $userStats['inactive_30d'] = (int)$stmt->fetchColumn();

    if ($action === 'view' && isset($_GET['id'])) {
        $id = (int)$_GET['id'];
        $stmt = $db->prepare(
            'SELECT u.id, u.full_name, u.email, u.phone, u.username, u.role_id, u.branch_id, u.is_active,
                    u.created_at, u.last_login_at, u.failed_attempts, u.locked_until,
                    r.name AS role_name,
                    b.name AS branch_name
             FROM users u
             JOIN roles r ON r.id = u.role_id
             LEFT JOIN branches b ON b.id = u.branch_id
             WHERE u.id = :id AND u.tenant_id = :tid'
        );
        $stmt->execute(['id' => $id, 'tid' => $userTenantId]);
        $user = $stmt->fetch();
        
        if (!$user) {
            header('Location: index.php?page=users');
            exit;
        }
        
        $userBranches = [];
        try {
            $db->query('SELECT tenant_id FROM branches LIMIT 1');
            $stmtUb = $db->prepare('SELECT b.id, b.name FROM user_branches ub JOIN branches b ON b.id = ub.branch_id WHERE ub.user_id = ? AND b.tenant_id = ?');
            $stmtUb->execute([$id, $userTenantId]);
        } catch (Throwable $e) {
            $stmtUb = $db->prepare('SELECT b.id, b.name FROM user_branches ub JOIN branches b ON b.id = ub.branch_id WHERE ub.user_id = ?');
            $stmtUb->execute([$id]);
        }
        $userBranches = $stmtUb->fetchAll();
        
        // إحصائيات المستخدم
        $userActivity = [];
        try {
            $stmt = $db->prepare('SELECT COUNT(*) FROM audit_log WHERE user_id = ?');
            $stmt->execute([$id]);
            $userActivity['total_actions'] = (int)$stmt->fetchColumn();
            
            $stmt = $db->prepare("SELECT COUNT(*) FROM audit_log WHERE user_id = ? AND action = 'login_success' AND DATE(created_at) = CURDATE()");
            $stmt->execute([$id]);
            $userActivity['today_logins'] = (int)$stmt->fetchColumn();
            
            try {
                $db->query('SELECT tenant_id FROM lab_orders LIMIT 1');
                $stmt = $db->prepare('SELECT COUNT(*) FROM lab_orders WHERE created_by = ? AND tenant_id = ?');
                $stmt->execute([$id, $userTenantId]);
            } catch (Throwable $e) {
                $stmt = $db->prepare('SELECT COUNT(*) FROM lab_orders WHERE created_by = ?');
                $stmt->execute([$id]);
            }
            $userActivity['total_orders'] = (int)$stmt->fetchColumn();
        } catch (Throwable $e) {
            $userActivity = ['total_actions' => 0, 'today_logins' => 0, 'total_orders' => 0];
        }
    } elseif ($action === 'edit' && isset($_GET['id'])) {
        $id = (int)$_GET['id'];
        $stmt = $db->prepare(
            'SELECT id, full_name, email, phone, username, role_id, branch_id, is_active
             FROM users
             WHERE id = :id AND tenant_id = :tid'
        );
        $stmt->execute(['id' => $id, 'tid' => $userTenantId]);
        $user = $stmt->fetch();
        $userBranches = [];
        if (isset($user)) {
            $stmtUb = $db->prepare('SELECT branch_id FROM user_branches WHERE user_id = ?');
            $stmtUb->execute([$id]);
            $userBranches = array_column($stmtUb->fetchAll(), 'branch_id');
        }
    } else {
        $userSearch = trim($_GET['q'] ?? '');
        $userRoleFilter = (int)($_GET['role'] ?? 0);
        $userStatusFilter = $_GET['status'] ?? '';
        $userBranchFilter = (int)($_GET['branch'] ?? 0);
        $userExport = isset($_GET['export']) && $_GET['export'] === 'csv';
        $userPage = max(1, (int)($_GET['p'] ?? 1));
        $userPerPage = 25;
        $userOffset = ($userPage - 1) * $userPerPage;
        
        $sql = 'SELECT u.id, u.full_name, u.email, u.phone, u.username, u.is_active, u.branch_id,
                    u.last_login_at, u.created_at,
                    r.name AS role_name,
                    b.name AS branch_name
             FROM users u
             JOIN roles r ON r.id = u.role_id
             LEFT JOIN branches b ON b.id = u.branch_id';
        $userTenantAnd = '';
        try { $db->query('SELECT tenant_id FROM users LIMIT 1'); $userTenantAnd = ' WHERE u.tenant_id = ' . (int)$userTenantId; } catch (Throwable $e) {}
        
        $whereParts = [];
        $params = [];
        
        if ($userTenantAnd) {
            $whereParts[] = substr($userTenantAnd, 7); // إزالة " WHERE "
        }
        
        if ($userSearch !== '') {
            $whereParts[] = '(u.full_name LIKE ? OR u.username LIKE ? OR u.email LIKE ?)';
            $params[] = '%' . $userSearch . '%';
            $params[] = '%' . $userSearch . '%';
            $params[] = '%' . $userSearch . '%';
        }
        
        if ($userRoleFilter > 0) {
            $whereParts[] = 'u.role_id = ?';
            $params[] = $userRoleFilter;
        }
        
        if ($userStatusFilter === 'active') {
            $whereParts[] = 'u.is_active = 1';
        } elseif ($userStatusFilter === 'inactive') {
            $whereParts[] = 'u.is_active = 0';
        }
        
        if ($userBranchFilter > 0) {
            $whereParts[] = '(u.branch_id = ? OR EXISTS (SELECT 1 FROM user_branches ub WHERE ub.user_id = u.id AND ub.branch_id = ?))';
            $params[] = $userBranchFilter;
            $params[] = $userBranchFilter;
        }
        
        $where = !empty($whereParts) ? ' WHERE ' . implode(' AND ', $whereParts) : '';
        $order = ' ORDER BY u.id DESC';
        
        if ($userExport) {
            $stmt = $db->prepare($sql . $where . $order);
            $stmt->execute($params);
            $users = $stmt->fetchAll();
            header('Content-Type: text/csv; charset=UTF-8');
            header('Content-Disposition: attachment; filename="users_' . date('Y-m-d') . '.csv"');
            echo "\xEF\xBB\xBF";
            echo "المعرف,الاسم,اسم المستخدم,البريد,الهاتف,الدور,الفرع,الحالة,آخر دخول,تاريخ الإنشاء\n";
            foreach ($users as $u) {
                $line = [
                    $u['id'], 
                    $u['full_name'], 
                    $u['username'], 
                    $u['email'] ?? '', 
                    $u['phone'] ?? '', 
                    $u['role_name'], 
                    $u['branch_name'] ?? 'الكل', 
                    ((int)$u['is_active'] === 1) ? 'فعّال' : 'موقوف',
                    $u['last_login_at'] ?? 'لم يسجل دخول',
                    $u['created_at'] ?? ''
                ];
                $escaped = [];
                foreach ($line as $v) {
                    $v = (string)$v;
                    if (strpbrk($v, ",\"\n\r") !== false) $v = '"' . str_replace('"', '""', $v) . '"';
                    $escaped[] = $v;
                }
                echo implode(',', $escaped) . "\n";
            }
            exit;
        }
        $limit = ' LIMIT ' . (int)$userPerPage . ' OFFSET ' . (int)$userOffset;
        $stmt = $db->prepare($sql . $where . $order . $limit);
        $stmt->execute($params);
        $users = $stmt->fetchAll();
        $cntSql = 'SELECT COUNT(*) FROM users u JOIN roles r ON r.id = u.role_id LEFT JOIN branches b ON b.id = u.branch_id' . $where;
        $stmt = $db->prepare($cntSql);
        $stmt->execute($params);
        $userTotal = (int)($stmt->fetchColumn() ?? 0);
        $userTotalPages = $userTotal > 0 ? (int)ceil($userTotal / $userPerPage) : 1;
    }
    $branches = [];
    try {
        $db->query('SELECT tenant_id FROM branches LIMIT 1');
        $stmt = $db->prepare('SELECT id, name FROM branches WHERE is_active = 1 AND tenant_id = ? ORDER BY name');
        $stmt->execute([$userTenantId]);
    } catch (Throwable $e) {
        $stmt = $db->query('SELECT id, name FROM branches WHERE is_active = 1 ORDER BY name');
    }
    $branches = $stmt->fetchAll();
} catch (Throwable $e) {
    $branches = [];
    $userStats = ['total' => 0, 'active' => 0, 'inactive' => 0, 'inactive_30d' => 0];
}

// عرض صفحة التفاصيل
if ($action === 'view' && isset($user)) {
    ?>
    <div class="page-header">
        <h1>تفاصيل المستخدم</h1>
        <div class="actions-bar">
            <a href="index.php?page=users&action=edit&id=<?php echo (int)$user['id']; ?>" class="btn-primary">✏️ تعديل</a>
            <a href="index.php?page=users" class="btn-secondary">رجوع</a>
        </div>
    </div>
    
    <?php if (!empty($_SESSION['users_msg'])): ?>
    <div class="alert alert-success" style="margin-bottom:16px;"><?php echo htmlspecialchars($_SESSION['users_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['users_msg']); ?></div>
    <?php endif; ?>
    <?php if (!empty($_SESSION['users_error'])): ?>
    <div class="alert alert-danger" style="margin-bottom:16px;"><?php echo e($_SESSION['users_error']); unset($_SESSION['users_error']); ?></div>
    <?php endif; ?>
    
    <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:16px;margin-bottom:24px;">
        <div class="card" style="text-align:center;">
            <div style="font-size:2rem;font-weight:bold;color:var(--primary);"><?php echo number_format($userActivity['total_actions'] ?? 0); ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">إجمالي الإجراءات</div>
        </div>
        <div class="card" style="text-align:center;">
            <div style="font-size:2rem;font-weight:bold;color:var(--success);"><?php echo number_format($userActivity['today_logins'] ?? 0); ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">دخول اليوم</div>
        </div>
        <div class="card" style="text-align:center;">
            <div style="font-size:2rem;font-weight:bold;color:var(--info);"><?php echo number_format($userActivity['total_orders'] ?? 0); ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">إجمالي الطلبات</div>
        </div>
    </div>
    
    <div class="card" style="margin-bottom:16px;">
        <h3 style="margin-top:0;">المعلومات الأساسية</h3>
        <div class="form-grid">
            <div>
                <label>الاسم الكامل</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><?php echo htmlspecialchars($user['full_name'], ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label>اسم المستخدم</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><code><?php echo htmlspecialchars($user['username'], ENT_QUOTES, 'UTF-8'); ?></code></div>
            </div>
            <div>
                <label>البريد الإلكتروني</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><?php echo htmlspecialchars($user['email'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label>رقم الهاتف</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><?php echo htmlspecialchars($user['phone'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label>الدور</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><?php echo htmlspecialchars($user['role_name'], ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label>الفرع الأساسي</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><?php echo htmlspecialchars($user['branch_name'] ?? 'الكل', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label>الحالة</label>
                <div style="padding:8px;">
                    <span class="badge badge-<?php echo (int)$user['is_active'] === 1 ? 'completed' : 'cancelled'; ?>">
                        <?php echo (int)$user['is_active'] === 1 ? 'فعّال' : 'موقوف'; ?>
                    </span>
                </div>
            </div>
            <div>
                <label>تاريخ الإنشاء</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><?php echo $user['created_at'] ? date('Y-m-d H:i', strtotime($user['created_at'])) : '-'; ?></div>
            </div>
            <div>
                <label>آخر دخول</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;">
                    <?php if ($user['last_login_at']): ?>
                        <?php echo date('Y-m-d H:i', strtotime($user['last_login_at'])); ?>
                        <span style="color:var(--text-muted);font-size:0.85rem;">
                            (<?php 
                            $daysAgo = floor((time() - strtotime($user['last_login_at'])) / 86400);
                            echo $daysAgo === 0 ? 'اليوم' : ($daysAgo === 1 ? 'أمس' : "منذ {$daysAgo} يوم");
                            ?>)
                        </span>
                    <?php else: ?>
                        <span style="color:var(--text-muted);">لم يسجل دخول</span>
                    <?php endif; ?>
                </div>
            </div>
            <?php if ((int)$user['failed_attempts'] > 0): ?>
            <div>
                <label>محاولات دخول فاشلة</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;">
                    <span class="badge badge-warning"><?php echo (int)$user['failed_attempts']; ?></span>
                </div>
            </div>
            <?php endif; ?>
            <?php if ($user['locked_until']): ?>
            <div>
                <label>مقفل حتى</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;">
                    <span class="badge badge-danger"><?php echo date('Y-m-d H:i', strtotime($user['locked_until'])); ?></span>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <?php if (!empty($userBranches)): ?>
    <div class="card" style="margin-bottom:16px;">
        <h3 style="margin-top:0;">الفروع الإضافية</h3>
        <div style="display:flex;flex-wrap:wrap;gap:8px;">
            <?php foreach ($userBranches as $ub): ?>
            <span class="badge badge-info"><?php echo htmlspecialchars($ub['name'], ENT_QUOTES, 'UTF-8'); ?></span>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
    
    <div class="card">
        <h3 style="margin-top:0;">إعادة تعيين كلمة المرور</h3>
        <form method="post" action="index.php?page=users&action=reset_password" style="max-width:400px;">
            <input type="hidden" name="id" value="<?php echo (int)$user['id']; ?>">
            <div style="margin-bottom:12px;">
                <label>كلمة المرور الجديدة</label>
                <input type="password" name="new_password" id="reset-password-input" required oninput="validatePasswordStrength(this.value, 'reset-password-strength')">
                <div id="reset-password-strength" style="margin-top:8px;font-size:0.85rem;"></div>
            </div>
            <div>
                <button type="submit" class="btn-primary">إعادة تعيين</button>
            </div>
        </form>
    </div>
    <?php
    return;
}

if ($action === 'create' || ($action === 'edit' && isset($user))) {
    $editing = $action === 'edit';
    $userId = $editing ? (int)$user['id'] : 0;
    $userBranches = $editing ? ($userBranches ?? []) : [];
    $fullName = $editing ? (string)$user['full_name'] : '';
    $email = $editing ? (string)($user['email'] ?? '') : '';
    $phone = $editing ? (string)($user['phone'] ?? '') : '';
    $username = $editing ? (string)$user['username'] : '';
    $roleId = $editing ? (int)$user['role_id'] : 0;
    $branchId = $editing ? ((int)($user['branch_id'] ?? 0)) : 0;
    $isActive = $editing ? ((int)$user['is_active'] === 1) : true;
    ?>
    <div class="page-header">
        <h1><?php echo $editing ? 'تعديل مستخدم' : 'إضافة مستخدم'; ?></h1>
    </div>
    <div class="card">
    <?php if (!empty($_SESSION['users_create_error'])): ?>
    <div class="alert alert-danger"><?php echo e($_SESSION['users_create_error']); unset($_SESSION['users_create_error']); ?></div>
    <?php endif; ?>
    <?php if (!empty($_SESSION['users_update_error'])): ?>
    <div class="alert alert-danger"><?php echo e($_SESSION['users_update_error']); unset($_SESSION['users_update_error']); ?></div>
    <?php endif; ?>
    <form method="post" class="form-grid">
        <?php if ($editing): ?>
            <input type="hidden" name="id" value="<?php echo $userId; ?>">
        <?php endif; ?>
        <div>
            <label>الاسم الكامل</label>
            <input type="text" name="full_name" required value="<?php echo htmlspecialchars($fullName, ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>اسم المستخدم</label>
            <input type="text" name="username" <?php echo $editing ? 'readonly' : 'required'; ?> value="<?php echo htmlspecialchars($username, ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>البريد الإلكتروني</label>
            <input type="email" name="email" value="<?php echo htmlspecialchars($email, ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>رقم الهاتف</label>
            <input type="text" name="phone" value="<?php echo htmlspecialchars($phone, ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>الدور</label>
            <select name="role_id" required>
                <option value="">اختر الدور</option>
                <?php foreach ($roles as $r): ?>
                    <option value="<?php echo (int)$r['id']; ?>" <?php echo $roleId === (int)$r['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($r['name'], ENT_QUOTES, 'UTF-8'); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>الفرع الأساسي (لغير المديرين)</label>
            <select name="branch_id">
                <option value="">كل الفروع (مدير)</option>
                <?php foreach ($branches as $br): ?>
                    <option value="<?php echo (int)$br['id']; ?>" <?php echo $branchId === (int)$br['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($br['name'], ENT_QUOTES, 'UTF-8'); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php if ($roleId !== 1 && count($branches) > 1): ?>
        <div class="full-width">
            <label>فروع إضافية (للتنقل بينها)</label>
            <div style="display:flex;flex-wrap:wrap;gap:8px;">
                <?php foreach ($branches as $br): $bid = (int)$br['id']; if ($bid === $branchId) continue; ?>
                <label class="settings-checkbox">
                    <input type="checkbox" name="user_branches[]" value="<?php echo $bid; ?>" <?php echo in_array($bid, $userBranches) ? 'checked' : ''; ?>>
                    <?php echo htmlspecialchars($br['name'], ENT_QUOTES, 'UTF-8'); ?>
                </label>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        <div>
            <label>كلمة المرور <?php echo $editing ? '(اتركها فارغة للإبقاء على الحالية)' : ''; ?></label>
            <input type="password" name="password" id="password-input" <?php echo $editing ? '' : 'required'; ?> oninput="validatePasswordStrength(this.value)">
            <div id="password-strength" style="margin-top:8px;font-size:0.85rem;"></div>
        </div>
        <div class="full-width">
            <label class="settings-checkbox">
                <input type="checkbox" name="is_active" value="1" <?php echo $isActive ? 'checked' : ''; ?>>
                مستخدم فعّال
            </label>
        </div>
        <div class="full-width form-actions">
            <button type="submit"><?php echo $editing ? 'حفظ التعديلات' : 'إضافة'; ?></button>
            <a href="index.php?page=users" class="btn-secondary">رجوع</a>
        </div>
    </form>
    </div>
    <?php
    return;
}

$userSearch = trim($_GET['q'] ?? '');
$userRoleFilter = (int)($_GET['role'] ?? 0);
$userStatusFilter = $_GET['status'] ?? '';
$userBranchFilter = (int)($_GET['branch'] ?? 0);
?>
<div class="page-header">
    <h1>👥 إدارة المستخدمين</h1>
    <div class="actions-bar" style="flex-wrap:wrap;gap:12px;">
        <a href="index.php?page=users&action=create" class="btn-primary">➕ مستخدم جديد</a>
        <a href="index.php?page=security" class="btn-secondary">🔒 الأمان</a>
    </div>
</div>

<?php if (!empty($_SESSION['users_msg'])): ?>
<div class="alert alert-success" style="margin-bottom:16px;"><?php echo htmlspecialchars($_SESSION['users_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['users_msg']); ?></div>
<?php endif; ?>

<!-- إحصائيات -->
<div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:16px;margin-bottom:24px;">
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--primary);"><?php echo number_format($userStats['total']); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">إجمالي المستخدمين</div>
    </div>
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--success);"><?php echo number_format($userStats['active']); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">نشط</div>
    </div>
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--danger);"><?php echo number_format($userStats['inactive']); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">موقوف</div>
    </div>
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--warning);"><?php echo number_format($userStats['inactive_30d']); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">غير نشط (30 يوم)</div>
    </div>
</div>

<!-- الفلترة والبحث -->
<div class="card" style="margin-bottom:16px;">
    <form method="get" action="index.php" style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:12px;align-items:end;">
        <input type="hidden" name="page" value="users">
        <div>
            <label>بحث</label>
            <input type="search" name="q" placeholder="اسم، اسم مستخدم، بريد..." value="<?php echo htmlspecialchars($userSearch, ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>الدور</label>
            <select name="role">
                <option value="">الكل</option>
                <?php foreach ($roles as $r): ?>
                    <option value="<?php echo (int)$r['id']; ?>" <?php echo $userRoleFilter === (int)$r['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($r['name'], ENT_QUOTES, 'UTF-8'); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>الحالة</label>
            <select name="status">
                <option value="">الكل</option>
                <option value="active" <?php echo $userStatusFilter === 'active' ? 'selected' : ''; ?>>فعّال</option>
                <option value="inactive" <?php echo $userStatusFilter === 'inactive' ? 'selected' : ''; ?>>موقوف</option>
            </select>
        </div>
        <div>
            <label>الفرع</label>
            <select name="branch">
                <option value="">الكل</option>
                <?php foreach ($branches as $br): ?>
                    <option value="<?php echo (int)$br['id']; ?>" <?php echo $userBranchFilter === (int)$br['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($br['name'], ENT_QUOTES, 'UTF-8'); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <button type="submit" class="btn-primary">بحث</button>
            <?php if ($userSearch || $userRoleFilter || $userStatusFilter || $userBranchFilter): ?>
                <a href="index.php?page=users" class="btn-secondary">إلغاء</a>
            <?php endif; ?>
        </div>
    </form>
    <div style="margin-top:12px;">
        <a href="index.php?page=users&export=csv<?php 
            $exportParams = [];
            if ($userSearch) $exportParams[] = 'q=' . urlencode($userSearch);
            if ($userRoleFilter) $exportParams[] = 'role=' . $userRoleFilter;
            if ($userStatusFilter) $exportParams[] = 'status=' . urlencode($userStatusFilter);
            if ($userBranchFilter) $exportParams[] = 'branch=' . $userBranchFilter;
            echo !empty($exportParams) ? '&' . implode('&', $exportParams) : '';
        ?>" class="btn-secondary">📥 تصدير CSV</a>
    </div>
</div>

<!-- الجدول -->
<div class="table-wrapper">
<table class="table">
    <thead>
        <tr>
            <th>#</th>
            <th>الاسم</th>
            <th>اسم المستخدم</th>
            <th>البريد</th>
            <th>الدور</th>
            <th>الفرع</th>
            <th>آخر دخول</th>
            <th>الحالة</th>
            <th>الإجراءات</th>
        </tr>
    </thead>
    <tbody>
    <?php if (empty($users)): ?>
        <tr><td colspan="9" style="text-align:center;padding:24px;color:var(--text-muted);">لا توجد نتائج</td></tr>
    <?php else: ?>
    <?php foreach ($users as $u): ?>
        <tr>
            <td><?php echo (int)$u['id']; ?></td>
            <td>
                <strong><?php echo htmlspecialchars($u['full_name'], ENT_QUOTES, 'UTF-8'); ?></strong>
                <?php if ($u['email']): ?>
                    <div style="font-size:0.85rem;color:var(--text-muted);"><?php echo htmlspecialchars($u['email'], ENT_QUOTES, 'UTF-8'); ?></div>
                <?php endif; ?>
            </td>
            <td><code><?php echo htmlspecialchars($u['username'], ENT_QUOTES, 'UTF-8'); ?></code></td>
            <td><?php echo htmlspecialchars($u['email'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
            <td><span class="badge badge-info"><?php echo htmlspecialchars($u['role_name'], ENT_QUOTES, 'UTF-8'); ?></span></td>
            <td><?php echo htmlspecialchars($u['branch_name'] ?? 'الكل', ENT_QUOTES, 'UTF-8'); ?></td>
            <td>
                <?php if ($u['last_login_at']): ?>
                    <div style="font-size:0.85rem;"><?php echo date('Y-m-d', strtotime($u['last_login_at'])); ?></div>
                    <div style="font-size:0.75rem;color:var(--text-muted);"><?php echo date('H:i', strtotime($u['last_login_at'])); ?></div>
                <?php else: ?>
                    <span style="color:var(--text-muted);font-size:0.85rem;">لم يسجل دخول</span>
                <?php endif; ?>
            </td>
            <td>
                <span class="badge badge-<?php echo (int)$u['is_active'] === 1 ? 'completed' : 'cancelled'; ?>">
                    <?php echo (int)$u['is_active'] === 1 ? 'فعّال' : 'موقوف'; ?>
                </span>
            </td>
            <td>
                <div style="display:flex;gap:8px;flex-wrap:wrap;">
                    <a href="index.php?page=users&action=view&id=<?php echo (int)$u['id']; ?>" class="btn-link">👁️ عرض</a>
                    <a href="index.php?page=users&action=edit&id=<?php echo (int)$u['id']; ?>" class="btn-link">✏️ تعديل</a>
                    <?php if ((int)$u['id'] !== (int)($_SESSION['user_id'] ?? 0)): ?>
                        <a href="index.php?page=users&action=toggle_active&id=<?php echo (int)$u['id']; ?>" 
                           class="btn-link" 
                           style="color:<?php echo (int)$u['is_active'] === 1 ? 'var(--danger)' : 'var(--success)'; ?>;"
                           onclick="return confirm('<?php echo (int)$u['is_active'] === 1 ? 'تعطيل' : 'تفعيل'; ?> هذا المستخدم؟');">
                            <?php echo (int)$u['is_active'] === 1 ? '⏸️ تعطيل' : '▶️ تفعيل'; ?>
                        </a>
                        <a href="index.php?page=users&action=delete&id=<?php echo (int)$u['id']; ?>" 
                           class="btn-link" 
                           style="color:var(--danger);"
                           onclick="return confirm('هل أنت متأكد من حذف هذا المستخدم؟');">🗑️ حذف</a>
                    <?php endif; ?>
                </div>
            </td>
        </tr>
    <?php endforeach; ?>
    <?php endif; ?>
    </tbody>
</table>
</div>

<?php if (isset($userTotalPages) && $userTotalPages > 1): ?>
<div class="pagination" style="margin-top:16px;">
    <?php 
    $baseParams = ['page' => 'users'];
    if ($userSearch) $baseParams['q'] = $userSearch;
    if ($userRoleFilter) $baseParams['role'] = $userRoleFilter;
    if ($userStatusFilter) $baseParams['status'] = $userStatusFilter;
    if ($userBranchFilter) $baseParams['branch'] = $userBranchFilter;
    $baseUrl = 'index.php?' . http_build_query($baseParams);
    for ($i = 1; $i <= min($userTotalPages, 10); $i++): 
        $active = $i === $userPage ? ' style="font-weight:bold;"' : ''; 
    ?>
        <a href="<?php echo $baseUrl . '&p=' . $i; ?>"<?php echo $active; ?>><?php echo $i; ?></a>
    <?php endfor; ?>
</div>
<?php endif; ?>

<script>
function validatePasswordStrength(password, targetId = 'password-strength') {
    const strengthDiv = document.getElementById(targetId);
    if (!strengthDiv) return;
    
    if (!password) {
        strengthDiv.innerHTML = '';
        return;
    }
    
    const config = {
        minLength: 8,
        requireUppercase: true,
        requireLowercase: true,
        requireNumbers: true,
        requireSpecial: false
    };
    
    const errors = [];
    const checks = [];
    
    if (password.length < config.minLength) {
        errors.push(`يجب أن تكون على الأقل ${config.minLength} أحرف`);
    } else {
        checks.push('✓ الطول مناسب');
    }
    
    if (config.requireUppercase && !/[A-Z]/.test(password)) {
        errors.push('يجب أن تحتوي على حرف كبير');
    } else if (config.requireUppercase) {
        checks.push('✓ حرف كبير');
    }
    
    if (config.requireLowercase && !/[a-z]/.test(password)) {
        errors.push('يجب أن تحتوي على حرف صغير');
    } else if (config.requireLowercase) {
        checks.push('✓ حرف صغير');
    }
    
    if (config.requireNumbers && !/[0-9]/.test(password)) {
        errors.push('يجب أن تحتوي على رقم');
    } else if (config.requireNumbers) {
        checks.push('✓ رقم');
    }
    
    if (errors.length > 0) {
        strengthDiv.innerHTML = '<div style="color:var(--danger);">' + errors.join('<br>') + '</div>';
    } else {
        strengthDiv.innerHTML = '<div style="color:var(--success);">' + checks.join(' • ') + '</div>';
    }
}
</script>
