<?php
session_start();
require_once('../config/db.php');

// جلب لغة المستخدم أو الافتراضية
$current_lang = $_SESSION['lang'] ?? 'ar';
$lang = include("../languages/{$current_lang}.php");

// ✅ التحقق من تسجيل الدخول وصلاحية المدير
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    echo '
    <!DOCTYPE html>
    <html lang="' . $current_lang . '" dir="' . ($current_lang == 'ar' ? 'rtl' : 'ltr') . '">
    <head>
        <meta charset="UTF-8">
        <title>' . ($lang['unauthorized_title'] ?? 'غير مصرح') . '</title>
        <script src="https://cdn.tailwindcss.com"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
        <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700&display=swap" rel="stylesheet">
        <style>body { font-family: "Cairo", sans-serif; }</style>
    </head>
    <body class="flex items-center justify-center min-h-screen bg-gray-50">
        <div class="bg-white p-10 rounded-2xl shadow-xl max-w-lg text-center border-t-4 border-red-500">
            <i class="fas fa-user-lock text-red-500 text-5xl mx-auto mb-4"></i>
            <h2 class="text-3xl font-extrabold text-gray-800 mb-3">' . ($lang['unauthorized_access'] ?? 'غير مصرح لك بالوصول') . '</h2>
            <p class="text-gray-600 mb-8">' . ($lang['admin_only_page'] ?? 'عذراً، هذه الصفحة مخصصة للمديرين فقط.') . '</p>
            <a href="../dashboard.php" class="inline-block bg-indigo-600 text-white px-6 py-3 rounded-full hover:bg-indigo-700 transition shadow-lg font-semibold">
                ' . $lang['back_to_dashboard'] . '
            </a>
        </div>
    </body>
    </html>';
    exit;
}

// ✅ جلب بيانات المستخدمين
$stmt = $conn->query("SELECT id, username, full_name, role, protected, created_at FROM users ORDER BY created_at DESC");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

<?php include('../includes/header.php'); ?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">

