<?php
// ══════════════════════════════════════════════════════════════
//  ALL LOGIC FIRST — before any HTML / includes
// ══════════════════════════════════════════════════════════════
require 'includes/db_connect.php';

// ── Ensure renewal_history table exists (runs once, harmless after that) ──
$conn->query("CREATE TABLE IF NOT EXISTS renewal_history (
    id              INT AUTO_INCREMENT PRIMARY KEY,
    association_id  INT NOT NULL,
    old_renewal     DATE,
    new_renewal     DATE NOT NULL,
    payment_amount  DECIMAL(10,2),
    payment_method  VARCHAR(50),
    receipt_number  VARCHAR(100),
    notes           TEXT,
    renewed_by      VARCHAR(150),
    renewed_at      DATETIME DEFAULT NOW()
)");

$success_msg = '';
$error_msg   = '';

// ── Handle Renew (POST) ────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'renew') {

    $assoc_id        = (int) $_POST['assoc_id'];
    $new_renewal     = mysqli_real_escape_string($conn, $_POST['new_renewal_date']);
    $payment_amount  = mysqli_real_escape_string($conn, trim($_POST['payment_amount']));
    $payment_method  = mysqli_real_escape_string($conn, $_POST['payment_method']);
    $receipt_number  = mysqli_real_escape_string($conn, trim($_POST['receipt_number']));
    $notes           = mysqli_real_escape_string($conn, trim($_POST['notes']));
    $renewed_by      = mysqli_real_escape_string($conn, trim($_POST['renewed_by']));

    // Fetch current renewal date for history
    $cur = mysqli_fetch_assoc(mysqli_query($conn, "SELECT date_of_renewal FROM associations WHERE id = $assoc_id"));
    $old_renewal = $cur['date_of_renewal'];

    // Update association renewal date
    $upd = "UPDATE associations SET date_of_renewal = '$new_renewal' WHERE id = $assoc_id";

    if ($conn->query($upd)) {

        // Insert into renewal history
        $ins = "INSERT INTO renewal_history
                    (association_id, old_renewal, new_renewal, payment_amount, payment_method, receipt_number, notes, renewed_by)
                VALUES
                    ($assoc_id, '$old_renewal', '$new_renewal', '$payment_amount', '$payment_method', '$receipt_number', '$notes', '$renewed_by')";
        $conn->query($ins);

        $success_msg = "Association renewed successfully until " . date('d M Y', strtotime($new_renewal)) . ".";
    } else {
        $error_msg = "Error: " . $conn->error;
    }
}

// ── Handle Quick Renew (one-click +1 year) ────────────────────
if (isset($_GET['quick_renew']) && is_numeric($_GET['quick_renew'])) {
    $qid  = (int) $_GET['quick_renew'];
    $crow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT date_of_renewal FROM associations WHERE id = $qid"));
    if ($crow) {
        $base        = strtotime($crow['date_of_renewal']) > time()
                       ? $crow['date_of_renewal']
                       : date('Y-m-d');
        $new_date    = date('Y-m-d', strtotime('+1 year', strtotime($base)));
        $old_renewal = $crow['date_of_renewal'];

        $conn->query("UPDATE associations SET date_of_renewal = '$new_date' WHERE id = $qid");

        $conn->query("INSERT INTO renewal_history
                        (association_id, old_renewal, new_renewal, payment_method, renewed_by)
                      VALUES ($qid, '$old_renewal', '$new_date', 'Quick Renewal', 'System')");

        header("Location: renewals.php?msg=quick_ok&id=$qid");
        exit;
    }
}

// ── Stats ──────────────────────────────────────────────────────
$today_str = date('Y-m-d');

$total_res    = mysqli_query($conn, "SELECT COUNT(*) c FROM associations");
$total_count  = mysqli_fetch_assoc($total_res)['c'];

$active_res   = mysqli_query($conn, "SELECT COUNT(*) c FROM associations WHERE date_of_renewal > DATE_ADD('$today_str', INTERVAL 30 DAY)");
$active_count = mysqli_fetch_assoc($active_res)['c'];

$due_res      = mysqli_query($conn, "SELECT COUNT(*) c FROM associations WHERE date_of_renewal BETWEEN '$today_str' AND DATE_ADD('$today_str', INTERVAL 30 DAY)");
$due_count    = mysqli_fetch_assoc($due_res)['c'];

$expired_res  = mysqli_query($conn, "SELECT COUNT(*) c FROM associations WHERE date_of_renewal < '$today_str'");
$expired_count= mysqli_fetch_assoc($expired_res)['c'];

// ── Filters ────────────────────────────────────────────────────
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, trim($_GET['search'])) : '';

$where = "WHERE 1=1";
if (!empty($search)) $where .= " AND (a.association_name LIKE '%$search%' OR a.location LIKE '%$search%')";
if ($filter === 'active')  $where .= " AND a.date_of_renewal > DATE_ADD('$today_str', INTERVAL 30 DAY)";
if ($filter === 'due')     $where .= " AND a.date_of_renewal BETWEEN '$today_str' AND DATE_ADD('$today_str', INTERVAL 30 DAY)";
if ($filter === 'expired') $where .= " AND a.date_of_renewal < '$today_str'";

