<?php
session_start();

// 1. إدارة اللغة والجلسة
if (isset($_GET['lang'])) {
    $_SESSION['lang'] = $_GET['lang'];
}
$lang = $_SESSION['lang'] ?? 'ar';
$is_ar = ($lang === 'ar');
$dir = $is_ar ? 'rtl' : 'ltr';

// نصوص الترجمة المحدثة
$texts = [
    'ar' => [
        'title' => 'إدارة الموظفين - أسامة إلكتريك',
        'header' => 'إدارة المستخدمين والصلاحيات المخصصة',
        'sub_header' => 'حدد بدقة ما يمكن لكل موظف فعله في النظام',
        'home' => 'الرئيسية',
        'add_user' => 'إضافة موظف جديد',
        'name' => 'الاسم الكامل',
        'username' => 'اسم المستخدم',
        'password' => 'كلمة المرور',
        'role' => 'القالب الافتراضي',
        'status' => 'الحالة',
        'actions' => 'العمليات',
        'active' => 'نشط',
        'inactive' => 'معطل',
        'admin' => 'مدير نظام',
        'primary_admin' => 'مدير أساسي 👑',
        'collector' => 'محصل مالي',
        'data_entry' => 'مدخل بيانات',
        'custom' => 'مخصص',
        'save' => 'حفظ البيانات والصلاحيات',
        'cancel' => 'إلغاء',
        'edit' => 'تعديل',
        'delete' => 'حذف',
        'success' => 'تم حفظ بيانات الموظف وصلاحياته بنجاح',
        'confirm_delete' => 'هل أنت متأكد من حذف هذا المستخدم؟',
        'perms_title' => 'تخصيص المهام المسموحة',
        'p_customers' => 'إدارة المشتركين',
        'p_meters' => 'إدارة العدادات',
        'p_pricing' => 'تعديل الأسعار',
        'p_exchange' => 'تعديل سعر الصرف',
        'p_readings' => 'إدخال القراءات',
        'p_bills_gen' => 'إصدار فواتير',
        'p_bills_pay' => 'تحصيل مالي',
        'p_reports' => 'عرض التقارير',
        'p_system' => 'إعدادات النظام (نسخ، سجلات)',
        'is_primary_label' => 'تعيين كمدير أساسي (صلاحية مطلقة)'
    ],
    'en' => [
        'title' => 'User Management - Osama Electric',
        'header' => 'Users & Custom Permissions',
        'sub_header' => 'Define exactly what each employee can do',
        'home' => 'Home',
        'add_user' => 'Add New User',
        'name' => 'Full Name',
        'username' => 'Username',
        'password' => 'Password',
        'role' => 'Role Template',
        'status' => 'Status',
        'actions' => 'Actions',
        'active' => 'Active',
        'inactive' => 'Inactive',
        'admin' => 'Administrator',
        'primary_admin' => 'Primary Admin 👑',
        'collector' => 'Collector',
        'data_entry' => 'Data Entry',
        'custom' => 'Custom',
        'save' => 'Save Data & Perms',
        'cancel' => 'Cancel',
        'edit' => 'Edit',
        'delete' => 'Delete',
        'success' => 'User and permissions saved successfully',
        'confirm_delete' => 'Are you sure you want to delete this user?',
        'perms_title' => 'Customize Allowed Tasks',
        'p_customers' => 'Manage Customers',
        'p_meters' => 'Manage Meters',
        'p_pricing' => 'Edit Pricing',
        'p_exchange' => 'Edit Exchange Rate',
        'p_readings' => 'Enter Readings',
        'p_bills_gen' => 'Generate Bills',
        'p_bills_pay' => 'Collect Payments',
        'p_reports' => 'View Reports',
        'p_system' => 'System (Backup, Logs)',
        'is_primary_label' => 'Set as Primary Admin (Full Access)'
    ]
];

// 2. تضمين ملف الاتصال PDO
require_once 'db.php';

