<?php
require_once __DIR__ . '/config/db.php';
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// حماية الصفحة: التأكد من تسجيل الدخول وصلاحية الآدمن
if (empty($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: login.php');
    exit;
}

// اللغة
$lang = ($_GET['lang'] ?? 'ar') === 'en' ? 'en' : 'ar';
$is_ar = $lang === 'ar';

function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

$msg = '';
$err = '';

// معالجة العمليات (POST) - إضافة وتعديل
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    try {
        if ($action === 'add') {
            $username = trim($_POST['username'] ?? '');
            $password = trim($_POST['password'] ?? '');
            $role = $_POST['role'] ?? 'user';
            
            if (!$username || !$password) throw new Exception($is_ar ? 'يرجى ملء جميع الحقول' : 'Fill all fields');
            
            $check = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $check->execute([$username]);
            if ($check->fetch()) throw new Exception($is_ar ? 'اسم المستخدم موجود مسبقاً' : 'Username exists');
            
            $hashed = password_hash($password, PASSWORD_DEFAULT);
            $pdo->prepare("INSERT INTO users (username, password, role, created_at) VALUES (?, ?, ?, NOW())")
                ->execute([$username, $hashed, $role]);
            $msg = $is_ar ? '✅ تم إضافة المستخدم بنجاح' : 'User added successfully';
            
        } elseif ($action === 'edit') {
            $id = (int)$_POST['id'];
            $username = trim($_POST['username'] ?? '');
            $role = $_POST['role'] ?? 'user';
            
            $sql = "UPDATE users SET username = ?, role = ?";
            $params = [$username, $role];
            
            if (!empty($_POST['password'])) {
                $sql .= ", password = ?";
                $params[] = password_hash($_POST['password'], PASSWORD_DEFAULT);
            }
            
            $sql .= " WHERE id = ?";
            $params[] = $id;
            
            $pdo->prepare($sql)->execute($params);
            $msg = $is_ar ? '✏️ تم تحديث البيانات بنجاح' : 'User updated successfully';
        }
    } catch (Throwable $e) {
        $err = $e->getMessage();
    }
}

// معالجة العمليات (GET) - حذف، ريست، تغيير صلاحية سريع
if (isset($_GET['action']) && isset($_GET['id'])) {
    $target_id = (int)$_GET['id'];
    
    if ($target_id == $_SESSION['user_id'] && $_GET['action'] !== 'reset') {
        $err = $is_ar ? 'لا يمكنك حذف أو تغيير صلاحية حسابك الحالي' : 'You cannot delete/toggle your own account';
    } else {
        switch($_GET['action']) {
            case 'reset':
                $new_password = password_hash('123456', PASSWORD_DEFAULT);
                $pdo->prepare("UPDATE users SET password = ? WHERE id = ?")->execute([$new_password, $target_id]);
                $msg = $is_ar ? '🔄 تم تصفير كلمة المرور إلى (123456)' : 'Password reset to (123456)';
                break;
            case 'delete':
                $pdo->prepare("DELETE FROM users WHERE id = ?")->execute([$target_id]);
                $msg = $is_ar ? '🗑️ تم حذف الحساب نهائياً' : 'User deleted permanently';
                break;
            case 'toggle_role':
                $stmt = $pdo->prepare("SELECT role FROM users WHERE id = ?");
                $stmt->execute([$target_id]);
                $next_role = ($stmt->fetchColumn() === 'admin') ? 'user' : 'admin';
                $pdo->prepare("UPDATE users SET role = ? WHERE id = ?")->execute([$next_role, $target_id]);
                $msg = $is_ar ? '🛡️ تم تحديث الصلاحية بنجاح' : 'Role updated successfully';
                break;
        }
    }
}

