<?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['BranchName']);
    $address = trim($_POST['BranchAddress']);
    $phone   = trim($_POST['Phone']);
    $manager = trim($_POST['ManagerName']);
    $isActive= isset($_POST['IsActive']) ? 1 : 0;
    $notes   = trim($_POST['Notes']);

    if ($name === "") {
        $error = "❌ برجاء إدخال اسم الفرع";
    } else {
        try {
            if ($id) {
                // تحديث
                $stmt = $pdo->prepare("UPDATE Branches SET BranchName=?, BranchAddress=?, Phone=?, ManagerName=?, IsActive=?, Notes=? WHERE BranchID=?");
                $stmt->execute([$name, $address, $phone, $manager, $isActive, $notes, $id]);
                $success = "✅ تم تعديل بيانات الفرع بنجاح";
            } else {
                // إضافة
                $stmt = $pdo->prepare("INSERT INTO Branches (BranchName, BranchAddress, Phone, ManagerName, IsActive, Notes) VALUES (?,?,?,?,?,?)");
                $stmt->execute([$name, $address, $phone, $manager, $isActive, $notes]);
                $success = "✅ تم إضافة الفرع بنجاح";
            }
        } catch (PDOException $e) {
            $error = "⚠️ خطأ: " . $e->getMessage();
        }
    }
}

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

// جلب الفروع
$branches = $pdo->query("SELECT * FROM Branches ORDER BY BranchID ASC")->fetchAll();

// الكروت
$totalBranches   = $pdo->query("SELECT COUNT(*) FROM Branches")->fetchColumn();
$activeBranches  = $pdo->query("SELECT COUNT(*) FROM Branches WHERE IsActive=1")->fetchColumn();     
$inactiveBranches= $pdo->query("SELECT COUNT(*) FROM Branches WHERE IsActive=0")->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-4 mb-3">
      <div class="card text-white bg-primary shadow">
        <div class="card-body">
          <h5>🏬 إجمالي الفروع</h5>
          <h2><?= $totalBranches ?></h2>
        </div>
      </div>
    </div>
    <div class="col-md-4 mb-3">
      <div class="card text-white bg-success shadow">
        <div class="card-body">
          <h5>✅ الفروع النشطة</h5>
          <h2><?= $activeBranches ?></h2>
        </div>
      </div>
    </div>
    <div class="col-md-4 mb-3">
      <div class="card text-white bg-danger shadow">
        <div class="card-body">
          <h5>⛔ الفروع الموقوفة</h5>
          <h2><?= $inactiveBranches ?></h2>
        </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="branch_id">
        <div class="col-md-4"><input type="text" name="BranchName" id="branch_name" class="form-control" placeholder="اسم الفرع" required></div>
        <div class="col-md-4"><input type="text" name="BranchAddress" id="branch_address" class="form-control" placeholder="العنوان"></div>
        <div class="col-md-4"><input type="text" name="Phone" id="branch_phone" class="form-control" placeholder="الهاتف"></div>
        <div class="col-md-4"><input type="text" name="ManagerName" id="branch_manager" class="form-control" placeholder="مدير الفرع"></div>
        <div class="col-md-2 d-flex align-items-center">
          <input type="checkbox" name="IsActive" id="branch_active" class="form-check-input me-2" checked>
          <label for="branch_active" class="form-check-label">نشط</label>
        </div>
        <div class="col-md-6"><input type="text" name="Notes" id="branch_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>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($branches as $b): ?>
          <tr>
            <td><?= $b['BranchID'] ?></td>
            <td><?= htmlspecialchars($b['BranchName']) ?></td>
            <td><?= htmlspecialchars($b['BranchAddress']) ?></td>
            <td><?= htmlspecialchars($b['Phone']) ?></td>
            <td><?= htmlspecialchars($b['ManagerName']) ?></td>
            <td><?= $b['IsActive'] ? '<span class="badge bg-success">نشط</span>' : '<span class="badge bg-danger">موقوف</span>' ?></td>
            <td><?= htmlspecialchars($b['Notes']) ?></td>
            <td>
              <button class="btn btn-sm btn-warning" 
                onclick="editBranch(<?= $b['BranchID'] ?>,'<?= htmlspecialchars($b['BranchName']) ?>','<?= htmlspecialchars($b['BranchAddress']) ?>','<?= htmlspecialchars($b['Phone']) ?>','<?= htmlspecialchars($b['ManagerName']) ?>',<?= $b['IsActive'] ?>,'<?= htmlspecialchars($b['Notes']) ?>')">✏️ تعديل</button>
              <a href="?delete=<?= $b['BranchID'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('هل أنت متأكد من الحذف؟')">🗑️ حذف</a>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>

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

<script>
function editBranch(id,name,address,phone,manager,isActive,notes){
  document.getElementById("branch_id").value = id;
  document.getElementById("branch_name").value = name;
  document.getElementById("branch_address").value = address;
  document.getElementById("branch_phone").value = phone;
  document.getElementById("branch_manager").value = manager;
  document.getElementById("branch_active").checked = isActive ? true : false;
  document.getElementById("branch_notes").value = notes;
}
</script>
</body>
</html>