// ميزة الإصلاح التلقائي لإضافة الأعمدة المطلوبة
try {
    $pdo->exec("ALTER TABLE `users` ADD COLUMN IF NOT EXISTS `permissions` TEXT NULL AFTER `role` ");
    $pdo->exec("ALTER TABLE `users` ADD COLUMN IF NOT EXISTS `is_primary` TINYINT(1) DEFAULT 0 AFTER `permissions` ");
} catch (PDOException $e) {}

$message = '';

// 3. معالجة الإضافة والتعديل
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    $name = $_POST['name'] ?? '';
    $username = $_POST['username'] ?? '';
    // حل مشكلة Undefined key "role" و "status"
    $role = $_POST['role'] ?? 'custom';
    $status = $_POST['status'] ?? 0;
    $user_id = $_POST['user_id'] ?? null;
    $is_primary = isset($_POST['is_primary']) ? 1 : 0;
    
    $perms_array = $_POST['perms'] ?? [];
    $permissions_json = json_encode($perms_array);

    try {
        if ($action == 'add') {
            $pass_input = $_POST['password'] ?? '123456';
            $password = password_hash($pass_input, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (name, username, password, role, status, permissions, is_primary) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $username, $password, $role, $status, $permissions_json, $is_primary]);
            $message = $texts[$lang]['success'];
        } elseif ($action == 'edit' && $user_id) {
            if (!empty($_POST['password'])) {
                $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE users SET name=?, username=?, password=?, role=?, status=?, permissions=?, is_primary=? WHERE id=?");
                $stmt->execute([$name, $username, $password, $role, $status, $permissions_json, $is_primary, $user_id]);
            } else {
                $stmt = $pdo->prepare("UPDATE users SET name=?, username=?, role=?, status=?, permissions=?, is_primary=? WHERE id=?");
                $stmt->execute([$name, $username, $role, $status, $permissions_json, $is_primary, $user_id]);
            }
            $message = $texts[$lang]['success'];
        }
        
        $pdo->prepare("INSERT INTO audit_log (user_id, action) VALUES (?, ?)")
            ->execute([$_SESSION['user_id'] ?? null, "Security: Managed user $username"]);

    } catch (PDOException $e) {
        $message = "Error: " . $e->getMessage();
    }
}

// 4. الحذف (مع حماية المدير الأساسي)
if (isset($_GET['delete'])) {
    $stmt_check = $pdo->prepare("SELECT is_primary FROM users WHERE id = ?");
    $stmt_check->execute([$_GET['delete']]);
    $u_check = $stmt_check->fetch();
    
    if ($u_check && $u_check['is_primary'] == 0) {
        $pdo->prepare("DELETE FROM users WHERE id = ?")->execute([$_GET['delete']]);
    }
    header("Location: users.php"); exit();
}

