<?php
require_once __DIR__ . '/../core/auth.php';
require_login();

$pdo = db();
$success = $error = "";

// إضافة أو تعديل موظف
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $id       = $_POST['id'] ?? null;
    $name     = trim($_POST['EmpName']);
    $phone    = trim($_POST['Phone']);
    $email    = trim($_POST['Email']);
    $role     = $_POST['Role'] ?? 'Other';
    $branch   = $_POST['BranchID'] ?: null;
    $isActive = isset($_POST['IsActive']) ? 1 : 0;
    $hireDate = $_POST['HireDate'] ?: null;
    $notes    = trim($_POST['Notes']);

    if ($name === "") {
        $error = "❌ برجاء إدخال اسم الموظف";
    } else {
        try {
            if ($id) {
                // تحديث
                $stmt = $pdo->prepare("UPDATE Employees SET EmpName=?, Phone=?, Email=?, Role=?, BranchID=?, IsActive=?, HireDate=?, Notes=? WHERE EmpID=?");
                $stmt->execute([$name, $phone, $email, $role, $branch, $isActive, $hireDate, $notes, $id]);
                $success = "✅ تم تعديل بيانات الموظف";
            } else {
                // إضافة
                $stmt = $pdo->prepare("INSERT INTO Employees (EmpName, Phone, Email, Role, BranchID, IsActive, HireDate, Notes) VALUES (?,?,?,?,?,?,?,?)");
                $stmt->execute([$name, $phone, $email, $role, $branch, $isActive, $hireDate, $notes]);
                $success = "✅ تم إضافة الموظف";
            }
        } catch (PDOException $e) {
            $error = "⚠️ خطأ: " . $e->getMessage();
        }
    }
}

// حذف موظف
if (isset($_GET['delete'])) {
    $id = (int) $_GET['delete'];
    $pdo->prepare("DELETE FROM Employees WHERE EmpID=?")->execute([$id]);
    $success = "🗑️ تم حذف الموظف";
}

// جلب الفروع
$branches = $pdo->query("SELECT BranchID, BranchName FROM Branches ORDER BY BranchName")->fetchAll(PDO::FETCH_KEY_PAIR);

