<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../inc/layout.php';

if (empty($_SESSION['user_id'])) {
    header('Location: ../index.html?e=1');
    exit;
}

$pdo = db();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

if (!function_exists('h')) {
    function h($s): string
    {
        return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('branch_name_ar_simple')) {
    function branch_name_ar_simple(int $branchId): string
    {
        return match ($branchId) {
            1 => 'أبوظبي',
            2 => 'دبي',
            3 => 'الشارقة',
            4 => 'العين',
            default => 'غير محدد',
        };
    }
}

$branchId = (int)($_SESSION['branch_id'] ?? 1);
$role     = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$isOwner  = ($role === 'OWNER');

$q = trim((string)($_GET['q'] ?? ''));
$requestedBranch = (int)($_GET['branch_id'] ?? 0);

/* لغير الأونر: نظهر القائمة لكن لا نسمح بتغيير الفرع فعليًا */
$filterBranch = $isOwner ? $requestedBranch : $branchId;

$params = [];
$where = [];

if (!$isOwner) {
    $where[] = 'branch_id = :user_branch';
    $params[':user_branch'] = $branchId;
} elseif ($filterBranch > 0) {
    $where[] = 'branch_id = :filter_branch';
    $params[':filter_branch'] = $filterBranch;
}

if ($q !== '') {
    $where[] = '(
        name LIKE :q_name
        OR phone LIKE :q_phone
        OR email LIKE :q_email
        OR id_number LIKE :q_id_number
    )';

    $searchLike = '%' . $q . '%';
    $params[':q_name'] = $searchLike;
    $params[':q_phone'] = $searchLike;
    $params[':q_email'] = $searchLike;
    $params[':q_id_number'] = $searchLike;
}

$sql = "
    SELECT
        id,
        name,
        id_number,
        phone,
        email,
        notes,
        reminder_date,
        created_at,
        document,
        branch_id
    FROM clients
";

if ($where) {
    $sql .= ' WHERE ' . implode(' AND ', $where);
}

$sql .= ' ORDER BY id DESC';

$st = $pdo->prepare($sql);
$st->execute($params);
$clients = $st->fetchAll();

$totalClients = 0;
$branchClients = 0;
$thisMonthClients = 0;
$withPhoneClients = 0;