// 5. جلب المستخدمين
$users = $pdo->query("SELECT * FROM users ORDER BY is_primary DESC, id DESC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $texts[$lang]['title'] ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>body { font-family: 'Cairo', sans-serif; background-color: #f1f5f9; }</style>
</head>
<body class="pb-20 text-slate-800">

    <div class="container mx-auto px-4 py-8 max-w-6xl">
        <!-- Header -->
        <div class="bg-white p-8 rounded-[2.5rem] shadow-sm mb-8 flex flex-col md:flex-row justify-between items-center gap-6 border border-slate-100">
            <div class="flex items-center gap-5">
                <div class="w-16 h-16 bg-blue-600 text-white rounded-2xl flex items-center justify-center text-3xl shadow-xl shadow-blue-100">
                    <i class="fas fa-user-shield"></i>
                </div>
                <div>
                    <h1 class="text-2xl font-black text-slate-800 italic"><?= $texts[$lang]['header'] ?></h1>
                    <p class="text-sm text-slate-400 font-bold uppercase tracking-wider"><?= $texts[$lang]['sub_header'] ?></p>
                </div>
            </div>
            <div class="flex gap-3">
                <button onclick="openModal('add')" class="bg-blue-600 hover:bg-black text-white px-8 py-3 rounded-2xl font-black transition flex items-center gap-2 shadow-lg shadow-blue-100 italic">
                    <i class="fas fa-plus-circle"></i> <?= $texts[$lang]['add_user'] ?>
                </button>
                <a href="dashboard.php" class="bg-slate-100 text-slate-600 px-8 py-3 rounded-2xl font-bold hover:bg-slate-200 transition italic">
                    <?= $texts[$lang]['home'] ?>
                </a>
            </div>
        </div>

        <?php if($message): ?>
            <div class="bg-emerald-500 text-white p-4 rounded-2xl mb-6 font-black shadow-lg animate-bounce flex items-center gap-3 italic text-sm">
                <i class="fas fa-check-circle"></i> <?= $message ?>
            </div>
        <?php endif; ?>

        <!-- Table -->
        <div class="bg-white rounded-[2.5rem] shadow-sm border border-slate-100 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full text-<?= $is_ar ? 'right' : 'left' ?>">
                    <thead class="bg-slate-50 text-slate-400 text-[10px] font-black uppercase tracking-widest border-b">
                        <tr>
                            <th class="p-6"><?= $texts[$lang]['name'] ?></th>
                            <th class="p-6"><?= $texts[$lang]['username'] ?></th>
                            <th class="p-6 text-center"><?= $texts[$lang]['role'] ?></th>
                            <th class="p-6 text-center"><?= $texts[$lang]['status'] ?></th>
                            <th class="p-6 text-center"><?= $texts[$lang]['actions'] ?></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-50">
                        <?php foreach($users as $u): ?>
                        <tr class="hover:bg-blue-50/10 transition group italic font-bold">
                            <td class="p-6">
                                <div class="flex items-center gap-3">
                                    <span class="text-slate-800 font-black"><?= htmlspecialchars($u['name']) ?></span>
                                    <?php if($u['is_primary']): ?>
                                        <span class="bg-amber-100 text-amber-600 px-2 py-0.5 rounded-lg text-[8px] font-black uppercase shadow-sm">
                                            <i class="fas fa-crown"></i> <?= $is_ar ? 'أساسي' : 'Primary' ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="p-6 text-slate-400 text-sm">@<?= htmlspecialchars($u['username']) ?></td>
                            <td class="p-6 text-center">
                                <span class="px-4 py-1.5 rounded-full text-[10px] font-black uppercase <?= ($u['is_primary'] ?? 0) ? 'bg-amber-600 text-white' : (($u['role'] ?? '') == 'admin' ? 'bg-indigo-100 text-indigo-700' : 'bg-slate-100 text-slate-600') ?>">
                                    <?= ($u['is_primary'] ?? 0) ? $texts[$lang]['primary_admin'] : ($texts[$lang][$u['role'] ?? ''] ?? ($u['role'] ?? '')) ?>
                                </span>
                            </td>
                            <td class="p-6 text-center">
                                <?php if($u['is_primary'] ?? 0): ?>
                                    <span class="text-emerald-500 text-[10px] font-black uppercase italic"><i class="fas fa-shield-alt"></i> محمـي</span>
                                <?php else: ?>
                                    <span class="w-3 h-3 rounded-full inline-block <?= ($u['status'] ?? 0) == 1 ? 'bg-emerald-500 shadow-lg shadow-emerald-200' : 'bg-rose-500' ?>"></span>
                                    <span class="text-xs ms-2"><?= ($u['status'] ?? 0) == 1 ? $texts[$lang]['active'] : $texts[$lang]['inactive'] ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="p-6 text-center">
                                <div class="flex justify-center gap-2">
                                    <button onclick='openModal("edit", <?= json_encode($u) ?>)' class="w-9 h-9 flex items-center justify-center bg-blue-50 text-blue-500 rounded-xl hover:bg-blue-600 hover:text-white transition shadow-sm"><i class="fas fa-edit"></i></button>
                                    
                                    <?php if(!($u['is_primary'] ?? 0)): ?>
                                    <a href="?delete=<?= $u['id'] ?>" onclick="return confirm('<?= $texts[$lang]['confirm_delete'] ?>')" class="w-9 h-9 flex items-center justify-center bg-rose-50 text-rose-500 rounded-xl hover:bg-rose-600 hover:text-white transition shadow-sm"><i class="fas fa-trash-alt"></i></a>
                                    <?php else: ?>
                                    <span class="w-9 h-9 flex items-center justify-center bg-slate-50 text-slate-200 rounded-xl cursor-not-allowed" title="Protected"><i class="fas fa-lock"></i></span>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- User Modal -->
    <div id="userModal" class="fixed inset-0 bg-slate-900/60 hidden items-center justify-center z-50 p-4 backdrop-blur-sm overflow-y-auto">
        <div class="bg-white rounded-[3rem] w-full max-w-2xl overflow-hidden shadow-2xl animate-in zoom-in duration-300 my-10 border-t-8 border-blue-600">
            <div class="p-8 bg-white border-b border-slate-100 flex justify-between items-center">
                <h3 id="modalTitle" class="text-xl font-black italic"></h3>
                <button onclick="closeModal()" class="text-2xl hover:rotate-90 transition-transform">&times;</button>
            </div>
            <form method="POST" class="p-8 space-y-6">
                <input type="hidden" name="action" id="formAction">
                <input type="hidden" name="user_id" id="userId">
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 italic">
                    <div>
                        <label class="block text-xs font-black text-slate-400 mb-2 uppercase tracking-widest"><?= $texts[$lang]['name'] ?> *</label>
                        <input type="text" name="name" id="userName" required class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold outline-none focus:ring-2 focus:ring-blue-600 shadow-inner text-sm">
                    </div>
                    <div>
                        <label class="block text-xs font-black text-slate-400 mb-2 uppercase tracking-widest"><?= $texts[$lang]['username'] ?> *</label>
                        <input type="text" name="username" id="userUsername" required class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold outline-none focus:ring-2 focus:ring-blue-600 shadow-inner text-sm text-center">
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 italic">
                    <div>
                        <label class="block text-xs font-black text-slate-400 mb-2 uppercase tracking-widest"><?= $texts[$lang]['password'] ?> <span id="pwdHint" class="text-[9px] text-blue-500"></span></label>
                        <input type="password" name="password" id="userPassword" class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold outline-none focus:ring-2 focus:ring-blue-600 shadow-inner text-sm text-center">
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-black text-slate-400 mb-2 uppercase tracking-widest"><?= $texts[$lang]['role'] ?></label>
                            <select name="role" id="userRole" onchange="applyRolePreset()" class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold outline-none cursor-pointer shadow-inner text-xs">
                                <option value="admin"><?= $texts[$lang]['admin'] ?></option>
                                <option value="collector"><?= $texts[$lang]['collector'] ?></option>
                                <option value="data_entry"><?= $texts[$lang]['data_entry'] ?></option>
                                <option value="custom"><?= $texts[$lang]['custom'] ?></option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-black text-slate-400 mb-2 uppercase tracking-widest"><?= $texts[$lang]['status'] ?></label>
                            <select name="status" id="userStatus" class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold outline-none cursor-pointer shadow-inner text-xs">
                                <option value="1"><?= $texts[$lang]['active'] ?></option>
                                <option value="0"><?= $texts[$lang]['inactive'] ?></option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="flex items-center justify-between p-6 bg-amber-50 rounded-2xl border-2 border-dashed border-amber-200">
                    <div class="flex items-center gap-3">
                        <i class="fas fa-crown text-amber-500 text-xl"></i>
                        <div>
                            <h4 class="font-black text-amber-800 text-xs italic"><?= $texts[$lang]['is_primary_label'] ?></h4>
                            <p class="text-[9px] text-amber-600 font-bold uppercase">المدير الأساسي لا يمكن حذفه أو تعطيله من النظام</p>
                        </div>
                    </div>
                    <input type="checkbox" name="is_primary" id="isPrimary" class="w-6 h-6 rounded border-amber-300 text-amber-600 focus:ring-amber-500">
                </div>

                <!-- Permissions Section -->
                <div class="bg-blue-50/50 p-6 rounded-[2.5rem] border border-blue-100 shadow-inner">
                    <h4 class="text-xs font-black text-blue-600 uppercase tracking-widest mb-6 flex items-center gap-2 italic">
                        <i class="fas fa-key"></i> <?= $texts[$lang]['perms_title'] ?>
                    </h4>
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 italic">
                        <?php 
                        $perms = ['customers', 'meters', 'pricing', 'exchange', 'readings', 'bills_gen', 'bills_pay', 'reports', 'system'];
                        foreach($perms as $p): ?>
                        <label class="flex items-center gap-3 p-3 bg-white rounded-xl border border-slate-100 hover:border-blue-300 transition cursor-pointer group shadow-sm">
                            <input type="checkbox" name="perms[]" value="<?= $p ?>" class="w-5 h-5 rounded border-slate-300 text-blue-600 focus:ring-blue-500 perm-checkbox">
                            <span class="text-[10px] font-black text-slate-500 group-hover:text-blue-600 uppercase tracking-tighter"><?= $texts[$lang]['p_'.$p] ?></span>
                        </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- [تم التعديل]: إضافة زر الإلغاء بجانب زر الحفظ -->
                <div class="flex gap-4">
                    <button type="submit" class="flex-grow p-6 bg-blue-600 text-white rounded-[2.5rem] font-black shadow-xl shadow-blue-100 hover:bg-black transition transform active:scale-95 flex items-center justify-center gap-4 italic uppercase">
                        <i class="fas fa-save"></i> <?= $texts[$lang]['save'] ?>
                    </button>
                    <button type="button" onclick="closeModal()" class="px-10 p-6 bg-slate-100 text-slate-500 rounded-[2.5rem] font-black hover:bg-slate-200 transition italic uppercase flex items-center justify-center gap-2">
                        <i class="fas fa-times"></i> <?= $texts[$lang]['cancel'] ?>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const presets = {
            'admin': ['customers', 'meters', 'pricing', 'exchange', 'readings', 'bills_gen', 'bills_pay', 'reports', 'system'],
            'collector': ['bills_pay', 'reports'],
            'data_entry': ['customers', 'meters', 'readings', 'bills_gen']
        };

        function applyRolePreset() {
            const role = document.getElementById('userRole').value;
            const checkboxes = document.querySelectorAll('.perm-checkbox');
            if (role === 'custom') return;
            checkboxes.forEach(cb => {
                cb.checked = presets[role].includes(cb.value);
            });
        }

        function openModal(mode, data = null) {
            const modal = document.getElementById('userModal');
            document.getElementById('formAction').value = mode;
            document.getElementById('pwdHint').innerText = mode === 'edit' ? '(اتركه فارغاً لعدم التغيير)' : '';
            
            document.querySelectorAll('.perm-checkbox').forEach(cb => cb.checked = false);

            if (mode === 'add') {
                document.getElementById('modalTitle').innerText = "<?= $texts[$lang]['add_user'] ?>";
                document.getElementById('userId').value = "";
                document.getElementById('userName').value = "";
                document.getElementById('userUsername').value = "";
                document.getElementById('userRole').value = "admin";
                document.getElementById('userStatus').value = "1";
                document.getElementById('isPrimary').checked = false;
                document.getElementById('userPassword').required = true;
                applyRolePreset();
            } else {
                document.getElementById('modalTitle').innerText = "<?= $texts[$lang]['edit'] ?>";
                document.getElementById('userId').value = data.id;
                document.getElementById('userName').value = data.name;
                document.getElementById('userUsername').value = data.username;
                document.getElementById('userRole').value = data.role;
                document.getElementById('userStatus').value = data.status;
                document.getElementById('isPrimary').checked = (data.is_primary == 1);
                document.getElementById('userPassword').required = false;

                if (data.permissions) {
                    try {
                        const perms = JSON.parse(data.permissions);
                        document.querySelectorAll('.perm-checkbox').forEach(cb => {
                            cb.checked = perms.includes(cb.value);
                        });
                    } catch(e) {}
                }
            }
            modal.classList.replace('hidden', 'flex');
        }

        function closeModal() {
            document.getElementById('userModal').classList.replace('flex', 'hidden');
        }
    </script>
</body>
</html>