// جلب المستخدمين مع البحث
$search = $_GET['q'] ?? '';
$sql = "SELECT id, username, role, last_login, created_at FROM users";
if ($search) {
    $sql .= " WHERE username LIKE " . $pdo->quote("%$search%");
}
$sql .= " ORDER BY id ASC";
$users = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html lang="<?= esc($is_ar ? 'ar' : 'en') ?>" dir="<?= $is_ar ? 'rtl' : 'ltr' ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title><?= $is_ar ? 'إدارة المستخدمين | Top Accessories' : 'User Management | Top Accessories' ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary: #2563eb;
            --primary-light: #eff6ff;
            --bg-body: #f8fafc;
            --card-shadow: 0 10px 40px -10px rgba(0, 0, 0, 0.05);
            --border: #e2e8f0;
        }

        body {
            font-family: <?= $is_ar ? "'Cairo', sans-serif" : "'Inter', sans-serif" ?>;
            background-color: var(--bg-body);
            color: #1e293b;
            padding: 40px 0;
        }

        .bg-pattern {
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            z-index: -1;
            background-image: radial-gradient(#cbd5e1 1px, transparent 1px);
            background-size: 30px 30px;
            opacity: 0.3;
        }

        .container { max-width: 1100px; }

        .glass-card {
            background: #ffffff;
            border-radius: 24px;
            border: 1px solid var(--border);
            box-shadow: var(--card-shadow);
            overflow: hidden;
            margin-bottom: 30px;
        }

        .search-area {
            padding: 24px;
            background: #ffffff;
            border-bottom: 1px solid var(--border);
            display: flex; gap: 15px; align-items: center;
        }

        .search-input {
            flex-grow: 1; border: 1px solid var(--border);
            padding: 10px 18px; border-radius: 12px; font-size: 0.95rem; background: #fcfcfd;
        }

        .table thead th {
            background: #f8fafc; color: #64748b; font-size: 0.75rem;
            text-transform: uppercase; padding: 18px 24px; font-weight: 700; border: 0;
        }
        .table tbody td { padding: 16px 24px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; }

        .user-icon {
            width: 40px; height: 40px; background: var(--primary-light); color: var(--primary);
            border-radius: 10px; display: flex; align-items: center; justify-content: center;
            font-weight: 700; font-size: 1rem;
        }

        .badge-system {
            padding: 6px 12px; border-radius: 50px; font-size: 0.7rem; font-weight: 700;
            text-decoration: none; transition: all 0.2s;
        }
        .badge-admin { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
        .badge-user { background: #f1f5f9; color: #475569; border: 1px solid #e2e8f0; }

        .action-icon {
            width: 34px; height: 34px; border-radius: 10px; display: inline-flex;
            align-items: center; justify-content: center; background: #fff;
            border: 1px solid var(--border); color: #64748b; transition: all 0.2s;
            margin: 0 2px; cursor: pointer; text-decoration: none;
        }
        .action-icon:hover { color: var(--primary); border-color: var(--primary); }
        .icon-delete:hover { color: #dc2626; border-color: #fecaca; background: #fef2f2; }

        .modal-content { border-radius: 24px; border: none; padding: 15px; }
        .form-control-pro { border-radius: 12px; padding: 12px; border: 1.5px solid var(--border); margin-bottom: 15px; }
    </style>
</head>
<body>

    <div class="bg-pattern"></div>

    <div class="container">
        <!-- Dashboard Top Navigation -->
        <div class="d-flex justify-content-between align-items-center mb-5">
            <div class="d-flex gap-2">
                <a href="index.php" class="btn btn-light rounded-pill px-4 fw-bold shadow-sm">🏠 <?= $is_ar ? 'الرئيسية' : 'Home' ?></a>
                <a href="?lang=<?= $is_ar ? 'en' : 'ar' ?>" class="btn btn-light rounded-pill px-4 fw-bold shadow-sm">🌐</a>
            </div>
            <a href="logout.php" class="btn btn-outline-danger rounded-pill px-4 fw-bold shadow-sm"><?= $is_ar ? 'خروج' : 'Logout' ?></a>
        </div>

        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="fw-bold fs-3 m-0"><?= $is_ar ? 'إدارة أعضاء النظام' : 'User Management' ?></h1>
                <p class="text-muted small m-0"><?= $is_ar ? 'تحكم كامل في المستخدمين والصلاحيات' : 'Full control over system access' ?></p>
            </div>
            <button class="btn btn-primary rounded-pill px-4 py-2 fw-bold shadow" data-bs-toggle="modal" data-bs-target="#addModal">
                + <?= $is_ar ? 'إضافة مستخدم' : 'Add User' ?>
            </button>
        </div>

        <!-- Feedback Messages -->
        <?php if ($msg): ?><div class="alert alert-success border-0 shadow-sm rounded-4 mb-4"><?= esc($msg) ?></div><?php endif; ?>
        <?php if ($err): ?><div class="alert alert-danger border-0 shadow-sm rounded-4 mb-4"><?= esc($err) ?></div><?php endif; ?>

        <!-- Table Card -->
        <div class="glass-card">
            <div class="search-area">
                <form action="" method="get" class="d-flex w-100 gap-2">
                    <input type="text" name="q" value="<?= esc($search) ?>" class="search-input" placeholder="<?= $is_ar ? 'ابحث عن مستخدم...' : 'Search users...' ?>">
                    <button type="submit" class="btn btn-primary rounded-3 px-4"><?= $is_ar ? 'بحث' : 'Search' ?></button>
                </form>
            </div>

            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th><?= $is_ar ? 'المستخدم' : 'User' ?></th>
                            <th><?= $is_ar ? 'الصلاحية' : 'Role' ?></th>
                            <th><?= $is_ar ? 'آخر ظهور' : 'Activity' ?></th>
                            <th class="text-center"><?= $is_ar ? 'خيارات' : 'Actions' ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $u): ?>
                        <tr>
                            <td class="text-muted small"><?= $u['id'] ?></td>
                            <td>
                                <div class="d-flex align-items-center gap-3">
                                    <div class="user-icon"><?= strtoupper(substr($u['username'], 0, 1)) ?></div>
                                    <div class="fw-bold"><?= esc($u['username']) ?></div>
                                </div>
                            </td>
                            <td>
                                <a href="?action=toggle_role&id=<?= $u['id'] ?>" 
                                   class="badge-system <?= $u['role'] === 'admin' ? 'badge-admin' : 'badge-user' ?>">
                                   <?= strtoupper($u['role']) ?>
                                </a>
                            </td>
                            <td class="text-muted small">
                                <?= $u['last_login'] ? date('Y-m-d H:i', strtotime($u['last_login'])) : '---' ?>
                            </td>
                            <td class="text-center">
                                <!-- Edit Button (Modal Trigger) -->
                                <button class="action-icon" data-bs-toggle="modal" data-bs-target="#editModal" 
                                        data-id="<?= $u['id'] ?>" data-username="<?= esc($u['username']) ?>" data-role="<?= esc($u['role']) ?>">
                                    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
                                </button>
                                <!-- Fast Reset -->
                                <a href="?action=reset&id=<?= $u['id'] ?>" class="action-icon" onclick="return confirm('<?= $is_ar ? 'تصفير لـ 123456؟' : 'Reset to 123456?' ?>')">
                                    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>
                                </a>
                                <!-- Delete -->
                                <a href="?action=delete&id=<?= $u['id'] ?>" class="action-icon icon-delete" onclick="return confirm('<?= $is_ar ? 'حذف نهائي؟' : 'Delete user?' ?>')">
                                    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Modal: Add -->
    <div class="modal fade" id="addModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <form method="post" class="modal-content shadow-lg">
                <input type="hidden" name="action" value="add">
                <div class="modal-header border-0"><h5 class="fw-bold"><?= $is_ar ? 'مستخدم جديد' : 'New User' ?></h5></div>
                <div class="modal-body">
                    <label class="small fw-bold mb-2"><?= $is_ar ? 'اسم المستخدم' : 'Username' ?></label>
                    <input name="username" class="form-control form-control-pro" required>
                    <label class="small fw-bold mb-2"><?= $is_ar ? 'كلمة المرور' : 'Password' ?></label>
                    <input name="password" type="password" class="form-control form-control-pro" required>
                    <label class="small fw-bold mb-2"><?= $is_ar ? 'الصلاحية' : 'Role' ?></label>
                    <select name="role" class="form-select form-control-pro">
                        <option value="user">USER</option>
                        <option value="admin">ADMIN</option>
                    </select>
                    <button class="btn btn-primary w-100 rounded-pill py-3 fw-bold"><?= $is_ar ? 'إضافة الحساب' : 'Create Account' ?></button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal: Edit -->
    <div class="modal fade" id="editModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <form method="post" class="modal-content shadow-lg">
                <input type="hidden" name="action" value="edit">
                <input type="hidden" name="id" id="edit-id">
                <div class="modal-header border-0"><h5 class="fw-bold"><?= $is_ar ? 'تعديل البيانات' : 'Edit User' ?></h5></div>
                <div class="modal-body">
                    <label class="small fw-bold mb-2"><?= $is_ar ? 'اسم المستخدم' : 'Username' ?></label>
                    <input name="username" id="edit-username" class="form-control form-control-pro" required>
                    <label class="small fw-bold mb-2"><?= $is_ar ? 'كلمة المرور الجديدة (اختياري)' : 'New Password (optional)' ?></label>
                    <input name="password" type="password" class="form-control form-control-pro" placeholder="••••••••">
                    <label class="small fw-bold mb-2"><?= $is_ar ? 'الصلاحية' : 'Role' ?></label>
                    <select name="role" id="edit-role" class="form-select form-control-pro">
                        <option value="user">USER</option>
                        <option value="admin">ADMIN</option>
                    </select>
                    <button class="btn btn-primary w-100 rounded-pill py-3 fw-bold"><?= $is_ar ? 'تحديث البيانات' : 'Update User' ?></button>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const editModal = document.getElementById('editModal');
        editModal.addEventListener('show.bs.modal', e => {
            const btn = e.relatedTarget;
            document.getElementById('edit-id').value = btn.getAttribute('data-id');
            document.getElementById('edit-username').value = btn.getAttribute('data-username');
            document.getElementById('edit-role').value = btn.getAttribute('data-role');
        });
    </script>
</body>
</html>