// ── Pagination ─────────────────────────────────────────────────
$per_page   = 12;
$page       = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset     = ($page - 1) * $per_page;

$cnt_row    = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) c FROM associations a $where"));
$total_rows = $cnt_row['c'];
$total_pages= ceil($total_rows / $per_page);

$sql = "SELECT a.*,
               DATEDIFF(a.date_of_renewal, '$today_str') AS days_left,
               (SELECT COUNT(*) FROM officials o WHERE o.association_id = a.id) AS official_count,
               (SELECT renewed_at FROM renewal_history rh WHERE rh.association_id = a.id ORDER BY rh.id DESC LIMIT 1) AS last_renewed
        FROM associations a
        $where
        ORDER BY a.date_of_renewal ASC
        LIMIT $per_page OFFSET $offset";

$result = mysqli_query($conn, $sql);

// Helper
function buildQ($params) {
    $q = $_GET; unset($q['quick_renew'], $q['msg']);
    foreach ($params as $k => $v) $q[$k] = $v;
    return '?' . http_build_query($q);
}

// ── HTML starts ────────────────────────────────────────────────
include 'includes/header.php';
include 'includes/sidebar.php';
?>

<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Sans:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">

<style>
  :root {
    --orange:      #E85D04;
    --orange-lt:   #FF6B1A;
    --orange-pale: #FFF0E6;
    --orange-glow: rgba(232,93,4,0.13);
    --dark:        #1A1A2E;
    --mid:         #2A2A4A;
    --surface:     #FFFFFF;
    --bg:          #F4F4FA;
    --border:      #E4E4F0;
    --muted:       #8888AA;
    --green:       #22C55E;
    --green-pale:  #DCFCE7;
    --red:         #EF4444;
    --red-pale:    #FEE2E2;
    --amber:       #F59E0B;
    --amber-pale:  #FEF3C7;
    --blue:        #3B82F6;
    --blue-pale:   #DBEAFE;
    --radius:      13px;
    --shadow:      0 2px 12px rgba(26,26,46,0.07);
    --shadow-md:   0 8px 30px rgba(26,26,46,0.11);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { font-family: 'DM Sans', sans-serif; background: var(--bg); color: var(--dark); }

  /* ── Breadcrumb ── */
  .bc { display:flex; align-items:center; gap:7px; font-size:0.8rem; color:var(--muted); margin-bottom:18px; }
  .bc a { color:var(--muted); text-decoration:none; transition:color .15s; }
  .bc a:hover { color:var(--orange); }
  .bc .sep { font-size:0.65rem; }
  .bc .cur { color:var(--orange); font-weight:600; }

  /* ── Page Header ── */
  .ph { display:flex; align-items:flex-start; justify-content:space-between; flex-wrap:wrap; gap:14px; margin-bottom:26px; padding-bottom:18px; border-bottom:2px solid var(--border); }
  .ph h2 { font-family:'Syne',sans-serif; font-size:1.65rem; font-weight:800; color:var(--dark); letter-spacing:-0.4px; }
  .ph h2 span { color:var(--orange); }
  .ph p { font-size:0.83rem; color:var(--muted); margin-top:4px; }

  /* ── Alert ── */
  .alert { border-radius:10px; padding:13px 18px; font-size:0.88rem; display:flex; align-items:center; gap:10px; margin-bottom:20px; }
  .alert-success { background:var(--green-pale); color:#15803D; }
  .alert-danger  { background:var(--red-pale);   color:#B91C1C; }
  .alert-info    { background:var(--blue-pale);   color:#1D4ED8; }

  /* ── Stats ── */
  .stats { display:grid; grid-template-columns:repeat(4,1fr); gap:16px; margin-bottom:24px; }
  @media(max-width:860px){ .stats { grid-template-columns:repeat(2,1fr); } }
  @media(max-width:480px){ .stats { grid-template-columns:1fr; } }

  .stat {
    background:var(--surface);
    border-radius:15px;
    border:1px solid var(--border);
    padding:18px 20px;
    display:flex;
    align-items:center;
    gap:14px;
    box-shadow:var(--shadow);
    cursor:pointer;
    transition:transform .2s, box-shadow .2s, border-color .2s;
    text-decoration:none;
    color:inherit;
  }
  .stat:hover { transform:translateY(-2px); box-shadow:var(--shadow-md); border-color:var(--orange); }
  .stat.active-filter { border-color:var(--orange); box-shadow:0 0 0 3px var(--orange-glow); }

  .stat-ico { width:44px; height:44px; border-radius:12px; display:flex; align-items:center; justify-content:center; font-size:1.1rem; flex-shrink:0; }
  .ico-orange { background:var(--orange-pale); color:var(--orange); }
  .ico-green  { background:var(--green-pale);  color:var(--green); }
  .ico-amber  { background:var(--amber-pale);  color:var(--amber); }
  .ico-red    { background:var(--red-pale);    color:var(--red); }

  .stat-info strong { display:block; font-family:'Syne',sans-serif; font-size:1.55rem; font-weight:800; color:var(--dark); line-height:1; }
  .stat-info span   { font-size:0.76rem; color:var(--muted); font-weight:500; }

  /* ── Filter bar ── */
  .fbar { background:var(--surface); border-radius:14px; padding:14px 18px; margin-bottom:20px; border:1px solid var(--border); display:flex; gap:10px; align-items:center; flex-wrap:wrap; box-shadow:var(--shadow); }
  .srch { position:relative; flex:1; min-width:200px; }
  .srch i { position:absolute; left:12px; top:50%; transform:translateY(-50%); color:var(--muted); font-size:0.82rem; }
  .srch input { width:100%; padding:9px 13px 9px 34px; border:1.5px solid var(--border); border-radius:9px; font-family:'DM Sans',sans-serif; font-size:0.87rem; outline:none; background:#FAFAFA; transition:border-color .2s; }
  .srch input:focus { border-color:var(--orange); background:var(--surface); }
  .fsel { padding:9px 13px; border:1.5px solid var(--border); border-radius:9px; font-family:'DM Sans',sans-serif; font-size:0.87rem; outline:none; background:#FAFAFA; cursor:pointer; min-width:170px; transition:border-color .2s; }
  .fsel:focus { border-color:var(--orange); }
  .fcount { font-size:0.8rem; color:var(--muted); margin-left:auto; white-space:nowrap; }

  /* ── Table card ── */
  .tcard { background:var(--surface); border-radius:16px; border:1px solid var(--border); overflow:hidden; box-shadow:var(--shadow); }
  .tscroll { overflow-x:auto; }

  table { width:100%; border-collapse:collapse; }
  thead { background:linear-gradient(135deg, var(--dark), var(--mid)); }
  thead th { padding:13px 16px; text-align:left; font-family:'Syne',sans-serif; font-size:0.7rem; font-weight:700; color:rgba(255,255,255,.7); text-transform:uppercase; letter-spacing:.8px; white-space:nowrap; }
  tbody tr { border-bottom:1px solid #F0F0F8; transition:background .15s; animation:fadeR .35s ease both; }
  tbody tr:hover { background:#FAFAFE; }
  tbody tr:last-child { border-bottom:none; }
  td { padding:14px 16px; font-size:0.875rem; vertical-align:middle; }

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

  /* ── Association name cell ── */
  .aname { font-family:'Syne',sans-serif; font-weight:700; font-size:0.88rem; color:var(--dark); }
  .aname small { display:block; font-family:'DM Sans',sans-serif; font-weight:400; font-size:0.76rem; color:var(--muted); margin-top:2px; }

  /* ── Pill ── */
  .loc-pill { display:inline-flex; align-items:center; gap:5px; background:#F0F0FA; color:#5555AA; padding:4px 10px; border-radius:20px; font-size:0.76rem; font-weight:500; }

  /* ── Status badge ── */
  .badge { padding:4px 12px; border-radius:20px; font-size:0.73rem; font-weight:700; display:inline-flex; align-items:center; gap:5px; white-space:nowrap; }
  .badge::before { content:''; width:6px; height:6px; border-radius:50%; }
  .b-active  { background:var(--green-pale);  color:#15803D; }   .b-active::before  { background:var(--green); }
  .b-expired { background:var(--red-pale);    color:#B91C1C; }   .b-expired::before { background:var(--red); }
  .b-due     { background:var(--amber-pale);  color:#B45309; }   .b-due::before     { background:var(--amber); }

  /* ── Days countdown ── */
  .days-chip { display:inline-flex; align-items:center; gap:5px; padding:5px 11px; border-radius:20px; font-size:0.78rem; font-weight:700; font-family:'Syne',sans-serif; }
  .days-ok   { background:#F0FDF4; color:#15803D; }
  .days-soon { background:var(--amber-pale); color:#B45309; }
  .days-over { background:var(--red-pale); color:#B91C1C; }

  /* ── Progress bar ── */
  .prog-wrap { width:90px; }
  .prog-bar  { height:5px; border-radius:3px; background:#EEEEF8; overflow:hidden; }
  .prog-fill { height:100%; border-radius:3px; transition:width .4s; }

  /* ── Action buttons ── */
  .acts { display:flex; gap:6px; align-items:center; flex-wrap:nowrap; }
  .btn-act { width:32px; height:32px; border-radius:8px; border:none; cursor:pointer; display:inline-flex; align-items:center; justify-content:center; font-size:0.78rem; transition:all .18s; text-decoration:none; position:relative; }
  .btn-act::after { content:attr(data-tip); position:absolute; bottom:110%; left:50%; transform:translateX(-50%); background:var(--dark); color:#fff; font-size:0.68rem; padding:3px 8px; border-radius:5px; white-space:nowrap; pointer-events:none; opacity:0; transition:opacity .15s; font-family:'DM Sans',sans-serif; }
  .btn-act:hover::after { opacity:1; }
  .btn-renew  { background:var(--orange-pale); color:var(--orange); }
  .btn-quick  { background:var(--green-pale);  color:var(--green); }
  .btn-hist   { background:var(--blue-pale);   color:var(--blue); }
  .btn-renew:hover { background:var(--orange); color:#fff; transform:scale(1.08); }
  .btn-quick:hover { background:var(--green);  color:#fff; transform:scale(1.08); }
  .btn-hist:hover  { background:var(--blue);   color:#fff; transform:scale(1.08); }

  /* ── Empty state ── */
  .empty { text-align:center; padding:55px 20px; }
  .empty i { font-size:2.8rem; color:#D0D0E0; display:block; margin-bottom:12px; }
  .empty p { color:var(--muted); font-size:0.88rem; }

  /* ── Table footer ── */
  .tfoot { display:flex; align-items:center; justify-content:space-between; padding:13px 18px; border-top:1px solid var(--border); background:#FAFAFA; flex-wrap:wrap; gap:10px; }
  .tfoot p { font-size:0.8rem; color:var(--muted); }
  .pagination { display:flex; gap:4px; list-style:none; }
  .pagination li a, .pagination li span { display:inline-flex; align-items:center; justify-content:center; width:31px; height:31px; border-radius:8px; font-size:0.8rem; font-weight:600; text-decoration:none; border:1.5px solid var(--border); color:var(--dark); background:var(--surface); transition:all .15s; }
  .pagination li.active span, .pagination li a:hover { background:var(--orange); color:#fff; border-color:var(--orange); }

  /* ══════════════════════════════════
     MODAL SHARED
  ══════════════════════════════════ */
  .modal-content { border:none; border-radius:16px; overflow:hidden; }

  /* ── Renew Modal ── */
  .rmhdr { background:linear-gradient(135deg,var(--dark),var(--mid)); padding:20px 24px; }
  .rmhdr h5 { font-family:'Syne',sans-serif; font-weight:800; color:#fff; margin:0; font-size:1.05rem; }
  .rmhdr small { color:rgba(255,255,255,.55); font-size:0.78rem; display:block; margin-top:3px; }

  .assoc-banner { background:var(--orange-pale); border-radius:10px; padding:13px 16px; margin-bottom:20px; display:flex; align-items:center; gap:12px; }
  .assoc-banner-icon { width:38px; height:38px; border-radius:10px; background:var(--orange); color:#fff; display:flex; align-items:center; justify-content:center; font-size:0.9rem; flex-shrink:0; }
  .assoc-banner strong { display:block; font-family:'Syne',sans-serif; font-size:0.9rem; font-weight:700; color:var(--dark); }
  .assoc-banner span { font-size:0.76rem; color:var(--muted); }

  .modal-lbl { display:block; font-size:0.74rem; font-weight:600; text-transform:uppercase; letter-spacing:.5px; color:var(--muted); margin-bottom:5px; }
  .modal-lbl .req { color:var(--orange); margin-left:2px; }
  .modal-inp { width:100%; padding:9px 13px; border:1.5px solid var(--border); border-radius:10px; font-family:'DM Sans',sans-serif; font-size:0.87rem; outline:none; background:#FAFAFA; transition:border-color .2s, box-shadow .2s; color:var(--dark); }
  .modal-inp:focus { border-color:var(--orange); background:var(--surface); box-shadow:0 0 0 3px var(--orange-glow); }
  select.modal-inp { cursor:pointer; }

  .modal-row { display:grid; grid-template-columns:1fr 1fr; gap:14px; }
  @media(max-width:500px){ .modal-row { grid-template-columns:1fr; } }

  .mgb { margin-bottom:15px; }

  .btn-renew-submit { background:var(--orange); color:#fff; border:none; padding:11px 26px; border-radius:10px; font-family:'Syne',sans-serif; font-weight:700; font-size:0.9rem; cursor:pointer; display:inline-flex; align-items:center; gap:8px; transition:background .2s,transform .15s,box-shadow .2s; }
  .btn-renew-submit:hover { background:var(--orange-lt); transform:translateY(-1px); box-shadow:0 6px 20px rgba(232,93,4,.3); }

  .btn-cancel-modal { background:transparent; color:var(--muted); border:1.5px solid var(--border); padding:10px 20px; border-radius:10px; font-family:'Syne',sans-serif; font-weight:600; font-size:0.87rem; cursor:pointer; transition:all .15s; }
  .btn-cancel-modal:hover { border-color:var(--muted); color:var(--dark); background:#F0F0F8; }

  /* year-picker highlight */
  .year-chips { display:flex; gap:8px; flex-wrap:wrap; margin-top:8px; }
  .year-chip { padding:5px 13px; border-radius:20px; border:1.5px solid var(--border); background:#FAFAFA; font-size:0.78rem; font-weight:600; cursor:pointer; transition:all .15s; font-family:'Syne',sans-serif; }
  .year-chip:hover, .year-chip.sel { background:var(--orange); color:#fff; border-color:var(--orange); }

  /* ── History Modal ── */
  .hist-row { display:flex; gap:14px; padding:13px 0; border-bottom:1px solid #F0F0F8; align-items:flex-start; }
  .hist-row:last-child { border-bottom:none; }
  .hist-dot { width:32px; height:32px; border-radius:50%; background:var(--orange-pale); color:var(--orange); display:flex; align-items:center; justify-content:center; font-size:0.78rem; flex-shrink:0; margin-top:2px; }
  .hist-info strong { font-family:'Syne',sans-serif; font-size:0.84rem; font-weight:700; color:var(--dark); display:block; }
  .hist-info span   { font-size:0.76rem; color:var(--muted); }
  .hist-info .hist-meta { display:flex; gap:10px; flex-wrap:wrap; margin-top:5px; }
  .hist-tag { background:#F0F0FA; color:#5555AA; padding:2px 9px; border-radius:20px; font-size:0.72rem; font-weight:600; }
  .no-hist { text-align:center; padding:30px; color:var(--muted); font-size:0.85rem; }
  .no-hist i { font-size:1.6rem; display:block; margin-bottom:8px; opacity:.4; }

  /* ── Overdue highlight row ── */
  .row-overdue { background:#FFF8F8 !important; }
  .row-due     { background:#FFFDF5 !important; }
</style>

<!-- ── Breadcrumb ── -->
<div class="bc">
  <a href="dashboard.php"><i class="fa fa-home"></i></a>
  <span class="sep"><i class="fa fa-chevron-right"></i></span>
  <a href="view_associations.php">Associations</a>
  <span class="sep"><i class="fa fa-chevron-right"></i></span>
  <span class="cur">Renewals</span>
</div>

<!-- ── Page Header ── -->
<div class="ph">
  <div>
    <h2>Association <span>Renewals</span></h2>
    <p>Track, manage and process yearly renewal of registered associations</p>
  </div>
  <a href="view_associations.php" style="background:transparent; color:var(--muted); border:1.5px solid var(--border); padding:9px 18px; border-radius:10px; font-family:'Syne',sans-serif; font-weight:600; font-size:0.85rem; text-decoration:none; display:inline-flex; align-items:center; gap:7px; transition:all .15s;"
     onmouseover="this.style.borderColor='var(--muted)'; this.style.color='var(--dark)';"
     onmouseout="this.style.borderColor='var(--border)'; this.style.color='var(--muted)';">
    <i class="fa fa-arrow-left"></i> Back
  </a>
</div>

<!-- ── Alerts ── -->
<?php if ($success_msg): ?>
  <div class="alert alert-success"><i class="fa fa-check-circle"></i><?= htmlspecialchars($success_msg) ?></div>
<?php endif; ?>
<?php if ($error_msg): ?>
  <div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i><?= htmlspecialchars($error_msg) ?></div>
<?php endif; ?>
<?php if (isset($_GET['msg']) && $_GET['msg'] === 'quick_ok'): ?>
  <div class="alert alert-success"><i class="fa fa-bolt"></i> Quick renewal applied — extended by 1 year.</div>
<?php endif; ?>

<!-- ── Stats ── -->
<div class="stats">
  <a href="<?= buildQ(['filter'=>'all','page'=>1]) ?>" class="stat <?= $filter==='all'?'active-filter':'' ?>" style="text-decoration:none;">
    <div class="stat-ico ico-orange"><i class="fa fa-building"></i></div>
    <div class="stat-info"><strong><?= $total_count ?></strong><span>Total Associations</span></div>
  </a>
  <a href="<?= buildQ(['filter'=>'active','page'=>1]) ?>" class="stat <?= $filter==='active'?'active-filter':'' ?>" style="text-decoration:none;">
    <div class="stat-ico ico-green"><i class="fa fa-check-circle"></i></div>
    <div class="stat-info"><strong><?= $active_count ?></strong><span>Active (30+ days)</span></div>
  </a>
  <a href="<?= buildQ(['filter'=>'due','page'=>1]) ?>" class="stat <?= $filter==='due'?'active-filter':'' ?>" style="text-decoration:none;">
    <div class="stat-ico ico-amber"><i class="fa fa-clock"></i></div>
    <div class="stat-info"><strong><?= $due_count ?></strong><span>Due Soon (≤30 days)</span></div>
  </a>
  <a href="<?= buildQ(['filter'=>'expired','page'=>1]) ?>" class="stat <?= $filter==='expired'?'active-filter':'' ?>" style="text-decoration:none;">
    <div class="stat-ico ico-red"><i class="fa fa-times-circle"></i></div>
    <div class="stat-info"><strong><?= $expired_count ?></strong><span>Expired</span></div>
  </a>
</div>

<!-- ── Filter bar ── -->
<form method="GET" class="fbar" id="filterForm">
  <div class="srch">
    <i class="fa fa-search"></i>
    <input type="text" name="search" placeholder="Search association or location…"
           value="<?= htmlspecialchars($search) ?>"
           oninput="this.form.submit()">
  </div>
  <select name="filter" class="fsel" onchange="this.form.submit()">
    <option value="all"     <?= $filter==='all'    ?'selected':'' ?>>All Status</option>
    <option value="active"  <?= $filter==='active' ?'selected':'' ?>>Active</option>
    <option value="due"     <?= $filter==='due'    ?'selected':'' ?>>Due Soon</option>
    <option value="expired" <?= $filter==='expired'?'selected':'' ?>>Expired</option>
  </select>
  <span class="fcount"><?= $total_rows ?> association<?= $total_rows!=1?'s':'' ?></span>
  <input type="hidden" name="page" value="1">
</form>

<!-- ── Table ── -->
<div class="tcard">
  <div class="tscroll">
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>Association</th>
          <th>Location</th>
          <th>Last Renewed</th>
          <th>Renewal Date</th>
          <th>Days Left</th>
          <th>Status</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>

      <?php if (!$result || mysqli_num_rows($result) === 0): ?>
        <tr><td colspan="8"><div class="empty">
          <i class="fa fa-calendar-times"></i>
          <p>No associations found<?= $search ? " for \"<strong>$search</strong>\"" : '' ?>.</p>
        </div></td></tr>

      <?php else:
        $sn = $offset + 1;
        while ($row = mysqli_fetch_assoc($result)):
          $dl = (int) $row['days_left'];
          if ($dl < 0)       { $status='expired'; $slabel='Expired';    $row_class='row-overdue'; }
          elseif ($dl <= 30) { $status='due';     $slabel='Due Soon';   $row_class='row-due'; }
          else               { $status='active';  $slabel='Active';     $row_class=''; }

          // Progress (0–365 days)
          $prog_pct = min(100, max(0, round($dl / 365 * 100)));
          $prog_clr = $dl < 0 ? '#EF4444' : ($dl <= 30 ? '#F59E0B' : '#22C55E');
      ?>
        <tr class="<?= $row_class ?>">
          <td style="font-family:'Syne',sans-serif; font-weight:700; font-size:0.78rem; color:var(--muted);"><?= $sn++ ?></td>

          <td>
            <div class="aname">
              <?= htmlspecialchars($row['association_name']) ?>
              <small><i class="fa fa-users" style="margin-right:4px;"></i><?= $row['official_count'] ?> official<?= $row['official_count']!=1?'s':'' ?></small>
            </div>
          </td>

          <td><span class="loc-pill"><i class="fa fa-map-marker-alt"></i><?= htmlspecialchars($row['location']) ?></span></td>

          <td style="font-size:0.82rem; color:var(--muted);">
            <?= $row['last_renewed'] ? date('d M Y', strtotime($row['last_renewed'])) : '<em>Never</em>' ?>
          </td>

          <td style="font-size:0.83rem; font-weight:600;">
            <?= $row['date_of_renewal'] ? date('d M Y', strtotime($row['date_of_renewal'])) : '—' ?>
          </td>

          <td>
            <?php if ($dl >= 0): ?>
              <div class="prog-wrap">
                <div style="font-family:'Syne',sans-serif; font-size:0.8rem; font-weight:700; color:<?= $prog_clr ?>; margin-bottom:4px;">
                  <?= $dl ?>d
                </div>
                <div class="prog-bar">
                  <div class="prog-fill" style="width:<?= $prog_pct ?>%; background:<?= $prog_clr ?>;"></div>
                </div>
              </div>
            <?php else: ?>
              <span class="days-chip days-over"><i class="fa fa-exclamation-triangle"></i><?= abs($dl) ?>d overdue</span>
            <?php endif; ?>
          </td>

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

          <td>
            <div class="acts">
              <!-- Renew (full form) -->
              <button class="btn-act btn-renew" data-tip="Renew Now"
                      onclick="openRenewModal(<?= $row['id'] ?>, '<?= addslashes(htmlspecialchars($row['association_name'])) ?>', '<?= htmlspecialchars($row['location']) ?>', '<?= htmlspecialchars($row['date_of_renewal']) ?>')">
                <i class="fa fa-redo"></i>
              </button>
              <!-- Quick +1 year -->
              <a class="btn-act btn-quick" data-tip="Quick +1 Year"
                 href="<?= buildQ(['quick_renew'=>$row['id']]) ?>"
                 onclick="return confirm('Extend <?= addslashes(htmlspecialchars($row['association_name'])) ?> by 1 year?')">
                <i class="fa fa-bolt"></i>
              </a>
              <!-- History -->
              <button class="btn-act btn-hist" data-tip="Renewal History"
                      onclick="openHistModal(<?= $row['id'] ?>, '<?= addslashes(htmlspecialchars($row['association_name'])) ?>')">
                <i class="fa fa-history"></i>
              </button>
            </div>
          </td>
        </tr>
      <?php endwhile; endif; ?>

      </tbody>
    </table>
  </div>

  <!-- Table footer -->
  <div class="tfoot">
    <p>Showing <?= min($offset+1,$total_rows) ?>–<?= min($offset+$per_page,$total_rows) ?> of <?= $total_rows ?></p>
    <?php if ($total_pages > 1): ?>
    <ul class="pagination">
      <?php if ($page>1): ?>
        <li><a href="<?= buildQ(['page'=>$page-1]) ?>"><i class="fa fa-chevron-left"></i></a></li>
      <?php endif; ?>
      <?php for($i=max(1,$page-2);$i<=min($total_pages,$page+2);$i++): ?>
        <li class="<?= $i===$page?'active':'' ?>">
          <?= $i===$page?"<span>$i</span>":"<a href='".buildQ(['page'=>$i])."'>$i</a>" ?>
        </li>
      <?php endfor; ?>
      <?php if ($page<$total_pages): ?>
        <li><a href="<?= buildQ(['page'=>$page+1]) ?>"><i class="fa fa-chevron-right"></i></a></li>
      <?php endif; ?>
    </ul>
    <?php endif; ?>
  </div>
</div>


<!-- ══════════════════════════════════════════════════════════
     RENEW MODAL
══════════════════════════════════════════════════════════ -->
<div class="modal fade" id="renewModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="max-width:520px;">
    <div class="modal-content">

      <div class="rmhdr">
        <h5><i class="fa fa-redo" style="color:var(--orange); margin-right:9px;"></i>Renew Association</h5>
        <small>Complete the renewal form below</small>
      </div>

      <form method="POST" id="renewForm">
        <input type="hidden" name="action"   value="renew">
        <input type="hidden" name="assoc_id" id="rAssocId">

        <div style="padding:22px;">

          <!-- Association banner -->
          <div class="assoc-banner" id="rBanner">
            <div class="assoc-banner-icon"><i class="fa fa-building"></i></div>
            <div>
              <strong id="rAssocName">—</strong>
              <span id="rAssocLoc">—</span>
            </div>
          </div>

          <!-- Current & New Date -->
          <div class="modal-row mgb">
            <div>
              <label class="modal-lbl">Current Renewal Date</label>
              <input type="text" class="modal-inp" id="rCurrentDate" readonly
                     style="background:#F5F5FA; color:var(--muted); cursor:default;">
            </div>
            <div>
              <label class="modal-lbl">New Renewal Date <span class="req">*</span></label>
              <input type="date" name="new_renewal_date" id="rNewDate" class="modal-inp" required>
            </div>
          </div>

          <!-- Quick year chips -->
          <div class="mgb">
            <label class="modal-lbl">Quick Select</label>
            <div class="year-chips" id="yearChips"></div>
          </div>

          <!-- Payment -->
          <div class="modal-row mgb">
            <div>
              <label class="modal-lbl">Payment Amount</label>
              <input type="number" name="payment_amount" class="modal-inp" placeholder="e.g. 5000" min="0" step="0.01">
            </div>
            <div>
              <label class="modal-lbl">Payment Method</label>
              <select name="payment_method" class="modal-inp">
                <option value="Cash">Cash</option>
                <option value="Bank Transfer">Bank Transfer</option>
                <option value="POS">POS</option>
                <option value="Cheque">Cheque</option>
                <option value="Quick Renewal">Quick Renewal</option>
              </select>
            </div>
          </div>

          <!-- Receipt & Officer -->
          <div class="modal-row mgb">
            <div>
              <label class="modal-lbl">Receipt / Reference No.</label>
              <input type="text" name="receipt_number" class="modal-inp" placeholder="e.g. RCT-2025-001">
            </div>
            <div>
              <label class="modal-lbl">Renewed By</label>
              <input type="text" name="renewed_by" class="modal-inp" placeholder="Officer name" value="Admin">
            </div>
          </div>

          <!-- Notes -->
          <div class="mgb">
            <label class="modal-lbl">Notes (optional)</label>
            <textarea name="notes" class="modal-inp" rows="2"
                      style="resize:vertical; line-height:1.5;"
                      placeholder="Any additional remarks…"></textarea>
          </div>

        </div>

        <div style="display:flex; align-items:center; justify-content:space-between; padding:15px 22px; background:#FAFAFA; border-top:1px solid var(--border); flex-wrap:wrap; gap:10px;">
          <button type="button" class="btn-cancel-modal" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn-renew-submit">
            <i class="fa fa-save"></i> Save Renewal
          </button>
        </div>

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


<!-- ══════════════════════════════════════════════════════════
     HISTORY MODAL
══════════════════════════════════════════════════════════ -->
<div class="modal fade" id="histModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" style="max-width:500px;">
    <div class="modal-content">

      <div style="background:linear-gradient(135deg,var(--dark),var(--mid)); padding:18px 22px; display:flex; align-items:center; justify-content:space-between;">
        <div>
          <h5 style="font-family:'Syne',sans-serif; font-weight:800; color:#fff; margin:0; font-size:1rem;">
            <i class="fa fa-history" style="color:var(--orange); margin-right:8px;"></i>Renewal History
          </h5>
          <small style="color:rgba(255,255,255,.5); font-size:0.75rem;" id="histAssocName"></small>
        </div>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body" id="histBody" style="padding:20px; max-height:440px; overflow-y:auto;">
        <div style="text-align:center; padding:24px;">
          <i class="fa fa-spinner fa-spin fa-2x" style="color:var(--orange);"></i>
        </div>
      </div>

      <div style="padding:12px 20px; background:#FAFAFA; border-top:1px solid var(--border); text-align:right;">
        <button class="btn-cancel-modal" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>


<!-- ══════════════════════════════════════════════════════════
     INLINE AJAX — history endpoint
══════════════════════════════════════════════════════════ -->
<?php
if (isset($_GET['hist_ajax']) && is_numeric($_GET['hist_ajax'])) {
    $hid  = (int) $_GET['hist_ajax'];
    $hres = mysqli_query($conn,
        "SELECT rh.*, a.association_name
         FROM renewal_history rh
         JOIN associations a ON a.id = rh.association_id
         WHERE rh.association_id = $hid
         ORDER BY rh.id DESC");

    if (mysqli_num_rows($hres) === 0) {
        echo '<div class="no-hist"><i class="fa fa-history"></i>No renewal records found.</div>';
    } else {
        while ($h = mysqli_fetch_assoc($hres)) {
            echo '<div class="hist-row">';
            echo '<div class="hist-dot"><i class="fa fa-redo"></i></div>';
            echo '<div class="hist-info">';
            echo '<strong>Renewed to ' . date('d M Y', strtotime($h['new_renewal'])) . '</strong>';
            echo '<span>From: ' . ($h['old_renewal'] ? date('d M Y', strtotime($h['old_renewal'])) : 'N/A') . '</span>';
            echo '<div class="hist-meta">';
            if ($h['payment_method']) echo '<span class="hist-tag"><i class="fa fa-credit-card" style="margin-right:4px;"></i>' . htmlspecialchars($h['payment_method']) . '</span>';
            if ($h['payment_amount']) echo '<span class="hist-tag">₦' . number_format($h['payment_amount'], 2) . '</span>';
            if ($h['receipt_number']) echo '<span class="hist-tag">Rcpt: ' . htmlspecialchars($h['receipt_number']) . '</span>';
            if ($h['renewed_by'])     echo '<span class="hist-tag"><i class="fa fa-user" style="margin-right:3px;"></i>' . htmlspecialchars($h['renewed_by']) . '</span>';
            echo '</div>';
            echo '<span style="font-size:0.72rem; color:var(--muted); margin-top:4px; display:block;"><i class="fa fa-clock" style="margin-right:3px;"></i>' . date('d M Y, h:ia', strtotime($h['renewed_at'])) . '</span>';
            if (!empty($h['notes'])) echo '<span style="font-size:0.78rem; color:#555; margin-top:3px; display:block; font-style:italic;">"' . htmlspecialchars($h['notes']) . '"</span>';
            echo '</div></div>';
        }
    }
    exit;
}
?>

<script>
// ── Renew Modal ────────────────────────────────────────────────
function openRenewModal(id, name, loc, currentDate) {
    document.getElementById('rAssocId').value    = id;
    document.getElementById('rAssocName').textContent = name;
    document.getElementById('rAssocLoc').textContent  = loc;

    // Show current date nicely
    const cd = currentDate ? new Date(currentDate + 'T00:00:00') : null;
    document.getElementById('rCurrentDate').value = cd
        ? cd.toLocaleDateString('en-GB', {day:'2-digit', month:'short', year:'numeric'})
        : 'Not set';

    // Default new date = current renewal + 1 year (or today + 1 year if expired)
    const base = (cd && cd > new Date()) ? cd : new Date();
    const next = new Date(base);
    next.setFullYear(next.getFullYear() + 1);
    document.getElementById('rNewDate').value = next.toISOString().split('T')[0];

    // Build quick-year chips
    buildYearChips(next);

    // Reset form fields
    document.getElementById('renewForm').querySelectorAll('input:not([type=hidden]):not([name=renewed_by])').forEach(i => {
        if (i.name !== 'new_renewal_date') i.value = '';
    });
    document.querySelector('[name=notes]').value = '';
    document.querySelector('[name=payment_method]').selectedIndex = 0;

    new bootstrap.Modal(document.getElementById('renewModal')).show();
}

function buildYearChips(defaultDate) {
    const wrap = document.getElementById('yearChips');
    wrap.innerHTML = '';
    const base = new Date();

    [1, 2, 3].forEach(y => {
        const d = new Date(base);
        d.setFullYear(d.getFullYear() + y);
        const val = d.toISOString().split('T')[0];
        const chip = document.createElement('button');
        chip.type      = 'button';
        chip.className = 'year-chip';
        chip.textContent = '+' + y + ' Year' + (y > 1 ? 's' : '') + ' (' + d.getFullYear() + ')';
        if (defaultDate && val === defaultDate.toISOString().split('T')[0]) chip.classList.add('sel');
        chip.onclick = function () {
            document.getElementById('rNewDate').value = val;
            wrap.querySelectorAll('.year-chip').forEach(c => c.classList.remove('sel'));
            chip.classList.add('sel');
        };
        wrap.appendChild(chip);
    });

    // Sync chips when date input changes manually
    document.getElementById('rNewDate').addEventListener('change', function () {
        wrap.querySelectorAll('.year-chip').forEach(c => c.classList.remove('sel'));
    });
}

// ── History Modal ──────────────────────────────────────────────
function openHistModal(id, name) {
    document.getElementById('histAssocName').textContent = name;
    document.getElementById('histBody').innerHTML =
        '<div style="text-align:center;padding:24px;"><i class="fa fa-spinner fa-spin fa-2x" style="color:var(--orange);"></i></div>';

    new bootstrap.Modal(document.getElementById('histModal')).show();

    fetch('?hist_ajax=' + id)
        .then(r => r.text())
        .then(html => { document.getElementById('histBody').innerHTML = html; })
        .catch(() => { document.getElementById('histBody').innerHTML = '<div class="no-hist"><i class="fa fa-exclamation-circle"></i>Failed to load history.</div>'; });
}
</script>

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