<?php
require_once __DIR__ . '/../core/auth.php';
require_login();
$pdo = db();

$success = $error = "";

/* ─────────────── المحافظات ─────────────── */
// إضافة / تعديل محافظة
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['governate_name'])) {
    $id   = $_POST['id'] ?? null;
    $name = trim($_POST['governate_name']);
    $notes = trim($_POST['notes'] ?? '');

    if ($name === '') {
        $error = "❌ برجاء إدخال اسم المحافظة";
    } else {
        try {
            if ($id) {
                $stmt = $pdo->prepare("UPDATE Governates SET GovernateName=?, Notes=? WHERE GovernateID=?");
                $stmt->execute([$name, $notes, $id]);
                $success = "✅ تم تعديل المحافظة بنجاح";
            } else {
                $stmt = $pdo->prepare("INSERT INTO Governates (GovernateName, Notes) VALUES (?,?)");
                $stmt->execute([$name, $notes]);
                $success = "✅ تم إضافة المحافظة بنجاح";
            }
        } catch (PDOException $e) {
            $error = "⚠️ خطأ: " . $e->getMessage();
        }
    }
}

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

/* ─────────────── المناطق ─────────────── */
// إضافة / تعديل منطقة
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['zone_name'])) {
    $id   = $_POST['zone_id'] ?? null;
    $name = trim($_POST['zone_name']);
    $govid = $_POST['governate_id'];
    $fee  = $_POST['delivery_fee'] ?: 0;
    $time = $_POST['estimated_time'] ?: null;

    if ($name === '' || !$govid) {
        $error = "❌ برجاء إدخال اسم المنطقة واختيار المحافظة";
    } else {
        try {
            if ($id) {
                $stmt = $pdo->prepare("UPDATE Zones SET ZoneName=?, GovernateID=?, DeliveryFee=?, EstimatedTime=? WHERE ZoneID=?");
                $stmt->execute([$name, $govid, $fee, $time, $id]);
                $success = "✅ تم تعديل المنطقة بنجاح";
            } else {
                $stmt = $pdo->prepare("INSERT INTO Zones (ZoneName, GovernateID, DeliveryFee, EstimatedTime) VALUES (?,?,?,?)");
                $stmt->execute([$name, $govid, $fee, $time]);
                $success = "✅ تم إضافة المنطقة بنجاح";
            }
        } catch (PDOException $e) {
            $error = "⚠️ خطأ: " . $e->getMessage();
        }
    }
}

// حذف منطقة
if (isset($_GET['delete_zone'])) {
    $id = (int) $_GET['delete_zone'];
    $pdo->prepare("DELETE FROM Zones WHERE ZoneID=?")->execute([$id]);
    $success = "🗑️ تم حذف المنطقة";
}

/* ─────────────── عرض البيانات ─────────────── */
$governates = $pdo->query("SELECT * FROM Governates ORDER BY GovernateName")->fetchAll();
$zones = $pdo->query("SELECT z.*, g.GovernateName FROM Zones z JOIN Governates g ON z.GovernateID=g.GovernateID ORDER BY g.GovernateName, z.ZoneName")->fetchAll();

// إحصائيات
$totalGovernates = count($governates);
$totalZones = count($zones);
?>
<!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">
</head>
<body class="bg-light">

<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 mb-4 text-center">
  <div class="col-md-6">
    <div class="card shadow-sm border-0">
      <div class="card-body">
        <h5 class="card-title text-muted">عدد المحافظات</h5>
        <h2 class="fw-bold text-primary"><?= $totalGovernates ?></h2>
      </div>
    </div>
  </div>
  <div class="col-md-6">
    <div class="card shadow-sm border-0">
      <div class="card-body">
        <h5 class="card-title text-muted">عدد المناطق</h5>
        <h2 class="fw-bold text-success"><?= $totalZones ?></h2>
      </div>
    </div>
  </div>
</div>


