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

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

/* ==============================
   إضافة / تعديل عميل
   ============================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id   = $_POST['CustomerID'] ?? null;
    $name = trim($_POST['CustomerName']);
    $email = trim($_POST['Email']);
    $notes = trim($_POST['Notes']);
    $isActive = isset($_POST['IsActive']) ? 1 : 0;

    if ($id) {
        $stmt = $pdo->prepare("UPDATE Customers SET CustomerName=?, Email=?, Notes=?, IsActive=? WHERE CustomerID=?");
        $stmt->execute([$name, $email, $notes, $isActive, $id]);
        $success = "✅ تم تعديل العميل بنجاح";
    } else {
        $stmt = $pdo->prepare("INSERT INTO Customers (CustomerName, Email, Notes, IsActive) VALUES (?,?,?,?)");
        $stmt->execute([$name, $email, $notes, $isActive]);
        $success = "✅ تم إضافة العميل بنجاح";
    }
}

/* ==============================
   1) إحصائيات عامة
   ============================== */
$totalCustomers = $pdo->query("SELECT COUNT(*) FROM Customers")->fetchColumn();
$totalInactive  = $pdo->query("SELECT COUNT(*) FROM Customers WHERE IsActive=0")->fetchColumn();
$totalPhones    = $pdo->query("SELECT COUNT(*) FROM CustomerPhones")->fetchColumn();
$totalAddresses = $pdo->query("SELECT COUNT(*) FROM CustomerAddresses")->fetchColumn();

/* ==============================
   2) بحث + Pagination
   ============================== */
$search = $_GET['search'] ?? '';
$where = "";
$params = [];

if ($search) {
    $where = "WHERE c.CustomerName LIKE ? 
              OR c.Email LIKE ? 
              OR EXISTS (SELECT 1 FROM CustomerPhones p 
                         WHERE p.CustomerID=c.CustomerID AND p.Phone LIKE ?)";
    $params = ["%$search%", "%$search%", "%$search%"];
}

// إعداد الـ Pagination
$perPage = 20; // عدد العملاء في الصفحة
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $perPage;

// العدد الكلي للنتائج بعد الفلترة
$countSql = "SELECT COUNT(*) FROM Customers c $where";
$stmt = $pdo->prepare($countSql);
$stmt->execute($params);
$totalCustomersFound = $stmt->fetchColumn();
$totalPages = ceil($totalCustomersFound / $perPage);

/* ==============================
   3) جلب العملاء (مع LIMIT)
   ============================== */
$sql = "SELECT c.*,
           (SELECT COUNT(*) FROM CustomerPhones p WHERE p.CustomerID=c.CustomerID) as PhoneCount,
           (SELECT COUNT(*) FROM CustomerAddresses a WHERE a.CustomerID=c.CustomerID) as AddressCount
        FROM Customers c
        $where
        ORDER BY c.CustomerID DESC
        LIMIT $perPage OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$customers = $stmt->fetchAll();

/* ==============================
   4) جلب المحافظات والمناطق
   ============================== */
$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(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);

?>
<!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", Tahoma, Arial, sans-serif;
  background: #f5f7fa;
  margin: 0;
  padding: 0;
  color: #333;
}

/* ==========================
   الهيدر
   ========================== */
header {
  background: linear-gradient(135deg,#0f2027,#203a43,#2c5364);
  color: #fff;
  padding: 15px 30px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 5px 20px rgba(0,0,0,0.3);
  position: relative;
}
header h1 {
  margin: 0;
  font-size: 22px;
  font-weight: bold;
  text-align: center;
  flex: 1;
}

/* بيانات المستخدم */
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  background: rgba(255,255,255,0.1);
  padding: 6px 14px;
  border-radius: 50px;
  transition: all 0.3s ease-in-out;
}
.user-info:hover {
  background: rgba(255,255,255,0.2);
}
.user-info img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #1abc9c;
}
.user-info span {
  font-weight: bold;
  font-size: 14px;
}
.user-info a {
  background: #e74c3c;
  border: none;
  color: #fff;
  padding: 5px 12px;
  border-radius: 30px;
  font-size: 13px;
  text-decoration: none;
  transition: background 0.3s;
}
.user-info a:hover {
  background: #c0392b;
}

/* زر الوضع الليلي */
#darkSwitch {
  background: #1abc9c;
  color: #fff;
  border: none;
  border-radius: 30px;
  padding: 8px 16px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s;
}
#darkSwitch:hover {
  background: #16a085;
}

