
<?php require 'includes/db_connect.php'; ?>

<!-- Handle Delete -->
<?php
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    // Delete officials first (foreign key constraint)
    mysqli_query($conn, "DELETE FROM officials WHERE association_id = $id");
    mysqli_query($conn, "DELETE FROM associations WHERE id = $id");
    header("Location: view_associations.php?msg=deleted");
    exit();
}

// Search / filter
$search = '';
if (!empty($_GET['search'])) {
    $search = mysqli_real_escape_string($conn, $_GET['search']);
}

$where  = $search ? "WHERE association_name LIKE '%$search%' OR location LIKE '%$search%'" : '';
$result = mysqli_query($conn, "SELECT * FROM associations $where ORDER BY id DESC");
$total  = mysqli_num_rows($result);
?>
<?php include 'includes/header.php'; ?>
<?php include 'includes/sidebar.php'; ?>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Sans:wght@300;400;500&display=swap');

  :root {
    --orange:       #F26522;
    --orange-light: #FFF0E8;
    --orange-glow:  rgba(242,101,34,0.15);
    --dark:         #1A1A2E;
    --mid:          #2C2C54;
    --surface:      #ffffff;
    --border:       #E8E8F0;
    --text:         #1A1A2E;
    --muted:        #7A7A9A;
    --green:        #22C55E;
    --red:          #EF4444;
    --blue:         #3B82F6;
    --radius:       14px;
    --shadow:       0 4px 24px rgba(26,26,46,0.08);
    --shadow-hover: 0 12px 40px rgba(242,101,34,0.18);
  }

  * { box-sizing: border-box; }

  /* ── Page Header ── */
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 16px;
    margin-bottom: 28px;
  }

  .page-title {
    font-family: 'Syne', sans-serif;
    font-size: 1.75rem;
    font-weight: 800;
    color: var(--dark);
    display: inline-block;
  }

  .page-title span { color: var(--orange); }

  .page-title::after {
    content: '';
    display: block;
    width: 48px;
    height: 4px;
    background: var(--orange);
    border-radius: 2px;
    margin-top: 6px;
  }

  .btn-add {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    background: var(--orange);
    color: #fff;
    font-family: 'Syne', sans-serif;
    font-weight: 700;
    font-size: 0.88rem;
    padding: 10px 22px;
    border-radius: 50px;
    text-decoration: none;
    border: none;
    cursor: pointer;
    transition: background .2s, box-shadow .2s, transform .15s;
    box-shadow: 0 4px 14px rgba(242,101,34,0.35);
  }

  .btn-add:hover {
    background: #d4541a;
    box-shadow: 0 6px 20px rgba(242,101,34,0.45);
    transform: translateY(-2px);
    color: #fff;
    text-decoration: none;
  }

  /* ── Stats Strip ── */
  .stats-strip {
    display: flex;
    gap: 16px;
    margin-bottom: 24px;
    flex-wrap: wrap;
  }

  .stat-card {
    flex: 1;
    min-width: 130px;
    background: var(--surface);
    border-radius: var(--radius);
    padding: 18px 22px;
    border: 1px solid var(--border);
    display: flex;
    align-items: center;
    gap: 14px;
    box-shadow: var(--shadow);
    transition: transform .2s, box-shadow .2s;
  }

  .stat-card:hover { transform: translateY(-3px); box-shadow: var(--shadow-hover); }

  .stat-icon {
    width: 44px; height: 44px;
    border-radius: 12px;
    display: flex; align-items: center; justify-content: center;
    font-size: 1.3rem; flex-shrink: 0;
  }

  .stat-icon.orange { background: var(--orange-light); color: var(--orange); }
  .stat-icon.green  { background: #ECFDF5; color: var(--green); }
  .stat-icon.blue   { background: #EFF6FF; color: var(--blue); }
  .stat-icon.red    { background: #FEF2F2; color: var(--red); }

  .stat-info p {
    font-size: 0.73rem; color: var(--muted);
    font-weight: 500; text-transform: uppercase; letter-spacing: .05em;
  }

  .stat-info h4 {
    font-family: 'Syne', sans-serif;
    font-size: 1.5rem; font-weight: 800; color: var(--dark); line-height: 1.1;
  }

  /* ── Toolbar ── */
  .toolbar {
    display: flex; align-items: center; gap: 12px;
    margin-bottom: 20px; flex-wrap: wrap;
  }

  .search-box { flex: 1; min-width: 220px; position: relative; }

  .search-box input {
    width: 100%;
    padding: 10px 16px 10px 42px;
    border: 1.5px solid var(--border);
    border-radius: 50px;
    font-family: 'DM Sans', sans-serif; font-size: 0.9rem;
    background: var(--surface); color: var(--text);
    transition: border-color .2s, box-shadow .2s; outline: none;
  }

  .search-box input:focus {
    border-color: var(--orange);
    box-shadow: 0 0 0 3px var(--orange-glow);
  }

  .search-box svg {
    position: absolute; left: 14px; top: 50%;
    transform: translateY(-50%); color: var(--muted);
    width: 16px; height: 16px; pointer-events: none;
  }

  .results-label { font-size: 0.85rem; color: var(--muted); white-space: nowrap; }
  .results-label strong { color: var(--orange); font-family: 'Syne', sans-serif; }

  /* ── Alert ── */
  .alert-custom {
    padding: 12px 20px; border-radius: var(--radius);
    font-size: 0.9rem; margin-bottom: 20px;
    display: flex; align-items: center; gap: 10px;
    animation: slideDown .35s ease;
  }

  .alert-success { background: #ECFDF5; color: #166534; border: 1px solid #BBF7D0; }
  .alert-danger  { background: #FEF2F2; color: #991B1B; border: 1px solid #FECACA; }

  @keyframes slideDown {
    from { opacity:0; transform:translateY(-10px); }
    to   { opacity:1; transform:translateY(0); }
  }

  /* ── Table Card ── */
  .table-card {
    background: var(--surface);
    border-radius: var(--radius);
    border: 1px solid var(--border);
    box-shadow: var(--shadow);
    overflow: hidden;
  }

  .table-responsive { overflow-x: auto; }

  table { width: 100%; border-collapse: collapse; }

  thead { background: var(--dark); }

  thead th {
    font-family: 'Syne', sans-serif;
    font-size: 0.75rem; font-weight: 700;
    color: #9999BB; text-transform: uppercase;
    letter-spacing: .08em; padding: 14px 18px;
    text-align: left; white-space: nowrap;
  }

  thead th:first-child { color: var(--orange); }

  tbody tr {
    border-bottom: 1px solid var(--border);
    transition: background .15s;
    animation: rowIn .3s ease both;
  }

  tbody tr:last-child { border-bottom: none; }
  tbody tr:hover { background: #FAFAFA; }

  tbody td {
    padding: 14px 18px; font-size: 0.9rem;
    color: var(--text); vertical-align: middle;
  }

  @keyframes rowIn {
    from { opacity:0; transform:translateX(-10px); }
    to   { opacity:1; transform:translateX(0); }
  }

  tbody tr:nth-child(1)  { animation-delay:.04s; }
  tbody tr:nth-child(2)  { animation-delay:.07s; }
  tbody tr:nth-child(3)  { animation-delay:.10s; }
  tbody tr:nth-child(4)  { animation-delay:.13s; }
  tbody tr:nth-child(5)  { animation-delay:.16s; }
  tbody tr:nth-child(6)  { animation-delay:.19s; }
  tbody tr:nth-child(7)  { animation-delay:.22s; }
  tbody tr:nth-child(8)  { animation-delay:.25s; }

  .sn-badge {
    display: inline-flex; align-items: center; justify-content: center;
    width: 30px; height: 30px;
    background: var(--orange-light); color: var(--orange);
    font-family: 'Syne', sans-serif; font-weight: 700;
    font-size: 0.8rem; border-radius: 8px;
  }

  .assoc-name {
    font-weight: 600; color: var(--dark);
    font-family: 'Syne', sans-serif; font-size: 0.92rem;
  }

  .location-pill {
    display: inline-flex; align-items: center; gap: 5px;
    background: #F0F0FA; color: var(--mid);
    font-size: 0.8rem; padding: 4px 10px;
    border-radius: 50px; font-weight: 500;
  }

  .date-text { font-size: 0.82rem; color: var(--muted); font-weight: 500; }

  .badge-status {
    display: inline-block; padding: 4px 12px; border-radius: 50px;
    font-size: 0.76rem; font-weight: 700;
    font-family: 'Syne', sans-serif; letter-spacing: .03em;
  }

  .badge-active   { background:#ECFDF5; color:#166534; }
  .badge-expiring { background:#FFF7ED; color:#9A3412; }
  .badge-expired  { background:#FEF2F2; color:#991B1B; }

  /* ── Actions ── */
  .actions { display: flex; gap: 8px; align-items: center; }

  .btn-action {
    display: inline-flex; align-items: center; justify-content: center;
    width: 34px; height: 34px; border-radius: 10px;
    border: none; cursor: pointer; text-decoration: none;
    transition: transform .15s, box-shadow .15s, background .15s;
    font-size: 0.9rem;
  }

  .btn-action:hover { transform: translateY(-2px); }

  .btn-view   { background:#EFF6FF; color:var(--blue); }
  .btn-edit   { background:#FFF7ED; color:var(--orange); }
  .btn-delete { background:#FEF2F2; color:var(--red); }

  .btn-view:hover   { background:var(--blue);   color:#fff; box-shadow:0 4px 12px rgba(59,130,246,.35); }
  .btn-edit:hover   { background:var(--orange);  color:#fff; box-shadow:0 4px 12px rgba(242,101,34,.35); }
  .btn-delete:hover { background:var(--red);     color:#fff; box-shadow:0 4px 12px rgba(239,68,68,.35); }

  /* ── Empty State ── */
  .empty-state { text-align:center; padding:64px 24px; }
  .empty-state .empty-icon { font-size:3.5rem; margin-bottom:16px; opacity:.35; }
  .empty-state h5 { font-family:'Syne',sans-serif; font-weight:700; color:var(--dark); font-size:1.1rem; margin-bottom:8px; }
  .empty-state p  { color:var(--muted); font-size:0.88rem; }

  /* ── Delete Modal ── */
  .modal-overlay {
    display:none; position:fixed; inset:0;
    background:rgba(26,26,46,0.55); backdrop-filter:blur(4px);
    z-index:1000; align-items:center; justify-content:center;
    animation:fadeIn .2s ease;
  }

  .modal-overlay.show { display:flex; }

  @keyframes fadeIn { from{opacity:0;} to{opacity:1;} }

  .modal-box {
    background:var(--surface); border-radius:20px;
    padding:32px; max-width:480px; width:92%;
    box-shadow:0 24px 60px rgba(26,26,46,0.3);
    animation:popUp .25s cubic-bezier(.34,1.56,.64,1);
  }

  @keyframes popUp {
    from{opacity:0;transform:scale(.88) translateY(20px);}
    to  {opacity:1;transform:scale(1) translateY(0);}
  }

  .modal-icon {
    width:60px; height:60px; background:#FEF2F2; border-radius:50%;
    display:flex; align-items:center; justify-content:center;
    font-size:1.6rem; margin:0 auto 16px;
  }

  .modal-box h5 {
    font-family:'Syne',sans-serif; font-size:1.2rem; font-weight:800;
    text-align:center; color:var(--dark); margin-bottom:8px;
  }

  .modal-box p {
    text-align:center; color:var(--muted);
    font-size:0.9rem; margin-bottom:24px;
  }

  .modal-box p strong { color:var(--text); }

  .modal-actions { display:flex; gap:12px; }

  .modal-actions a,
  .modal-actions button {
    flex:1; padding:11px; border-radius:10px;
    font-family:'Syne',sans-serif; font-weight:700; font-size:0.9rem;
    text-align:center; cursor:pointer; border:none; text-decoration:none;
    transition:opacity .15s, transform .15s;
  }

  .modal-actions a:hover,
  .modal-actions button:hover { opacity:.88; transform:translateY(-1px); }

  .btn-cancel  { background:var(--border); color:var(--text); }
  .btn-confirm { background:var(--red); color:#fff; box-shadow:0 4px 12px rgba(239,68,68,.35); }

  /* ── View Drawer ── */
  .drawer-overlay {
    display:none; position:fixed; inset:0;
    background:rgba(26,26,46,0.45); backdrop-filter:blur(4px);
    z-index:999; animation:fadeIn .2s ease;
  }

  .drawer-overlay.show { display:block; }

  .drawer {
    position:fixed; top:0; right:-490px;
    width:470px; max-width:95vw; height:100vh;
    background:var(--surface);
    box-shadow:-12px 0 48px rgba(26,26,46,0.2);
    z-index:1000; overflow-y:auto;
    transition:right .35s cubic-bezier(.4,0,.2,1);
    padding:32px 28px;
  }

  .drawer.open { right:0; }

  .drawer-header {
    display:flex; align-items:center; justify-content:space-between;
    margin-bottom:28px;
  }

  .drawer-title {
    font-family:'Syne',sans-serif; font-size:1.15rem;
    font-weight:800; color:var(--dark);
  }

  .drawer-close {
    width:36px; height:36px; border-radius:50%;
    background:var(--border); border:none; cursor:pointer;
    font-size:1.1rem; display:flex; align-items:center; justify-content:center;
    transition:background .15s; color:var(--text);
  }

  .drawer-close:hover { background:#DDDDF0; }

  .drawer-section { margin-bottom:24px; }

  .drawer-section-title {
    font-family:'Syne',sans-serif; font-size:0.72rem; font-weight:700;
    color:var(--muted); text-transform:uppercase; letter-spacing:.1em;
    margin-bottom:10px; padding-bottom:6px; border-bottom:1px solid var(--border);
  }

  .detail-grid { display:grid; grid-template-columns:1fr 1fr; gap:12px; }

  .detail-item label {
    display:block; font-size:0.73rem; color:var(--muted);
    font-weight:500; margin-bottom:3px;
    text-transform:uppercase; letter-spacing:.04em;
  }

  .detail-item span { font-size:0.92rem; color:var(--text); font-weight:500; }
  .detail-item.full { grid-column:1/-1; }

  .officials-table { width:100%; border-collapse:collapse; font-size:0.85rem; }

  .officials-table thead th {
    background:#F6F6FB; color:var(--muted);
    font-size:0.72rem; text-transform:uppercase; letter-spacing:.06em;
    padding:8px 12px; text-align:left; font-weight:600;
  }

  .officials-table tbody td {
    padding:10px 12px; border-bottom:1px solid var(--border); color:var(--text);
  }

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

  .pos-chip {
    display:inline-block; padding:3px 9px; border-radius:50px;
    font-size:0.72rem; font-weight:700; font-family:'Syne',sans-serif;
  }

  .pos-chairman  { background:var(--orange-light); color:var(--orange); }
  .pos-secretary { background:#EFF6FF; color:var(--blue); }
  .pos-treasurer { background:#ECFDF5; color:var(--green); }
  .pos-other     { background:#F0F0FA; color:var(--mid); }

  .countdown-bar { height:6px; background:var(--border); border-radius:3px; overflow:hidden; margin-top:6px; }
  .countdown-fill { height:100%; border-radius:3px; transition:width .6s ease; }
  .fill-green  { background:var(--green); }
  .fill-orange { background:var(--orange); }
  .fill-red    { background:var(--red); }

  .pagination-wrap {
    display:flex; align-items:center; justify-content:space-between;
    padding:16px 20px; border-top:1px solid var(--border);
    font-size:0.85rem; color:var(--muted); flex-wrap:wrap; gap:10px;
  }

  .pagination-wrap strong { color:var(--text); }

  @media (max-width:600px) {
    .page-title { font-size:1.35rem; }
    .stat-card  { padding:12px 14px; }
    .drawer     { width:100vw; }
  }
</style>

<!-- ── Delete Modal ── -->
<div class="modal-overlay" id="deleteModal">
  <div class="modal-box">
    <div class="modal-icon">🗑️</div>
    <h5>Delete Association?</h5>
    <p>You're about to permanently delete <strong id="modalAssocName">this association</strong> and all its officials. This cannot be undone.</p>
    <div class="modal-actions">
      <button class="btn-cancel" onclick="closeDeleteModal()">Cancel</button>
      <a href="#" id="confirmDeleteBtn" class="btn-confirm">Yes, Delete</a>
    </div>
  </div>
</div>

<!-- ── View Drawer ── -->
<div class="drawer-overlay" id="drawerOverlay" onclick="closeDrawer()"></div>
<div class="drawer" id="viewDrawer">
  <div class="drawer-header">
    <span class="drawer-title">Association Details</span>
    <button class="drawer-close" onclick="closeDrawer()">✕</button>
  </div>
  <div id="drawerContent">
    <p style="color:var(--muted);text-align:center;padding:40px 0;">Loading…</p>
  </div>
</div>

<!-- ── Alerts ── -->
<?php if (isset($_GET['msg'])): ?>
  <?php if ($_GET['msg'] === 'deleted'): ?>
    <div class="alert-custom alert-success">✅ Association deleted successfully.</div>
  <?php elseif ($_GET['msg'] === 'updated'): ?>
    <div class="alert-custom alert-success">✅ Association updated successfully.</div>
  <?php endif; ?>
<?php endif; ?>

<!-- ── Page Header ── -->
<div class="page-header">
  <h2 class="page-title">Registered <span>Associations</span></h2>
  <a href="add_ass.php" class="btn-add">
    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
      <path d="M12 5v14M5 12h14"/>
    </svg>
    Add Association
  </a>
</div>

<!-- ── Stats ── -->
<?php
$all_q    = mysqli_query($conn, "SELECT date_of_renewal FROM associations");
$t_all    = mysqli_num_rows($all_q);
$active   = $expiring = $expired = 0;
while ($r = mysqli_fetch_assoc($all_q)) {
    $d = (strtotime($r['date_of_renewal']) - time()) / 86400;
    if ($d < 0)       $expired++;
    elseif ($d <= 30) $expiring++;
    else              $active++;
}
?>
<div class="stats-strip">
  <div class="stat-card">
    <div class="stat-icon orange">🏢</div>
    <div class="stat-info"><p>Total</p><h4><?= $t_all ?></h4></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon green">✅</div>
    <div class="stat-info"><p>Active</p><h4><?= $active ?></h4></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon orange">⚠️</div>
    <div class="stat-info"><p>Expiring Soon</p><h4><?= $expiring ?></h4></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon red">❌</div>
    <div class="stat-info"><p>Expired</p><h4><?= $expired ?></h4></div>
  </div>
</div>

<!-- ── Toolbar ── -->
<div class="toolbar">
  <form method="GET" style="flex:1;display:flex;gap:12px;flex-wrap:wrap;align-items:center;">
    <div class="search-box">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
      </svg>
      <input type="text" name="search"
             placeholder="Search by name or location…"
             value="<?= htmlspecialchars($search) ?>">
    </div>
    <button type="submit" class="btn-add" style="padding:10px 18px;font-size:.82rem;">Search</button>
    <?php if ($search): ?>
      <a href="view_associations.php" class="btn-add"
         style="background:#6B7280;padding:10px 18px;font-size:.82rem;box-shadow:none;">Clear</a>
    <?php endif; ?>
  </form>
  <div class="results-label">
    Showing <strong><?= $total ?></strong> result<?= $total != 1 ? 's' : '' ?>
    <?= $search ? ' for "<strong>'.htmlspecialchars($search).'</strong>"' : '' ?>
  </div>
</div>

<!-- ── Table ── -->
<div class="table-card">
  <div class="table-responsive">
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>Association Name</th>
          <th>Location</th>
          <th>Reg. Date</th>
          
          <th>Renewal Date</th>
          <th>Status</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($total === 0): ?>
          <tr>
            <td colspan="7">
              <div class="empty-state">
                <div class="empty-icon">🏢</div>
                <h5><?= $search ? 'No results found' : 'No associations yet' ?></h5>
                <p><?= $search ? 'Try a different search term.' : 'Click "Add Association" to register the first one.' ?></p>
              </div>
            </td>
          </tr>
        <?php else: ?>
          <?php $sn = 1; while ($row = mysqli_fetch_assoc($result)): ?>
            <?php
              $diff = (strtotime($row['date_of_renewal']) - time()) / 86400;
              if      ($diff < 0)   { $status = 'Expired';       $badge = 'badge-expired'; }
              elseif  ($diff <= 30) { $status = 'Expiring Soon'; $badge = 'badge-expiring'; }
              else                  { $status = 'Active';        $badge = 'badge-active'; }

              $regTs   = strtotime($row['date_of_registration']);
              $renTs   = strtotime($row['date_of_renewal']);
              $pct     = $renTs > $regTs
                         ? min(100, max(0, round((time() - $regTs) / ($renTs - $regTs) * 100)))
                         : 0;
            ?>
            <tr data-id="<?= $row['id'] ?>"
                data-name="<?= htmlspecialchars($row['association_name'], ENT_QUOTES) ?>"
                data-location="<?= htmlspecialchars($row['location'], ENT_QUOTES) ?>"
                data-reg="<?= $row['date_of_registration'] ?>"
                data-renewal="<?= $row['date_of_renewal'] ?>"
                data-status="<?= $status ?>"
                data-pct="<?= $pct ?>">

              <td><span class="sn-badge"><?= $sn++ ?></span></td>

              <td>
                <div class="assoc-name"><?= htmlspecialchars($row['association_name']) ?></div>
              </td>

              <td>
                <span class="location-pill">
                  📍 <?= htmlspecialchars($row['location']) ?>
                </span>
              </td>

              <td>
                <span class="date-text">
                  <?= $row['date_of_registration'] ? date('d M Y', strtotime($row['date_of_registration'])) : '—' ?>
                </span>
              </td>

              <td>
                <span class="date-text">
                  <?= $row['date_of_renewal'] ? date('d M Y', strtotime($row['date_of_renewal'])) : '—' ?>
                </span>
              </td>

              <td><span class="badge-status <?= $badge ?>"><?= $status ?></span></td>

              <td>
                <div class="actions">

                  <!-- View -->
                  <button class="btn-action btn-view" title="View Details"
                          onclick="openDrawer(<?= $row['id'] ?>, this.closest('tr'))">
                    <svg width="15" height="15" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24">
                      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                      <circle cx="12" cy="12" r="3"/>
                    </svg>
                  </button>

                  <!-- Edit -->
                  <a href="edit_ass.php?id=<?= $row['id'] ?>" class="btn-action btn-edit" title="Edit">
                    <svg width="15" height="15" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24">
                      <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                      <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                    </svg>
                  </a>

                  <!-- Delete -->
                  <button class="btn-action btn-delete" title="Delete"
                          onclick="confirmDelete(<?= $row['id'] ?>, '<?= addslashes(htmlspecialchars($row['association_name'])) ?>')">
                    <svg width="15" height="15" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24">
                      <polyline points="3 6 5 6 21 6"/>
                      <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>
                      <path d="M10 11v6M14 11v6"/>
                      <path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/>
                    </svg>
                  </button>

                </div>
              </td>
            </tr>
          <?php endwhile; ?>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

  <?php if ($total > 0): ?>
  <div class="pagination-wrap">
    <span>Showing <strong><?= $total ?></strong> association<?= $total != 1 ? 's' : '' ?></span>
    <span style="color:var(--orange);font-family:'Syne',sans-serif;font-weight:700;font-size:.82rem;">
      <?= date('d M Y, H:i') ?>
    </span>
  </div>
  <?php endif; ?>
</div>

<!-- ── Scripts ── -->
<script>
// Delete Modal
function confirmDelete(id, name) {
  document.getElementById('modalAssocName').textContent = name;
  document.getElementById('confirmDeleteBtn').href = 'view_associations.php?delete=' + id;
  document.getElementById('deleteModal').classList.add('show');
}

function closeDeleteModal() {
  document.getElementById('deleteModal').classList.remove('show');
}

document.getElementById('deleteModal').addEventListener('click', function(e) {
  if (e.target === this) closeDeleteModal();
});

// View Drawer
function openDrawer(id, row) {
  const name     = row.dataset.name;
  const location = row.dataset.location;
  const reg      = row.dataset.reg;
  const renewal  = row.dataset.renewal;
  const status   = row.dataset.status;
  const pct      = parseInt(row.dataset.pct) || 0;

  const badgeClass = status === 'Active'        ? 'badge-active'   :
                     status === 'Expiring Soon' ? 'badge-expiring' : 'badge-expired';

  const diff    = Math.round((new Date(renewal) - Date.now()) / 86400000);
  const diffTxt = diff < 0   ? Math.abs(diff) + ' days overdue' :
                  diff === 0 ? 'Expires today'                   :
                               diff + ' days remaining';

  const fillClass = diff < 0 ? 'fill-red' : diff <= 30 ? 'fill-orange' : 'fill-green';

  const fmt = d => d ? new Date(d).toLocaleDateString('en-GB',
                       { day:'2-digit', month:'short', year:'numeric' }) : '—';

  document.getElementById('drawerContent').innerHTML = `
    <div class="drawer-section">
      <div class="drawer-section-title">Basic Information</div>
      <div class="detail-grid">
        <div class="detail-item full">
          <label>Association Name</label>
          <span style="font-family:'Syne',sans-serif;font-weight:700;font-size:1rem;">${name}</span>
        </div>
        <div class="detail-item">
          <label>Location</label>
          <span>📍 ${location}</span>
        </div>
        <div class="detail-item">
          <label>Status</label>
          <span class="badge-status ${badgeClass}">${status}</span>
        </div>
        <div class="detail-item">
          <label>Registration Date</label>
          <span>${fmt(reg)}</span>
        </div>
        <div class="detail-item">
          <label>Renewal Date</label>
          <span>${fmt(renewal)}</span>
        </div>
      </div>
    </div>

    <div class="drawer-section">
      <div class="drawer-section-title">Renewal Progress</div>
      <div style="display:flex;justify-content:space-between;font-size:.82rem;color:var(--muted);margin-bottom:4px;">
        <span>${fmt(reg)}</span>
        <span style="font-weight:600;color:${diff<0?'var(--red)':diff<=30?'var(--orange)':'var(--green)'};">${diffTxt}</span>
        <span>${fmt(renewal)}</span>
      </div>
      <div class="countdown-bar">
        <div class="countdown-fill ${fillClass}" style="width:${pct}%"></div>
      </div>
    </div>

    <div class="drawer-section">
      <div class="drawer-section-title">Officials</div>
      <div id="officialsArea">
        <p style="color:var(--muted);font-size:.85rem;text-align:center;padding:16px 0;">Loading officials…</p>
      </div>
    </div>

    <div style="display:flex;gap:10px;margin-top:8px;">
      <a href="edit_ass.php?id=${id}" class="btn-add" style="flex:1;text-align:center;padding:11px;">
        ✏️ Edit
      </a>
      <button onclick="closeDrawer();confirmDelete(${id},\`${name.replace(/`/g,'\\`')}\`);"
              class="btn-add"
              style="flex:1;background:#EF4444;box-shadow:0 4px 14px rgba(239,68,68,.3);">
        🗑️ Delete
      </button>
    </div>
  `;

  document.getElementById('drawerOverlay').classList.add('show');
  document.getElementById('viewDrawer').classList.add('open');

  // Fetch officials
  fetch('get_officials.php?association_id=' + id)
    .then(r => r.json())
    .then(data => {
      const area = document.getElementById('officialsArea');
      if (!data || !data.length) {
        area.innerHTML = '<p style="color:var(--muted);font-size:.85rem;text-align:center;padding:16px 0;">No officials recorded.</p>';
        return;
      }
      const posClass = p => {
        p = (p || '').toLowerCase();
        return p === 'chairman'  ? 'pos-chairman'  :
               p === 'secretary' ? 'pos-secretary' :
               p === 'treasurer' ? 'pos-treasurer' : 'pos-other';
      };
      area.innerHTML = `
        <table class="officials-table">
          <thead><tr><th>Name</th><th>Position</th><th>Phone</th></tr></thead>
          <tbody>
            ${data.map(o => `
              <tr>
                <td>${o.full_name}</td>
                <td><span class="pos-chip ${posClass(o.position)}">${o.position}</span></td>
                <td>${o.phone || '—'}</td>
              </tr>`).join('')}
          </tbody>
        </table>`;
    })
    .catch(() => {
      const area = document.getElementById('officialsArea');
      if (area) area.innerHTML =
        '<p style="color:var(--red);font-size:.85rem;text-align:center;padding:16px 0;">Could not load officials.</p>';
    });
}

function closeDrawer() {
  document.getElementById('drawerOverlay').classList.remove('show');
  document.getElementById('viewDrawer').classList.remove('open');
}

document.addEventListener('keydown', e => {
  if (e.key === 'Escape') { closeDrawer(); closeDeleteModal(); }
});
</script>

<?php include 'includes/footer.php'; ?>