<div class="container py-4">


  <h2 class="mb-4">🌍 إدارة المحافظات والمناطق</h2>

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

  <div class="row">
    <!-- المحافظات -->
    <div class="col-md-6">
      <div class="card mb-4">
        <div class="card-header bg-primary text-white">📌 المحافظات</div>
        <div class="card-body">
          <form method="post" class="row g-2 mb-3">
            <input type="hidden" name="id" id="gov_id">
            <div class="col-6"><input type="text" name="governate_name" id="gov_name" class="form-control" placeholder="اسم المحافظة"></div>
            <div class="col-4"><input type="text" name="notes" id="gov_notes" class="form-control" placeholder="ملاحظات"></div>
            <div class="col-2"><button class="btn btn-success w-100">💾</button></div>
          </form>

          <table class="table table-bordered text-center">
            <thead class="table-dark"><tr><th>#</th><th>الاسم</th><th>ملاحظات</th><th>إجراءات</th></tr></thead>
            <tbody>
            <?php foreach ($governates as $g): ?>
              <tr>
                <td><?= $g['GovernateID'] ?></td>
                <td><?= htmlspecialchars($g['GovernateName']) ?></td>
                <td><?= htmlspecialchars($g['Notes']) ?></td>
                <td>
                  <button class="btn btn-sm btn-warning" onclick="editGov(<?= $g['GovernateID'] ?>,'<?= htmlspecialchars($g['GovernateName']) ?>','<?= htmlspecialchars($g['Notes']) ?>')">✏️</button>
                  <a href="?delete_governate=<?= $g['GovernateID'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('هل أنت متأكد من الحذف؟')">🗑️</a>
                </td>
              </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- المناطق -->
    <div class="col-md-6">
      <div class="card mb-4">
        <div class="card-header bg-success text-white">📍 المناطق</div>
        <div class="card-body">
          <form method="post" class="row g-2 mb-3">
            <input type="hidden" name="zone_id" id="zone_id">
            <div class="col-4"><input type="text" name="zone_name" id="zone_name" class="form-control" placeholder="اسم المنطقة"></div>
            <div class="col-3">
              <select name="governate_id" id="zone_gov" class="form-select">
                <option value="">المحافظة</option>
                <?php foreach ($governates as $g): ?>
                  <option value="<?= $g['GovernateID'] ?>"><?= htmlspecialchars($g['GovernateName']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-2"><input type="number" step="0.01" name="delivery_fee" id="zone_fee" class="form-control" placeholder="التوصيل"></div>
            <div class="col-2"><input type="number" name="estimated_time" id="zone_time" class="form-control" placeholder="وقت"></div>
            <div class="col-1"><button class="btn btn-success w-100">💾</button></div>
          </form>

          <table class="table table-bordered text-center">
            <thead class="table-dark"><tr><th>#</th><th>المنطقة</th><th>المحافظة</th><th>التوصيل</th><th>وقت</th><th>إجراءات</th></tr></thead>
            <tbody>
            <?php foreach ($zones as $z): ?>
              <tr>
                <td><?= $z['ZoneID'] ?></td>
                <td><?= htmlspecialchars($z['ZoneName']) ?></td>
                <td><?= htmlspecialchars($z['GovernateName']) ?></td>
                <td><?= $z['DeliveryFee'] ?></td>
                <td><?= $z['EstimatedTime'] ?></td>
                <td>
                  <button class="btn btn-sm btn-warning" onclick="editZone(<?= $z['ZoneID'] ?>,'<?= htmlspecialchars($z['ZoneName']) ?>',<?= $z['GovernateID'] ?>,'<?= $z['DeliveryFee'] ?>','<?= $z['EstimatedTime'] ?>')">✏️</button>
                  <a href="?delete_zone=<?= $z['ZoneID'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('هل أنت متأكد من الحذف؟')">🗑️</a>
                </td>
              </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
function editGov(id,name,notes){
  document.getElementById('gov_id').value = id;
  document.getElementById('gov_name').value = name;
  document.getElementById('gov_notes').value = notes;
}
function editZone(id,name,gov,fee,time){
  document.getElementById('zone_id').value = id;
  document.getElementById('zone_name').value = name;
  document.getElementById('zone_gov').value = gov;
  document.getElementById('zone_fee').value = fee;
  document.getElementById('zone_time').value = time;
}
</script>
</body>
</html>