<style>
    /* أنماط الـ Modal والحركة */
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(-20px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .animate-fadeIn { animation: fadeIn 0.3s ease-out; }
    
    /* نمط الجدول الحديث */
    .table-header {
        background-color: #4f46e5;
        color: white;
    }
    .table-body tr {
        transition: background-color 0.2s ease;
    }
    .table-body tr:hover {
        background-color: #eef2ff;
    }
    .action-group {
        display: flex;
        flex-wrap: nowrap;
        justify-content: center;
        gap: 0.5rem;
    }
</style>

<?php include('../includes/navbar.php'); ?>

<div class="min-h-screen bg-gray-100 dark:bg-gray-900 pb-16 font-[Cairo]">
  <div class="max-w-7xl mx-auto py-10 px-4 sm:px-6 lg:px-8">

    <div class="bg-white dark:bg-gray-800 shadow-xl rounded-xl p-6 mb-8 border-b-4 border-indigo-500/10">
      <div class="flex flex-col md:flex-row md:justify-between md:items-center">
        
        <h2 class="text-3xl font-extrabold text-gray-800 dark:text-gray-100 mb-4 md:mb-0 border-b-4 border-indigo-400/50 pb-2 inline-block">
          <i class="fas fa-users-cog text-indigo-500 <?= $current_lang == 'ar' ? 'ml-2' : 'mr-2' ?>"></i> <?= $lang['users_management'] ?>
        </h2>
        
        <div class="flex flex-wrap gap-3">
          <a href="add.php" class="bg-indigo-600 text-white px-5 py-2 rounded-xl hover:bg-indigo-700 transition flex items-center shadow-lg transform hover:scale-[1.02]">
            <i class="fas fa-user-plus <?= $current_lang == 'ar' ? 'ml-2' : 'mr-2' ?>"></i> <?= $lang['add_new_user'] ?>
          </a>
          <a href="add_teacher.php" class="bg-emerald-600 text-white px-5 py-2 rounded-xl hover:bg-emerald-700 transition flex items-center shadow-lg transform hover:scale-[1.02]">
            <i class="fas fa-chalkboard-teacher <?= $current_lang == 'ar' ? 'ml-2' : 'mr-2' ?>"></i> <?= $lang['add_new_teacher'] ?>
          </a>
        </div>
      </div>
    </div>

    <div class="bg-white dark:bg-gray-800 shadow-xl rounded-xl p-6 mb-8">
      <input type="search" id="searchInput"
          placeholder="<?= $lang['search_users_placeholder'] ?>"
          onkeyup="searchTable()"
          class="border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-xl px-5 py-3 w-full focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner">
    </div>

    <div class="overflow-x-auto rounded-xl shadow-2xl">
      <table id="usersTable" class="min-w-full <?= $current_lang == 'ar' ? 'text-right' : 'text-left' ?> bg-white dark:bg-gray-800 border-collapse">
        <thead class="table-header">
          <tr>
            <th class="p-4 border-b border-indigo-400"><?= $lang['full_name'] ?></th>
            <th class="p-4 border-b border-indigo-400"><?= $lang['username'] ?></th>
            <th class="p-4 border-b border-indigo-400"><?= $lang['role'] ?></th>
            <th class="p-4 border-b border-indigo-400 text-center w-[200px] min-w-[200px]"><?= $lang['actions'] ?></th>
          </tr>
        </thead>
        <tbody class="table-body text-gray-700 dark:text-gray-300">
          <?php if ($users): ?>
            <?php foreach ($users as $user): ?>
              <tr class="border-b dark:border-gray-700">
                <td class="p-4 font-semibold"><?= htmlspecialchars($user['full_name']) ?></td>
                <td class="p-4 font-mono text-sm"><?= htmlspecialchars($user['username']) ?></td>
                <td class="p-4">
                  <span class="inline-block px-3 py-1 text-xs font-medium rounded-full
                    <?= ($user['role'] == 'admin') ? 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300' : 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300' ?>">
                    <?= htmlspecialchars($user['role']) ?>
                  </span>
                  <?php if ($user['protected']): ?>
                    <i class="fas fa-lock text-red-500 text-xs <?= $current_lang == 'ar' ? 'ml-1' : 'mr-1' ?>" title="<?= $lang['protected_account'] ?>"></i>
                  <?php endif; ?>
                </td>
                <td class="p-4 text-center">
                  <div class="action-group">
                    <a href="edit_user.php?id=<?= $user['id'] ?>"
                       class="action-button bg-blue-600 hover:bg-blue-700 p-2 rounded-full text-white shadow-md transform hover:scale-110 transition duration-150" title="<?= $lang['edit'] ?>">
                      <i class="fas fa-edit w-4 h-4"></i>
                    </a>
                    
                    <a href="reset_password.php?id=<?= $user['id'] ?>"
                       onclick="return confirm('<?= str_replace('{user}', htmlspecialchars($user['username']), $lang['confirm_reset_password']) ?>');"
                       class="action-button bg-yellow-500 hover:bg-yellow-600 p-2 rounded-full text-white shadow-md transform hover:scale-110 transition duration-150" title="<?= $lang['reset_password_title'] ?>">
                      <i class="fas fa-key w-4 h-4"></i>
                    </a>

                    <?php if ($user['protected']): ?>
                        <button disabled class="action-button bg-gray-400 p-2 rounded-full text-white shadow-md cursor-not-allowed" title="<?= $lang['cannot_delete_protected'] ?>">
                            <i class="fas fa-trash-alt w-4 h-4"></i>
                        </button>
                    <?php else: ?>
                      <button onclick="confirmDelete(<?= $user['id'] ?>, '<?= htmlspecialchars($user['username']) ?>')"
                        class="action-button bg-red-600 hover:bg-red-700 p-2 rounded-full text-white shadow-md transform hover:scale-110 transition duration-150" title="<?= $lang['delete'] ?>">
                        <i class="fas fa-trash-alt w-4 h-4"></i>
                      </button>
                    <?php endif; ?>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php else: ?>
            <tr>
              <td colspan="4" class="text-center p-8 text-xl text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-700">
                <i class="fas fa-exclamation-circle text-4xl mb-3 text-red-500"></i><br>
                <?= $lang['no_users_found'] ?>
              </td>
            </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div id="credentialsModal" class="hidden fixed inset-0 bg-black bg-opacity-70 flex justify-center items-center z-50 p-4">
  <div class="bg-white dark:bg-gray-800 rounded-3xl shadow-2xl w-full max-w-lg p-8 relative animate-fadeIn border-t-8 border-purple-600">
    <button onclick="closeCredentialsModal()" class="absolute top-4 right-4 text-gray-400 hover:text-red-500 text-3xl transition">&times;</button>
    <h3 class="text-3xl font-extrabold text-center mb-8 text-purple-700 dark:text-purple-400">🔑 <?= $lang['login_details'] ?></h3>
    
    <div class="text-center text-gray-700 dark:text-gray-300 text-xl space-y-4 bg-gray-50 dark:bg-gray-700 p-6 rounded-xl border border-dashed border-purple-300 dark:border-purple-700">
      <p class="flex justify-between items-center">
        <span><i class="fas fa-user-circle <?= $current_lang == 'ar' ? 'ml-2' : 'mr-2' ?> text-purple-500"></i> <?= $lang['username'] ?>:</span>
        <strong id="credUsername" class="text-2xl font-mono text-gray-900 dark:text-white"></strong>
      </p>
      <p class="flex justify-between items-center">
        <span><i class="fas fa-lock <?= $current_lang == 'ar' ? 'ml-2' : 'mr-2' ?> text-purple-500"></i> <?= $lang['default_password'] ?>:</span>
        <strong id="credPassword" class="text-2xl font-mono text-gray-900 dark:text-white">123</strong>
      </p>
      <p class="text-sm text-red-500 mt-4"><i class="fas fa-exclamation-triangle"></i> <?= $lang['reset_password_note'] ?? 'كلمة المرور الافتراضية بعد إعادة التعيين هي: 123' ?></p>
    </div>
    
    <div class="text-center mt-10">
      <button onclick="closeCredentialsModal()" class="bg-gray-400 hover:bg-gray-500 text-white px-8 py-3 rounded-xl font-bold transition shadow-lg">
        <i class="fas fa-times <?= $current_lang == 'ar' ? 'ml-2' : 'mr-2' ?>"></i> <?= $lang['close'] ?>
      </button>
    </div>
  </div>
</div>

<div id="toast" class="hidden fixed bottom-6 right-6 bg-green-600 text-white px-6 py-3 rounded-xl shadow-2xl text-lg font-bold transition duration-300 transform opacity-0 translate-y-full">
  <i class="fas fa-check-circle <?= $current_lang == 'ar' ? 'ml-2' : 'mr-2' ?>"></i> <?= $lang['delete_success_msg'] ?>
</div>

<script>
  function searchTable() {
    const input = document.getElementById('searchInput').value.toLowerCase();
    document.querySelectorAll('#usersTable tbody tr').forEach(row => {
      const rowContent = row.textContent.toLowerCase();
      row.style.display = rowContent.includes(input) ? '' : 'none';
    });
  }

  function showCredentials(username) {
    document.getElementById('credUsername').textContent = username;
    document.getElementById('credentialsModal').classList.remove('hidden');
  }

  function closeCredentialsModal() {
    document.getElementById('credentialsModal').classList.add('hidden');
  }

  function confirmDelete(id, username) {
    if (confirm(`<?= $lang['confirm_delete_user'] ?> (${username})?`)) {
      fetch(`delete_user.php?id=${id}`)
        .then(response => {
          if (!response.ok) throw new Error('فشل الحذف');
          return response.text();
        })
        .then(() => {
          const toast = document.getElementById('toast');
          toast.classList.remove('hidden', 'opacity-0', 'translate-y-full');
          toast.classList.add('opacity-100', 'translate-y-0');

          setTimeout(() => {
            toast.classList.remove('opacity-100', 'translate-y-0');
            toast.classList.add('opacity-0', 'translate-y-full');
            setTimeout(() => {
              toast.classList.add('hidden');
              location.reload();
            }, 500);
          }, 1500);
        })
        .catch(error => {
          console.error('Error:', error);
          alert('<?= $lang['operation_error'] ?>');
        });
    }
  }
</script>

<?php include('../includes/footer.php'); ?>