try {
    if ($isOwner) {
        $totalClients = (int)$pdo->query("SELECT COUNT(*) FROM clients")->fetchColumn();

        $stm = $pdo->prepare("
            SELECT COUNT(*)
            FROM clients
            WHERE created_at >= DATE_FORMAT(CURDATE(), '%Y-%m-01')
        ");
        $stm->execute();
        $thisMonthClients = (int)$stm->fetchColumn();

        $stp = $pdo->prepare("
            SELECT COUNT(*)
            FROM clients
            WHERE phone IS NOT NULL AND TRIM(phone) <> ''
        ");
        $stp->execute();
        $withPhoneClients = (int)$stp->fetchColumn();

        $targetBranch = $filterBranch > 0 ? $filterBranch : $branchId;
        $stb = $pdo->prepare("SELECT COUNT(*) FROM clients WHERE branch_id = ?");
        $stb->execute([$targetBranch]);
        $branchClients = (int)$stb->fetchColumn();
    } else {
        $st1 = $pdo->prepare("SELECT COUNT(*) FROM clients WHERE branch_id = ?");
        $st1->execute([$branchId]);
        $totalClients = (int)$st1->fetchColumn();
        $branchClients = $totalClients;

        $st2 = $pdo->prepare("
            SELECT COUNT(*)
            FROM clients
            WHERE branch_id = ?
              AND created_at >= DATE_FORMAT(CURDATE(), '%Y-%m-01')
        ");
        $st2->execute([$branchId]);
        $thisMonthClients = (int)$st2->fetchColumn();

        $st3 = $pdo->prepare("
            SELECT COUNT(*)
            FROM clients
            WHERE branch_id = ?
              AND phone IS NOT NULL
              AND TRIM(phone) <> ''
        ");
        $st3->execute([$branchId]);
        $withPhoneClients = (int)$st3->fetchColumn();
    }
} catch (Throwable $e) {
}
render_layout_start('العملاء');
?>

<style>
.clients-shell{
  width:100%;
  max-width:100%;
}

.clients-hero{
  display:grid;
  grid-template-columns:minmax(0,1fr) auto;
  gap:16px;
  align-items:start;
  margin-bottom:18px;
}

.clients-hero-card{
  border:1px solid rgba(255,255,255,.08);
  background:linear-gradient(135deg, rgba(255,255,255,.05), rgba(255,255,255,.03));
  border-radius:22px;
  padding:22px;
  box-shadow:0 14px 34px rgba(0,0,0,.18);
}

.clients-title{
  margin:0 0 6px;
  font-size:36px;
  font-weight:900;
  line-height:1.1;
  color:#fff;
}

.clients-sub{
  margin:0;
  color:var(--layout-muted);
  font-size:15px;
  line-height:1.8;
}

.clients-add-btn{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:8px;
  min-height:52px;
  padding:0 18px;
  border-radius:16px;
  background:linear-gradient(180deg, rgba(0,106,122,.42), rgba(0,66,79,.24));
  border:1px solid rgba(0,106,122,.45);
  color:#fff;
  text-decoration:none;
  font-weight:800;
  white-space:nowrap;
  box-shadow:0 10px 24px rgba(0,0,0,.16);
}

.clients-add-btn:hover{
  filter:brightness(1.06);
}

.clients-stats{
  display:grid;
  grid-template-columns:repeat(4, minmax(0,1fr));
  gap:14px;
  margin-bottom:18px;
}

.clients-stat{
  border:1px solid rgba(255,255,255,.08);
  background:rgba(255,255,255,.04);
  border-radius:20px;
  padding:18px 16px;
  box-shadow:0 12px 28px rgba(0,0,0,.14);
}

.clients-stat-label{
  color:var(--layout-muted);
  font-size:13px;
  margin-bottom:10px;
}

.clients-stat-value{
  color:#fff;
  font-size:30px;
  font-weight:900;
  line-height:1;
}

.clients-toolbar{
  border:1px solid rgba(255,255,255,.08);
  background:rgba(255,255,255,.04);
  border-radius:22px;
  padding:16px;
  margin-bottom:18px;
}

.clients-filter-form{
  display:grid;
  grid-template-columns:minmax(0,1.4fr) 180px auto auto;
  gap:12px;
  align-items:center;
}

.clients-input,
.clients-select{
  width:100%;
  min-width:0;
  height:48px;
  border-radius:14px;
  border:1px solid rgba(255,255,255,.10);
  background:rgba(0,0,0,.18);
  color:#fff;
  padding:0 14px;
  font:inherit;
  outline:none;
}

.clients-input::placeholder{
  color:rgba(255,255,255,.25);
}

.clients-select option{
  background:#0b2633;
  color:#fff;
}

.clients-filter-btn,
.clients-reset-btn{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-height:48px;
  padding:0 16px;
  border-radius:14px;
  font:inherit;
  font-weight:800;
  text-decoration:none;
  cursor:pointer;
  white-space:nowrap;
}

.clients-filter-btn{
  border:1px solid rgba(0,106,122,.45);
  background:linear-gradient(180deg, rgba(0,106,122,.35), rgba(0,66,79,.18));
  color:#fff;
}

.clients-reset-btn{
  border:1px solid rgba(255,255,255,.10);
  background:rgba(255,255,255,.04);
  color:#fff;
}

.clients-table-card{
  border:1px solid rgba(255,255,255,.08);
  background:rgba(255,255,255,.04);
  border-radius:24px;
  overflow:hidden;
  box-shadow:0 14px 34px rgba(0,0,0,.16);
}

.clients-table-head{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:12px;
  padding:18px 20px;
  border-bottom:1px solid rgba(255,255,255,.08);
  background:linear-gradient(180deg, rgba(255,255,255,.04), rgba(255,255,255,.02));
}

.clients-table-title{
  margin:0;
  color:#fff;
  font-size:18px;
  font-weight:900;
}

.clients-table-sub{
  color:var(--layout-muted);
  font-size:13px;
}

.clients-table-wrap{
  width:100%;
  overflow-x:auto;
  overflow-y:hidden;
  -webkit-overflow-scrolling:touch;
}

.clients-table-wrap::-webkit-scrollbar{
  height:10px;
}

.clients-table-wrap::-webkit-scrollbar-thumb{
  background:rgba(255,255,255,.14);
  border-radius:999px;
}

.clients-table{
  width:100%;
  min-width:980px;
  border-collapse:separate;
  border-spacing:0;
}

.clients-table thead th{
  padding:16px 14px;
  text-align:right;
  font-size:14px;
  font-weight:900;
  color:#fff;
  background:rgba(255,255,255,.05);
  border-bottom:1px solid rgba(255,255,255,.08);
  white-space:nowrap;
}

.clients-table tbody td{
  padding:16px 14px;
  color:var(--layout-text);
  border-bottom:1px solid rgba(255,255,255,.06);
  vertical-align:middle;
  white-space:nowrap;
}

.clients-table tbody tr:hover{
  background:rgba(255,255,255,.03);
}

.clients-table tbody tr:last-child td{
  border-bottom:none;
}

.clients-name{
  display:flex;
  flex-direction:column;
  gap:4px;
}

.clients-name-main{
  font-weight:800;
  color:#fff;
}

.clients-name-sub{
  color:var(--layout-muted);
  font-size:12px;
}

.clients-branch{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-width:72px;
  padding:6px 12px;
  border-radius:999px;
  background:rgba(255,255,255,.08);
  border:1px solid rgba(255,255,255,.10);
  color:#fff;
  font-size:12px;
  font-weight:800;
}

.clients-actions-cell{
  display:flex;
  align-items:center;
  gap:8px;
  flex-wrap:wrap;
}

.clients-action{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-height:38px;
  padding:0 14px;
  border-radius:12px;
  text-decoration:none;
  font-size:13px;
  font-weight:800;
  border:1px solid rgba(255,255,255,.08);
}

.clients-action.view{
  background:#0b91b1;
  color:#fff;
}

.clients-action.edit{
  background:rgba(255,255,255,.06);
  color:#fff;
}

.clients-empty{
  text-align:center;
  padding:34px 20px !important;
  color:var(--layout-muted);
  font-weight:700;
}

@media (max-width: 1200px){
  .clients-stats{
    grid-template-columns:repeat(2, minmax(0,1fr));
  }

  .clients-filter-form{
    grid-template-columns:1fr 1fr;
  }
}

@media (max-width: 800px){
  .clients-hero{
    grid-template-columns:1fr;
  }

  .clients-stats{
    grid-template-columns:1fr;
  }

  .clients-filter-form{
    grid-template-columns:1fr;
  }

  .clients-title{
    font-size:28px;
  }
}
.clients-select.is-disabled{
  opacity:.58;
  cursor:not-allowed;
  pointer-events:none;
  background:rgba(255,255,255,.05);
  color:rgba(255,255,255,.72);
}
/* =========================
   GLASS EFFECT 🔥
========================= */

/* الكروت */
.clients-hero-card,
.clients-stat,
.clients-toolbar,
.clients-table-card{
  position:relative;
  backdrop-filter:blur(18px);
  -webkit-backdrop-filter:blur(18px);

  background:linear-gradient(
    145deg,
    rgba(255,255,255,.08),
    rgba(255,255,255,.03)
  ) !important;

  border:1px solid rgba(255,255,255,.12) !important;
  box-shadow:
    0 20px 45px rgba(0,0,0,.25),
    inset 0 1px 0 rgba(255,255,255,.25);
}

/* لمعة متحركة */
.clients-hero-card::after,
.clients-stat::after,
.clients-toolbar::after,
.clients-table-card::after{
  content:"";
  position:absolute;
  top:0;
  left:-80%;
  width:50%;
  height:100%;

  background:linear-gradient(
    120deg,
    transparent,
    rgba(255,255,255,.45),
    transparent
  );

  transform:skewX(-20deg);
  animation:glassShine 6s infinite;
}

/* الحركة */
@keyframes glassShine{
  0%{ left:-80%; opacity:0; }
  30%{ opacity:.8; }
  100%{ left:140%; opacity:0; }
}
.clients-add-btn,
.clients-filter-btn{
  position:relative;
  overflow:hidden;
}

.clients-add-btn::after,
.clients-filter-btn::after{
  content:"";
  position:absolute;
  top:0;
  left:-70%;
  width:50%;
  height:100%;

  background:linear-gradient(
    120deg,
    transparent,
    rgba(255,255,255,.6),
    transparent
  );

  transform:skewX(-20deg);
  animation:btnShine 3.5s infinite;
}

@keyframes btnShine{
  0%{ left:-70%; }
  100%{ left:130%; }
}
.clients-table thead th{
  position:relative;
  overflow:hidden;
}

.clients-table thead th::after{
  content:"";
  position:absolute;
  top:0;
  left:-60%;
  width:40%;
  height:100%;

  background:linear-gradient(120deg,transparent,rgba(255,255,255,.25),transparent);
  animation:shineHead 5s infinite;
}

@keyframes shineHead{
  0%{ left:-60%; }
  100%{ left:140%; }
}
/* =========================
   GOLD GLASS EFFECT ✨
========================= */

.clients-hero-card,
.clients-stat,
.clients-toolbar,
.clients-table-card{
  position:relative;
  overflow:hidden;

  backdrop-filter:blur(18px);
  -webkit-backdrop-filter:blur(18px);

  background:linear-gradient(
    145deg,
    rgba(255,255,255,.07),
    rgba(255,255,255,.03)
  ) !important;

  border:1px solid rgba(212,175,55,.25) !important;

  box-shadow:
    0 20px 45px rgba(0,0,0,.25),
    0 0 25px rgba(212,175,55,.15),
    inset 0 1px 0 rgba(255,255,255,.25);
}

/* ✨ لمعة ذهبية متحركة */
.clients-hero-card::after,
.clients-stat::after,
.clients-toolbar::after,
.clients-table-card::after{
  content:"";
  position:absolute;
  top:0;
  left:-80%;
  width:50%;
  height:100%;

  background:linear-gradient(
    120deg,
    transparent,
    rgba(212,175,55,.65),
    rgba(255,215,106,.35),
    transparent
  );

  transform:skewX(-20deg);
  animation:goldShine 6s infinite;
}

@keyframes goldShine{
  0%{ left:-80%; opacity:0; }
  30%{ opacity:.9; }
  100%{ left:140%; opacity:0; }
}
/* لمعة ذهبية خفيفة جدًا */
.clients-hero-card::after,
.clients-stat::after,
.clients-toolbar::after,
.clients-table-card::after{
  content:"";
  position:absolute;
  top:0;
  left:-90%;
  width:35%;                 /* أصغر */
  height:100%;

  background:linear-gradient(
    120deg,
    transparent,
    rgba(212,175,55,.25),   /* 👈 أخف بكثير */
    rgba(255,215,106,.15),  /* 👈 لمسة خفيفة */
    transparent
  );

  transform:skewX(-18deg);
  animation:goldShineSoft 8s infinite; /* 👈 أبطأ */
  opacity:.6;                          /* 👈 تهدئة إضافية */
}

@keyframes goldShineSoft{
  0%{ left:-90%; opacity:0; }
  40%{ opacity:.5; }
  100%{ left:130%; opacity:0; }
}
.clients-add-btn::after,
.clients-filter-btn::after{
  background:linear-gradient(
    120deg,
    transparent,
    rgba(255,215,106,.35),  /* أخف */
    transparent
  );

  animation:goldBtnShineSoft 5s infinite;
}

@keyframes goldBtnShineSoft{
  0%{ left:-80%; }
  100%{ left:120%; }
}
</style>

<div class="clients-shell">
  <div class="clients-hero">
    <div class="clients-hero-card">
      <h1 class="clients-title">العملاء</h1>
      <p class="clients-sub">إدارة بيانات العملاء والبحث عنهم وعرض ملفاتهم داخل النظام بشكل منظم واحترافي.</p>
    </div>

    <div>
      <a class="clients-add-btn" href="<?= h(u('clients/add.php')) ?>">+ إضافة عميل</a>
    </div>
  </div>

  <div class="clients-stats">
    <div class="clients-stat">
      <div class="clients-stat-label">إجمالي العملاء</div>
      <div class="clients-stat-value"><?= (int)$totalClients ?></div>
    </div>

    <div class="clients-stat">
      <div class="clients-stat-label">عملاء هذا الشهر</div>
      <div class="clients-stat-value"><?= (int)$thisMonthClients ?></div>
    </div>

    <div class="clients-stat">
      <div class="clients-stat-label">عملاء الفرع الحالي</div>
      <div class="clients-stat-value"><?= (int)$branchClients ?></div>
    </div>

    <div class="clients-stat">
      <div class="clients-stat-label">لديهم رقم هاتف</div>
      <div class="clients-stat-value"><?= (int)$withPhoneClients ?></div>
    </div>
  </div>

  <div class="clients-toolbar">
    <form method="get" class="clients-filter-form">
      <input
        class="clients-input"
        type="text"
        name="q"
        value="<?= h($q) ?>"
        placeholder="ابحث بالاسم أو الهاتف أو البريد أو رقم الهوية">

     <select
  class="clients-select<?= !$isOwner ? ' is-disabled' : '' ?>"
  name="branch_id"
  <?= !$isOwner ? 'disabled' : '' ?>
  title="<?= !$isOwner ? 'تبديل الفروع متاح للأونر فقط' : '' ?>"
>
  <option value="0" <?= $filterBranch === 0 ? 'selected' : '' ?>>كل الفروع</option>
  <option value="1" <?= $filterBranch === 1 ? 'selected' : '' ?>>أبوظبي</option>
  <option value="2" <?= $filterBranch === 2 ? 'selected' : '' ?>>دبي</option>
  <option value="3" <?= $filterBranch === 3 ? 'selected' : '' ?>>الشارقة</option>
  <option value="4" <?= $filterBranch === 4 ? 'selected' : '' ?>>العين</option>
</select>

<?php if (!$isOwner): ?>
  <input type="hidden" name="branch_id" value="<?= (int)$branchId ?>">
<?php endif; ?>

      <button class="clients-filter-btn" type="submit">بحث</button>
      <a class="clients-reset-btn" href="<?= h(u('clients/index.php')) ?>">إعادة تعيين</a>
    </form>
  </div>

  <div class="clients-table-card">
    <div class="clients-table-head">
      <div>
        <h2 class="clients-table-title">قائمة العملاء</h2>
        <div class="clients-table-sub">عدد النتائج: <?= count($clients) ?></div>
      </div>
    </div>

    <div class="clients-table-wrap">
      <table class="clients-table">
        <thead>
          <tr>
            <th>#</th>
            <th>العميل</th>
            <th>رقم الهوية</th>
            <th>الهاتف</th>
            <th>الإيميل</th>
            <th>الفرع</th>
            <th>تاريخ الإضافة</th>
            <th>الإجراءات</th>
          </tr>
        </thead>

        <tbody>
          <?php if (!$clients): ?>
            <tr>
              <td colspan="8" class="clients-empty">لا يوجد عملاء مطابقون للبحث حالياً.</td>
            </tr>
          <?php else: ?>
            <?php foreach ($clients as $c): ?>
              <tr>
                <td><?= (int)($c['id'] ?? 0) ?></td>

                <td>
                  <div class="clients-name">
                    <div class="clients-name-main"><?= h($c['name'] ?? '-') ?></div>
                    <div class="clients-name-sub">عميل رقم #<?= (int)($c['id'] ?? 0) ?></div>
                  </div>
                </td>

                <td><?= h($c['id_number'] ?? '-') ?></td>
                <td><?= h($c['phone'] ?? '-') ?></td>
                <td><?= h($c['email'] ?? '-') ?></td>

                <td>
                  <span class="clients-branch">
                    <?= h(branch_name_ar_simple((int)($c['branch_id'] ?? 0))) ?>
                  </span>
                </td>

                <td><?= h(!empty($c['created_at']) ? date('Y-m-d', strtotime((string)$c['created_at'])) : '-') ?></td>

                <td>
                  <div class="clients-actions-cell">
                    <a class="clients-action view" href="<?= h(u('clients/view.php?id=' . (int)$c['id'])) ?>">عرض</a>
                    <a class="clients-action edit" href="<?= h(u('clients/edit.php?id=' . (int)$c['id'])) ?>">تعديل</a>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php
render_layout_end();
?>