/* الوضع الليلي */
body.dark {
  background:#121212;
  color:#eee;
}
body.dark header {
  background: linear-gradient(135deg,#000,#333);
  border-bottom: 3px solid #1abc9c;
}
body.dark .user-info {
  background: rgba(255,255,255,0.1);
}
body.dark .card {
  background: #1e1e1e;
  color: #fff;
}
body.dark .accordion-button {
  background:#222;
  color:#fff;
}
body.dark .table {
  color: #eee;
}

/* ==========================
   محتوى الصفحة
   ========================== */
.container {
  max-width: 1200px;
  margin: auto;
  padding: 20px;
}

.card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  border: none;
  margin-bottom: 20px;
}
.card-header {
  background: linear-gradient(135deg,#1d2671,#c33764);
  color: #fff;
  font-weight: bold;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

.badge {
  font-size: 0.8rem;
  padding: 6px 10px;
  border-radius: 8px;
}

/* الأكورديون */
.accordion-button {
  font-weight: bold;
  background: #f1f1f1;
  border-radius: 8px;
  transition: all 0.3s;
}
.accordion-button:not(.collapsed) {
  background: #1abc9c;
  color: #fff;
}
.accordion-item {
  border: none;
  margin-bottom: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

/* الجداول */
.table {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}
.table th {
  background: #2c5364;
  color: #fff;
  text-align: center;
}
.table td {
  text-align: center;
  vertical-align: middle;
}

/* فورم البحث */
.input-group input {
  border-radius: 30px 0 0 30px;
}
.input-group button {
  border-radius: 0 30px 30px 0;
}

/* فورم إضافة عميل */
form .btn {
  border-radius: 30px;
}

/* Pagination */
.pagination .page-link {
  border-radius: 8px;
  margin: 0 3px;
  color: #2c5364;
}
.pagination .active .page-link {
  background: #1abc9c;
  border-color: #1abc9c;
}


</style>


</head>
<body>
<header>
    <!-- بيانات المستخدم يمين -->
    <div class="user-info">
    <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><?= htmlspecialchars($_SESSION['admin_username']) ?></span>
      <a href="logout.php"><i class="fa-solid fa-right-from-bracket"></i> خروج</a>
    </div>

    <!-- عنوان الصفحة في الوسط -->
    <h1><i class="fa-solid fa-gauge-high"></i>ادارة العملاء</h1>

    <!-- زر الوضع الليلي شمال -->
    <button id="darkSwitch">🌙</button>
</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="container py-4">

  <!-- إحصائيات -->
  <div class="row mb-4 text-center">
    <div class="col-md-3">
      <div class="card"><div class="card-body">
        <h6 class="text-muted">عدد العملاء</h6>
        <h3 class="fw-bold text-primary"><?= $totalCustomers ?></h3>
      </div></div>
    </div>
    <div class="col-md-3">
      <div class="card"><div class="card-body">
        <h6 class="text-muted">عملاء موقوفين</h6>
        <h3 class="fw-bold text-danger"><?= $totalInactive ?></h3>
      </div></div>
    </div>
    <div class="col-md-3">
      <div class="card"><div class="card-body">
        <h6 class="text-muted">إجمالي الهواتف</h6>
        <h3 class="fw-bold text-info"><?= $totalPhones ?></h3>
      </div></div>
    </div>
    <div class="col-md-3">
      <div class="card"><div class="card-body">
        <h6 class="text-muted">إجمالي العناوين</h6>
        <h3 class="fw-bold text-success"><?= $totalAddresses ?></h3>
      </div></div>
    </div>
  </div>

  <!-- بحث -->
  <form class="input-group mb-4">
    <input type="text" name="search" class="form-control" placeholder="🔎 بحث بالاسم أو الهاتف أو البريد" value="<?= htmlspecialchars($search) ?>">
    <button class="btn btn-outline-primary">بحث</button>
    <a href="customers.php" class="btn btn-outline-secondary">إلغاء</a>
  </form>

  <!-- فورم إضافة/تعديل عميل -->
  <div class="card mb-4">
    <div class="card-header">➕ إضافة / تعديل عميل</div>
    <div class="card-body">
      <form method="post" action="" class="row g-3">
        <input type="hidden" name="CustomerID" id="CustomerID">
        <div class="col-md-4">
          <label class="form-label">اسم العميل</label>
          <input type="text" name="CustomerName" id="CustomerName" class="form-control" required>
        </div>
        <div class="col-md-4">
          <label class="form-label">البريد الإلكتروني</label>
          <input type="email" name="Email" id="Email" class="form-control">
        </div>
        <div class="col-md-4">
          <label class="form-label">ملاحظات</label>
          <input type="text" name="Notes" id="Notes" class="form-control">
        </div>
        <div class="col-md-2">
          <div class="form-check mt-4">
            <input type="checkbox" name="IsActive" id="IsActive" class="form-check-input" checked>
            <label for="IsActive" class="form-check-label">مفعل</label>
          </div>
        </div>
        <div class="col-md-10 text-end">
          <button type="submit" class="btn btn-success">💾 حفظ</button>
          <button type="reset" class="btn btn-secondary">إلغاء</button>
        </div>
      </form>
    </div>
  </div>

  <!-- العملاء -->
  <div class="accordion" id="customersAccordion">
    <?php foreach($customers as $c): ?>
    <div class="accordion-item mb-2">
      <h2 class="accordion-header">
        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
                data-bs-target="#cust<?= $c['CustomerID'] ?>">
          <?= htmlspecialchars($c['CustomerName']) ?> 
          <span class="badge bg-info ms-2">📞 <?= $c['PhoneCount'] ?></span>
          <span class="badge bg-success ms-2">📍 <?= $c['AddressCount'] ?></span>
        </button>
      </h2>
      <div id="cust<?= $c['CustomerID'] ?>" class="accordion-collapse collapse" data-bs-parent="#customersAccordion">
      <div class="accordion-body">

<!-- هواتف -->
<h6>📞 هواتف</h6>
<table class="table table-sm">
  <thead><tr><th>الرقم</th><th>أساسي</th><th>إجراءات</th></tr></thead>
  <tbody>
    <?php
    $phones = $pdo->prepare("SELECT * FROM CustomerPhones WHERE CustomerID=?");
    $phones->execute([$c['CustomerID']]);
    foreach($phones as $p): ?>
    <tr>
      <td><?= htmlspecialchars($p['Phone']) ?></td>
      <td><?= $p['IsDefault'] ? '✅' : '' ?></td>
      <td>
        <a href="customer_phone_delete.php?id=<?= $p['PhoneID'] ?>" class="btn btn-sm btn-danger">🗑️</a>
      </td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table>
<!-- إضافة رقم جديد -->
<form method="post" action="customer_phone_add.php" class="row g-2 mt-2">
<input type="hidden" name="CustomerID" value="<?= $c['CustomerID'] ?>">
<div class="col-md-6">
<input type="text" name="Phone" class="form-control" placeholder="رقم جديد" required>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="IsDefault" class="form-check-input" id="defaultPhone<?= $c['CustomerID'] ?>">
<label for="defaultPhone<?= $c['CustomerID'] ?>" class="form-check-label">أساسي</label>
</div>
</div>
<div class="col-md-2 text-end">
<button type="submit" class="btn btn-sm btn-success">➕</button>
</div>
</form>

<!-- عناوين -->
<h6>📍 عناوين</h6>
<table class="table table-sm">
  <thead><tr><th>العنوان</th><th>المدينة</th><th>المنطقة</th><th>أساسي</th><th>إجراءات</th></tr></thead>
  <tbody>
    <?php
    $addrs = $pdo->prepare("SELECT a.*, z.ZoneName, g.GovernateName
                            FROM CustomerAddresses a 
                            LEFT JOIN Zones z ON a.ZoneID=z.ZoneID
                            LEFT JOIN Governates g ON z.GovernateID=g.GovernateID
                            WHERE a.CustomerID=?");
    $addrs->execute([$c['CustomerID']]);
    foreach($addrs as $a): ?>
    <tr>
      <td><?= htmlspecialchars($a['Address']) ?></td>
      <td><?= htmlspecialchars($a['City']) ?></td>
      <td><?= htmlspecialchars($a['ZoneName'] ?? '') ?></td>
      <td><?= $a['IsDefault'] ? '✅' : '' ?></td>
      <td>
        <a href="customer_address_delete.php?id=<?= $a['AddressID'] ?>" class="btn btn-sm btn-danger">🗑️</a>
      </td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table>
<!-- إضافة عنوان جديد -->
<form method="post" action="customer_address_add.php" class="row g-2 mt-2">
<input type="hidden" name="CustomerID" value="<?= $c['CustomerID'] ?>">
<div class="col-md-6">
<input type="text" name="Address" class="form-control" placeholder="العنوان" required>
</div>
<div class="col-md-3">
<input type="text" name="City" class="form-control" placeholder="المدينة">
</div>
<div class="col-md-3">
<select name="ZoneID" class="form-select">
<option value="">اختر المنطقة</option>
<?php foreach ($zones as $gid => $arr): 
foreach ($arr as $z): ?>
<option value="<?= $z['ZoneID'] ?>"><?= htmlspecialchars($z['GovernateName']." - ".$z['ZoneName']) ?></option>
<?php endforeach; endforeach; ?>
</select>
</div>
<div class="col-md-3">
<div class="form-check">
<input type="checkbox" name="IsDefault" class="form-check-input" id="defaultAddr<?= $c['CustomerID'] ?>">
<label for="defaultAddr<?= $c['CustomerID'] ?>" class="form-check-label">أساسي</label>
</div>
</div>
<div class="col-md-2 text-end">
<button type="submit" class="btn btn-sm btn-success">➕</button>
</div>
</form>

</div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- روابط الصفحات -->
  <?php if ($totalPages > 1): ?>
  <nav class="mt-4">
    <ul class="pagination justify-content-center">
      <?php for ($i = 1; $i <= $totalPages; $i++): ?>
        <li class="page-item <?= $i == $page ? 'active' : '' ?>">
          <a class="page-link" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
        </li>
      <?php endfor; ?>
    </ul>
  </nav>
  <?php endif; ?>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>