// جلب الموظفين
$employees = $pdo->query("SELECT e.*, b.BranchName 
                          FROM Employees e 
                          LEFT JOIN Branches b ON e.BranchID=b.BranchID
                          ORDER BY e.EmpID DESC")->fetchAll();

// الكروت
$totalEmployees = $pdo->query("SELECT COUNT(*) FROM Employees")->fetchColumn();
$totalCashiers  = $pdo->query("SELECT COUNT(*) FROM Employees WHERE Role='Cashier'")->fetchColumn();
$totalCaptains  = $pdo->query("SELECT COUNT(*) FROM Employees WHERE Role='Captain'")->fetchColumn();
$totalDrivers   = $pdo->query("SELECT COUNT(*) FROM Employees WHERE Role='Driver'")->fetchColumn();
$lastEmployee   = $pdo->query("SELECT EmpName FROM Employees ORDER BY EmpID DESC LIMIT 1")->fetchColumn();

?>

<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <title>إدارة الموظفين</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { font-family:"Tajawal",sans-serif; background:#f8f9fa; }
    .card { border-radius:12px; box-shadow:0 4px 10px rgba(0,0,0,0.1); }
    .card-header { background:linear-gradient(135deg,#0f2027,#203a43,#2c5364); color:#fff; font-weight:bold; }
    .btn-custom { border-radius:25px; }
  </style>
</head>
<body>
<div class="container py-4">
<header class="mb-4">
  <div class="d-flex justify-content-between align-items-center p-3 bg-dark text-white shadow-sm">
    <!-- يمين: بيانات المستخدم -->
    <div class="d-flex align-items-center gap-2">
        <img src="uploads/<?= htmlspecialchars($_SESSION['avatar'] ?? 'default.png') ?>" 
            alt="Avatar" 
            class="rounded-circle border border-2 border-light"
            style="width:40px;height:40px;object-fit:cover;">
            
        <span class="fw-bold"><?= htmlspecialchars($_SESSION['admin_username'] ?? 'Admin') ?></span>
        
        <a href="logout.php" class="btn btn-sm btn-outline-light">خروج</a>
    </div>


    <!-- وسط: عنوان الصفحة -->
    <h1 class="h5 m-0">الموظفين</h1>

    <!-- شمال: زر الوضع الليلي -->
    <button id="darkSwitch" class="btn btn-sm btn-success">🌙</button>
  </div>
</header>
<div class="text-end mb-3">
  <a href="dashboard.php" class="btn btn-secondary">
    <i class="fa-solid fa-house"></i> الرئيسية
  </a>
</div>
 <!-- الكروت -->
 <div class="row text-center mb-4">
    <div class="col-md-2 mb-3">
      <div class="card text-white bg-primary shadow">
        <div class="card-body">
          <h6>👥 عدد الموظفين</h6>
          <h2><?= $totalEmployees ?></h2>
        </div>
      </div>
    </div>
    <div class="col-md-2 mb-3">
      <div class="card text-white bg-success shadow">
        <div class="card-body">
          <h6>💰 عدد الكاشير</h6>
          <h2><?= $totalCashiers ?></h2>
        </div>
      </div>
    </div>
    <div class="col-md-2 mb-3">
      <div class="card text-white bg-info shadow">
        <div class="card-body">
          <h6>🍽️ عدد الكباتن</h6>
          <h2><?= $totalCaptains ?></h2>
        </div>
      </div>
    </div>
    <div class="col-md-2 mb-3">
      <div class="card text-white bg-warning shadow">
        <div class="card-body">
          <h6>🛵 عدد الطيارين</h6>
          <h2><?= $totalDrivers ?></h2>
        </div>
      </div>
    </div>
    <div class="col-md-4 mb-3">
      <div class="card text-white bg-dark shadow">
        <div class="card-body">
          <h6>🆕 آخر موظف</h6>
          <h4><?= htmlspecialchars($lastEmployee ?: '—') ?></h4>
        </div>
      </div>
    </div>
  </div>
  
  <div class="card">
    <div class="card-header">👨‍💼 إدارة الموظفين</div>
    <div class="card-body">

      <?php if ($success): ?>
        <div class="alert alert-success text-center"><?= $success ?></div>
      <?php elseif ($error): ?>
        <div class="alert alert-danger text-center"><?= $error ?></div>
      <?php endif; ?>

      <!-- نموذج إضافة / تعديل -->
      <form method="post" class="row g-3 mb-4">
        <input type="hidden" name="id" id="emp_id">
        <div class="col-md-4"><input type="text" name="EmpName" id="emp_name" class="form-control" placeholder="اسم الموظف" required></div>
        <div class="col-md-4"><input type="text" name="Phone" id="emp_phone" class="form-control" placeholder="الهاتف"></div>
        <div class="col-md-4"><input type="email" name="Email" id="emp_email" class="form-control" placeholder="البريد الإلكتروني"></div>
        <div class="col-md-3">
          <select name="Role" id="emp_role" class="form-select">
            <option value="Captain">كابتن</option>
            <option value="Driver">طيار</option>
            <option value="Cashier">كاشير</option>
            <option value="Other">أخرى</option>
          </select>
        </div>
        <div class="col-md-3">
          <select name="BranchID" id="emp_branch" class="form-select">
            <option value="">اختر الفرع</option>
            <?php foreach ($branches as $id=>$name): ?>
              <option value="<?= $id ?>"><?= htmlspecialchars($name) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2 d-flex align-items-center">
          <input type="checkbox" name="IsActive" id="emp_active" class="form-check-input me-2" checked>
          <label for="emp_active" class="form-check-label">نشط</label>
        </div>
        <div class="col-md-4"><input type="date" name="HireDate" id="emp_hiredate" class="form-control"></div>
        <div class="col-md-12"><input type="text" name="Notes" id="emp_notes" class="form-control" placeholder="ملاحظات"></div>
        <div class="col-md-12 text-end"><button type="submit" class="btn btn-primary btn-custom px-4">💾 حفظ</button></div>
      </form>

      <!-- جدول عرض الموظفين -->
      <table class="table table-bordered text-center align-middle">
        <thead class="table-dark">
          <tr>
            <th>#</th>
            <th>الاسم</th>
            <th>الهاتف</th>
            <th>البريد</th>
            <th>الوظيفة</th>
            <th>الفرع</th>
            <th>الحالة</th>
            <th>تاريخ التعيين</th>
            <th>ملاحظات</th>
            <th>إجراءات</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($employees as $e): ?>
          <tr>
            <td><?= $e['EmpID'] ?></td>
            <td><?= htmlspecialchars($e['EmpName']) ?></td>
            <td><?= htmlspecialchars($e['Phone']) ?></td>
            <td><?= htmlspecialchars($e['Email']) ?></td>
            <td><?= htmlspecialchars($e['Role']) ?></td>
            <td><?= htmlspecialchars($e['BranchName'] ?? '—') ?></td>
            <td><?= $e['IsActive'] ? '<span class="badge bg-success">نشط</span>' : '<span class="badge bg-danger">موقوف</span>' ?></td>
            <td><?= $e['HireDate'] ?></td>
            <td><?= htmlspecialchars($e['Notes']) ?></td>
            <td>
              <button class="btn btn-sm btn-warning" 
                onclick="editEmployee(<?= $e['EmpID'] ?>,'<?= htmlspecialchars($e['EmpName']) ?>','<?= htmlspecialchars($e['Phone']) ?>','<?= htmlspecialchars($e['Email']) ?>','<?= $e['Role'] ?>','<?= $e['BranchID'] ?>',<?= $e['IsActive'] ?>,'<?= $e['HireDate'] ?>','<?= htmlspecialchars($e['Notes']) ?>')">✏️</button>
              <a href="?delete=<?= $e['EmpID'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('هل أنت متأكد من الحذف؟')">🗑️</a>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>

    </div>
  </div>
</div>

<script>
function editEmployee(id,name,phone,email,role,branch,isActive,hiredate,notes){
  document.getElementById("emp_id").value = id;
  document.getElementById("emp_name").value = name;
  document.getElementById("emp_phone").value = phone;
  document.getElementById("emp_email").value = email;
  document.getElementById("emp_role").value = role;
  document.getElementById("emp_branch").value = branch;
  document.getElementById("emp_active").checked = isActive ? true : false;
  document.getElementById("emp_hiredate").value = hiredate;
  document.getElementById("emp_notes").value = notes;
}
</script>
</body>
</html>
