<?php
session_start();
require_once('../config/db.php');

// --- نظام جلب اللغة ---
$current_lang = $_SESSION['lang'] ?? 'ar';
$lang_file = "../languages/" . $current_lang . ".php";
$translations = file_exists($lang_file) ? include($lang_file) : [];

// ✅ التحقق من تسجيل الدخول وصلاحية المدير
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
  header('Location: ../dashboard.php');
  exit;
}

$error = '';
$success = '';

// تهيئة المتغيرات
$username = $_POST['username'] ?? '';
$full_name = $_POST['full_name'] ?? '';
$role = $_POST['role'] ?? 'staff';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $username = trim($username);
  $full_name = trim($full_name);
  $password = $_POST['password'] ?? '';
  $role = $_POST['role'] ?? 'staff';

  if (empty($username) || empty($password) || empty($full_name)) {
    $error = $translations['error_all_fields'] ?? "🚫 يرجى ملء جميع الحقول المطلوبة.";
  } else {
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    try {
      $stmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
      $stmt->execute([$username]);
      
      if ($stmt->fetch()) {
        $error = ($translations['error_user_exists'] ?? "🚫 اسم المستخدم موجود مسبقاً: ") . htmlspecialchars($username);
      } else {
        $stmt = $conn->prepare("INSERT INTO users (username, full_name, password, role) VALUES (?, ?, ?, ?)");
        
        if ($stmt->execute([$username, $full_name, $hashed_password, $role])) {
          $success = ($translations['success_user_created'] ?? "✅ تم إنشاء المستخدم بنجاح: ") . htmlspecialchars($full_name);
          $username = $full_name = ''; // تفريغ الحقول
        } else {
          $error = $translations['error_db_insert'] ?? "❌ حدث خطأ أثناء إنشاء المستخدم.";
        }
      }
    } catch (PDOException $e) {
      $error = "❌ " . $e->getMessage();
    }
  }
}

include('../includes/header.php');
include('../includes/navbar.php');

// متغيرات التنسيق بناءً على اللغة
$dir = ($current_lang == 'ar') ? 'rtl' : 'ltr';
$ml = ($current_lang == 'ar') ? 'ml-2' : 'mr-2';
?>

<div class="min-h-screen bg-gray-100 dark:bg-gray-900 pb-16 font-[Cairo]" dir="<?= $dir ?>">
  <div class="max-w-xl mx-auto py-10 px-4 sm:px-6 lg:px-8">
    <div class="bg-white dark:bg-gray-800 shadow-2xl rounded-2xl p-8 border-t-8 border-indigo-600 dark:border-indigo-500 transform transition duration-300">
     
      <h2 class="text-3xl font-extrabold mb-8 text-center text-indigo-700 dark:text-indigo-400 border-b pb-4">
        <i class="fas fa-user-plus <?= $ml ?>"></i> <?= $translations['add_new_user'] ?? 'إضافة مستخدم جديد' ?>
      </h2>

      <?php if ($error): ?>
        <div class="bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300 p-4 rounded-xl mb-6 shadow-lg border border-red-300">
          <i class="fas fa-times-circle <?= $ml ?>"></i> <?= htmlspecialchars($error) ?>
        </div>
      <?php elseif ($success): ?>
        <div class="bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 p-4 rounded-xl mb-6 shadow-lg border border-green-300">
          <i class="fas fa-check-circle <?= $ml ?>"></i> <?= htmlspecialchars($success) ?>
        </div>
      <?php endif; ?>

      <form method="POST" class="space-y-6">
       
        <div>
          <label for="full_name" class="block mb-2 font-bold text-gray-700 dark:text-gray-300">
            <?= $translations['label_full_name'] ?? 'الاسم الكامل' ?> <span class="text-red-500">*</span>
          </label>
          <input type="text" name="full_name" id="full_name" required
            value="<?= htmlspecialchars($full_name) ?>"
            placeholder="<?= $translations['placeholder_full_name'] ?? 'أدخل الاسم الكامل' ?>"
            class="w-full border-2 border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-xl px-4 py-3 focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner">
        </div>

        <div>
          <label for="username" class="block mb-2 font-bold text-gray-700 dark:text-gray-300">
            <?= $translations['label_username'] ?? 'اسم المستخدم' ?> <span class="text-red-500">*</span>
          </label>
          <input type="text" name="username" id="username" required
            value="<?= htmlspecialchars($username) ?>"
            placeholder="<?= $translations['placeholder_username'] ?? 'أدخل اسم المستخدم' ?>"
            class="w-full border-2 border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-xl px-4 py-3 focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner">
        </div>

        <div>
          <label for="password" class="block mb-2 font-bold text-gray-700 dark:text-gray-300">
            <?= $translations['label_password'] ?? 'كلمة المرور' ?> <span class="text-red-500">*</span>
          </label>
          <input type="password" name="password" id="password" required
            placeholder="<?= $translations['placeholder_password'] ?? 'كلمة مرور قوية' ?>"
            class="w-full border-2 border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-xl px-4 py-3 focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner">
        </div>

        <div>
          <label for="role" class="block mb-2 font-bold text-gray-700 dark:text-gray-300">
            <?= $translations['label_role'] ?? 'الصلاحية' ?>
          </label>
          <select name="role" id="role" required
            class="w-full border-2 border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-xl px-4 py-3 focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner">
            <option value="staff" <?= $role === 'staff' ? 'selected' : '' ?>><?= $translations['role_staff'] ?? 'مستخدم (Staff)' ?></option>
            <option value="admin" <?= $role === 'admin' ? 'selected' : '' ?>><?= $translations['role_admin'] ?? 'مدير (Admin)' ?></option>
          </select>
        </div>

        <div class="flex flex-col sm:flex-row justify-between items-center pt-4 space-y-4 sm:space-y-0 gap-4">
          
          <button type="submit"
            class="bg-indigo-600 text-white w-full sm:w-auto px-8 py-3 rounded-xl hover:bg-indigo-700 transition font-extrabold shadow-lg transform hover:scale-[1.02]">
            <i class="fas fa-save <?= $ml ?>"></i> <?= $translations['btn_create_user'] ?? 'إنشاء المستخدم' ?>
          </button>
          
          <a href="list.php"
            class="w-full sm:w-auto px-6 text-center bg-gray-300 dark:bg-gray-600 text-gray-800 dark:text-gray-100 font-semibold py-3 rounded-xl hover:bg-gray-400 transition shadow-md flex items-center justify-center">
            <i class="fas <?= ($current_lang == 'ar') ? 'fa-arrow-right ml-2' : 'fa-arrow-left mr-2' ?>"></i> 
            <?= $translations['back_to_list'] ?? 'العودة للقائمة' ?>
          </a>
        </div>
      </form>
    </div>
  </div>
</div>

<?php include('../includes/footer.php'); ?>