
<?php require 'includes/db_connect.php'; ?>
<?php include 'includes/header.php'; ?>
<?php include 'includes/sidebar.php'; ?>
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Sans:ital,wght@0,300;0,400;0,500;1,400&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-light: #FF6B1A;
    --orange-pale:  #FFF0E6;
    --orange-glow:  rgba(232,93,4,0.12);
    --dark:         #1A1A2E;
    --mid:          #2A2A4A;
    --surface:      #FFFFFF;
    --bg:           #F5F5FA;
    --border:       #E4E4F0;
    --border-focus: #E85D04;
    --text:         #1A1A2E;
    --muted:        #8888AA;
    --green:        #22C55E;
    --green-pale:   #DCFCE7;
    --red:          #EF4444;
    --red-pale:     #FEE2E2;
    --blue:         #3B82F6;
    --blue-pale:    #DBEAFE;
    --radius:       12px;
    --shadow:       0 2px 12px rgba(26,26,46,0.07);
    --shadow-md:    0 6px 28px rgba(26,26,46,0.10);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'DM Sans', sans-serif;
    background: var(--bg);
    color: var(--text);
  }

  /* ── Breadcrumb ── */
  .breadcrumb-bar {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 20px;
    font-size: 0.82rem;
    color: var(--muted);
  }

  .breadcrumb-bar a {
    color: var(--muted);
    text-decoration: none;
    transition: color 0.15s;
  }

  .breadcrumb-bar a:hover { color: var(--orange); }
  .breadcrumb-bar .sep { font-size: 0.7rem; }
  .breadcrumb-bar .current { color: var(--orange); font-weight: 600; }

  /* ── Page Header ── */
  .page-header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 16px;
    margin-bottom: 28px;
    padding-bottom: 20px;
    border-bottom: 2px solid var(--border);
  }

  .page-header h2 {
    font-family: 'Syne', sans-serif;
    font-size: 1.65rem;
    font-weight: 800;
    color: var(--dark);
    letter-spacing: -0.4px;
  }

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

  .page-header p {
    margin-top: 4px;
    font-size: 0.84rem;
    color: var(--muted);
  }

  .header-actions { display: flex; gap: 10px; align-items: center; }

  /* ── Alerts ── */
  .alert {
    border-radius: 10px;
    padding: 13px 18px;
    font-size: 0.88rem;
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
    border: none;
  }

  .alert-success { background: var(--green-pale); color: #15803D; }
  .alert-danger  { background: var(--red-pale);   color: #B91C1C; }
  .alert i       { font-size: 1rem; flex-shrink: 0; }

  /* ── Layout Grid ── */
  .edit-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 22px;
    align-items: start;
  }

  @media (max-width: 900px) {
    .edit-grid { grid-template-columns: 1fr; }
  }

  .full-width { grid-column: 1 / -1; }

  /* ── Section Cards ── */
  .section-card {
    background: var(--surface);
    border-radius: 16px;
    border: 1px solid var(--border);
    box-shadow: var(--shadow);
    overflow: hidden;
    transition: box-shadow 0.2s;
  }

  .section-card:hover { box-shadow: var(--shadow-md); }

  .section-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 22px;
    border-bottom: 1px solid var(--border);
    background: linear-gradient(135deg, #FAFAFA 0%, #F5F5FA 100%);
  }

  .section-card-header-left {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .section-icon {
    width: 36px;
    height: 36px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.9rem;
    flex-shrink: 0;
  }

  .section-icon.orange { background: var(--orange-pale); color: var(--orange); }
  .section-icon.blue   { background: var(--blue-pale);   color: var(--blue); }

  .section-card-header h5 {
    font-family: 'Syne', sans-serif;
    font-size: 0.95rem;
    font-weight: 700;
    color: var(--dark);
    margin: 0;
  }

  .section-card-header small {
    display: block;
    font-size: 0.75rem;
    color: var(--muted);
    margin-top: 1px;
  }

  .section-card-body { padding: 22px; }

  /* ── Form Elements ── */
  .form-group {
    margin-bottom: 18px;
  }

  .form-group:last-child { margin-bottom: 0; }

  .form-label {
    display: block;
    font-size: 0.78rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: var(--muted);
    margin-bottom: 6px;
  }

  .form-label .required {
    color: var(--orange);
    margin-left: 2px;
  }

  .form-control {
    width: 100%;
    padding: 10px 14px;
    border: 1.5px solid var(--border);
    border-radius: var(--radius);
    font-family: 'DM Sans', sans-serif;
    font-size: 0.88rem;
    color: var(--text);
    background: #FAFAFA;
    outline: none;
    transition: border-color 0.2s, background 0.2s, box-shadow 0.2s;
  }

  .form-control:focus {
    border-color: var(--border-focus);
    background: var(--surface);
    box-shadow: 0 0 0 3px var(--orange-glow);
  }

  select.form-control { cursor: pointer; }

  .form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 14px;
  }

  @media (max-width: 600px) {
    .form-row { grid-template-columns: 1fr; }
  }

  /* ── Status Badge ── */
  .status-display {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    padding: 6px 14px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
  }

  .status-display::before {
    content: '';
    width: 7px;
    height: 7px;
    border-radius: 50%;
  }

  .status-active  { background: var(--green-pale); color: #15803D; }
  .status-active::before  { background: var(--green); }
  .status-expired { background: var(--red-pale);   color: #B91C1C; }
  .status-expired::before { background: var(--red); }
  .status-soon    { background: #FEF3C7;            color: #B45309; }
  .status-soon::before    { background: #F59E0B; }

  /* ── Officials Table ── */
  .officials-section { margin-top: 0; }

  .officials-table-wrap {
    border-radius: 12px;
    overflow: hidden;
    border: 1.5px solid var(--border);
    margin-bottom: 16px;
  }

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

  .officials-table thead {
    background: linear-gradient(135deg, var(--dark) 0%, var(--mid) 100%);
  }

  .officials-table thead th {
    padding: 11px 14px;
    font-family: 'Syne', sans-serif;
    font-size: 0.7rem;
    font-weight: 700;
    color: rgba(255,255,255,0.7);
    text-transform: uppercase;
    letter-spacing: 0.7px;
    white-space: nowrap;
  }

  .officials-table tbody tr {
    border-bottom: 1px solid #F0F0F8;
    transition: background 0.15s;
  }

  .officials-table tbody tr:last-child { border-bottom: none; }
  .officials-table tbody tr:hover { background: #FAFAFE; }

  .officials-table td {
    padding: 10px 14px;
    vertical-align: middle;
  }

  .official-row-input {
    padding: 8px 11px;
    border: 1.5px solid var(--border);
    border-radius: 9px;
    font-family: 'DM Sans', sans-serif;
    font-size: 0.84rem;
    width: 100%;
    outline: none;
    background: #FAFAFA;
    transition: border-color 0.2s, box-shadow 0.2s;
  }

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

  select.official-row-input { cursor: pointer; }

  /* Row state badges */
  .row-badge {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 0.68rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.3px;
  }

  .row-badge.existing { background: var(--blue-pale);  color: var(--blue); }
  .row-badge.new      { background: var(--green-pale); color: #15803D; }
  .row-badge.deleted  { background: var(--red-pale);   color: var(--red); }

  /* Delete row button */
  .btn-del-row {
    width: 30px;
    height: 30px;
    border-radius: 8px;
    border: none;
    background: var(--red-pale);
    color: var(--red);
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 0.78rem;
    transition: all 0.15s;
    flex-shrink: 0;
  }

  .btn-del-row:hover {
    background: var(--red);
    color: #fff;
    transform: scale(1.05);
  }

  /* Deleted row style */
  .official-deleted {
    opacity: 0.45;
    background: #FFF5F5 !important;
  }

  .official-deleted input,
  .official-deleted select {
    pointer-events: none;
    background: #FFF5F5;
  }

  /* ── Add Official Button ── */
  .btn-add-official {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 9px 18px;
    background: var(--orange-pale);
    color: var(--orange);
    border: 1.5px dashed var(--orange);
    border-radius: var(--radius);
    font-family: 'Syne', sans-serif;
    font-size: 0.82rem;
    font-weight: 700;
    cursor: pointer;
    transition: all 0.2s;
    width: 100%;
    justify-content: center;
  }

  .btn-add-official:hover {
    background: var(--orange);
    color: #fff;
    border-style: solid;
  }

  /* ── Action Buttons ── */
  .form-actions {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 18px 22px;
    background: #FAFAFA;
    border-top: 1px solid var(--border);
    flex-wrap: wrap;
  }

  .btn-save {
    background: var(--orange);
    color: #fff;
    border: none;
    padding: 11px 28px;
    border-radius: var(--radius);
    font-family: 'Syne', sans-serif;
    font-weight: 700;
    font-size: 0.9rem;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: background 0.2s, transform 0.15s, box-shadow 0.2s;
    letter-spacing: 0.2px;
  }

  .btn-save:hover {
    background: var(--orange-light);
    transform: translateY(-1px);
    box-shadow: 0 6px 20px rgba(232,93,4,0.3);
  }

  .btn-save:active { transform: translateY(0); }

  .btn-cancel {
    background: transparent;
    color: var(--muted);
    border: 1.5px solid var(--border);
    padding: 10px 22px;
    border-radius: var(--radius);
    font-family: 'Syne', sans-serif;
    font-weight: 600;
    font-size: 0.88rem;
    cursor: pointer;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.15s;
  }

  .btn-cancel:hover {
    border-color: var(--muted);
    color: var(--dark);
    background: #F0F0F8;
  }

  /* ── Changes summary ── */
  .changes-pill {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 14px;
    background: var(--orange-pale);
    color: var(--orange);
    border-radius: 20px;
    font-size: 0.78rem;
    font-weight: 700;
    font-family: 'Syne', sans-serif;
  }

  /* ── Info strip ── */
  .info-strip {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 14px;
    background: var(--blue-pale);
    border-radius: 9px;
    font-size: 0.8rem;
    color: #1D4ED8;
    margin-bottom: 16px;
  }

  /* ── Input with icon ── */
  .input-icon-wrap {
    position: relative;
  }

  .input-icon-wrap i {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--muted);
    font-size: 0.82rem;
    pointer-events: none;
  }

  .input-icon-wrap .form-control { padding-left: 34px; }

  /* Loading overlay */
  .saving-overlay {
    position: fixed;
    inset: 0;
    background: rgba(26,26,46,0.35);
    display: none;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    backdrop-filter: blur(2px);
  }

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

  .saving-box {
    background: var(--surface);
    border-radius: 16px;
    padding: 28px 36px;
    text-align: center;
    box-shadow: 0 20px 60px rgba(0,0,0,0.2);
  }

  .saving-box i { font-size: 2rem; color: var(--orange); display: block; margin-bottom: 10px; }
  .saving-box p { font-family: 'Syne', sans-serif; font-weight: 700; color: var(--dark); }
</style>

<?php
// ── Guard: require valid ID ──────────────────────────────────────────────────
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: view_associations.php');
    exit;
}

$assoc_id = (int) $_GET['id'];

// ── Handle POST (save changes) ───────────────────────────────────────────────
$success_msg = '';
$error_msg   = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // — Association fields —
    $association_name     = mysqli_real_escape_string($conn, trim($_POST['association_name']));
    $location             = mysqli_real_escape_string($conn, trim($_POST['location']));
    $date_of_registration = mysqli_real_escape_string($conn, $_POST['date_of_registration']);
    $date_of_renewal      = mysqli_real_escape_string($conn, $_POST['date_of_renewal']);

    $upd = "UPDATE associations
            SET association_name  = '$association_name',
                location          = '$location',
                date_of_registration = '$date_of_registration',
                date_of_renewal   = '$date_of_renewal'
            WHERE id = $assoc_id";

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

        // — Officials: delete marked rows —
        if (!empty($_POST['delete_official'])) {
            foreach ($_POST['delete_official'] as $del_id) {
                $del_id = (int) $del_id;
                mysqli_query($conn, "DELETE FROM officials WHERE id = $del_id AND association_id = $assoc_id");
            }
        }

        // — Officials: update existing —
        if (!empty($_POST['official_id'])) {
            foreach ($_POST['official_id'] as $idx => $off_id) {
                $off_id   = (int) $off_id;
                $off_name = mysqli_real_escape_string($conn, trim($_POST['official_name'][$idx]));
                $position = mysqli_real_escape_string($conn, $_POST['official_position'][$idx]);
                $phone    = mysqli_real_escape_string($conn, trim($_POST['official_phone'][$idx]));

                if (!empty($off_name)) {
                    mysqli_query($conn,
                        "UPDATE officials
                         SET full_name = '$off_name', position = '$position', phone = '$phone'
                         WHERE id = $off_id AND association_id = $assoc_id");
                }
            }
        }

        // — Officials: insert new —
        if (!empty($_POST['new_official_name'])) {
            foreach ($_POST['new_official_name'] as $idx => $new_name) {
                $new_name = mysqli_real_escape_string($conn, trim($new_name));
                if (empty($new_name)) continue;
                $new_pos   = mysqli_real_escape_string($conn, $_POST['new_official_position'][$idx]);
                $new_phone = mysqli_real_escape_string($conn, trim($_POST['new_official_phone'][$idx]));

                mysqli_query($conn,
                    "INSERT INTO officials (association_id, full_name, position, phone, reg_date)
                     VALUES ($assoc_id, '$new_name', '$new_pos', '$new_phone', NOW())");
            }
        }

        $success_msg = "Association and officials updated successfully.";

    } else {
        $error_msg = "Database error: " . $conn->error;
    }
}

// ── Fetch association ────────────────────────────────────────────────────────
$assoc_res = mysqli_query($conn, "SELECT * FROM associations WHERE id = $assoc_id");
if (!$assoc_res || mysqli_num_rows($assoc_res) === 0) {
    header('Location: view_associations.php');
    exit;
}
$assoc = mysqli_fetch_assoc($assoc_res);

// ── Fetch officials ──────────────────────────────────────────────────────────
$off_res  = mysqli_query($conn, "SELECT * FROM officials WHERE association_id = $assoc_id ORDER BY id ASC");
$officials = [];
while ($o = mysqli_fetch_assoc($off_res)) {
    $officials[] = $o;
}

// ── Compute status ───────────────────────────────────────────────────────────
$today     = new DateTime();
$renewal   = new DateTime($assoc['date_of_renewal']);
$diff_days = (int) $today->diff($renewal)->format('%r%a');
if ($diff_days < 0)       { $status = 'expired'; $status_label = 'Expired'; }
elseif ($diff_days <= 30) { $status = 'soon';    $status_label = 'Renewing Soon'; }
else                      { $status = 'active';  $status_label = 'Active'; }
?>

<!-- ── Saving Overlay ── -->
<div class="saving-overlay" id="savingOverlay">
  <div class="saving-box">
    <i class="fa fa-spinner fa-spin"></i>
    <p>Saving Changes…</p>
  </div>
</div>

<!-- ── Breadcrumb ── -->
<div class="breadcrumb-bar">
  <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="current">Edit — <?= htmlspecialchars($assoc['association_name']) ?></span>
</div>

<!-- ── Page Header ── -->
<div class="page-header">
  <div>
    <h2>Edit <span>Association</span></h2>
    <p>Update association details and manage its registered officials</p>
  </div>
  <div class="header-actions">
    <span class="status-display status-<?= $status ?>"><?= $status_label ?></span>
    <a href="view_associations.php" class="btn-cancel">
      <i class="fa fa-arrow-left"></i> Back
    </a>
  </div>
</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; ?>

<!-- ── Form ── -->
<form method="POST" id="editForm">

  <div class="edit-grid">

    <!-- ── Association Details Card ── -->
    <div class="section-card">
      <div class="section-card-header">
        <div class="section-card-header-left">
          <div class="section-icon orange"><i class="fa fa-building"></i></div>
          <div>
            <h5>Association Details</h5>
            <small>Core information about the association</small>
          </div>
        </div>
        <span class="row-badge existing">ID #<?= $assoc_id ?></span>
      </div>
      <div class="section-card-body">

        <div class="form-group">
          <label class="form-label">Association Name <span class="required">*</span></label>
          <div class="input-icon-wrap">
            <i class="fa fa-building"></i>
            <input type="text" name="association_name" class="form-control"
                   value="<?= htmlspecialchars($assoc['association_name']) ?>" required>
          </div>
        </div>

        <div class="form-group">
          <label class="form-label">Location / Area <span class="required">*</span></label>
          <div class="input-icon-wrap">
            <i class="fa fa-map-marker-alt"></i>
            <input type="text" name="location" class="form-control"
                   value="<?= htmlspecialchars($assoc['location']) ?>" required>
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label class="form-label">Registration Date <span class="required">*</span></label>
            <input type="date" name="date_of_registration" class="form-control"
                   value="<?= htmlspecialchars($assoc['date_of_registration']) ?>" required>
          </div>
          <div class="form-group">
            <label class="form-label">Renewal Date <span class="required">*</span></label>
            <input type="date" name="date_of_renewal" class="form-control"
                   value="<?= htmlspecialchars($assoc['date_of_renewal']) ?>"
                   required id="renewalDateInput">
          </div>
        </div>

        <!-- Live status preview -->
        <div style="margin-top: 4px;">
          <label class="form-label">Current Status</label>
          <div>
            <span class="status-display status-<?= $status ?>" id="statusPreview">
              <?= $status_label ?>
            </span>
            <?php if ($diff_days >= 0): ?>
              <small style="font-size:0.78rem; color:var(--muted); margin-left:10px;">
                <?= $diff_days ?> day<?= $diff_days != 1 ? 's' : '' ?> remaining
              </small>
            <?php else: ?>
              <small style="font-size:0.78rem; color:var(--red); margin-left:10px;">
                <?= abs($diff_days) ?> day<?= abs($diff_days) != 1 ? 's' : '' ?> overdue
              </small>
            <?php endif; ?>
          </div>
        </div>

      </div>
    </div>

    <!-- ── Quick Info Card ── -->
    <div class="section-card">
      <div class="section-card-header">
        <div class="section-card-header-left">
          <div class="section-icon blue"><i class="fa fa-chart-bar"></i></div>
          <div>
            <h5>Quick Summary</h5>
            <small>Overview of this association</small>
          </div>
        </div>
      </div>
      <div class="section-card-body">

        <div style="display:grid; grid-template-columns:1fr 1fr; gap:14px; margin-bottom:18px;">

          <div style="background:#F5F5FA; border-radius:10px; padding:14px; text-align:center;">
            <div style="font-family:'Syne',sans-serif; font-size:1.8rem; font-weight:800; color:var(--orange); line-height:1;">
              <?= count($officials) ?>
            </div>
            <div style="font-size:0.75rem; color:var(--muted); margin-top:4px; font-weight:500;">Officials</div>
          </div>

          <div style="background:#F5F5FA; border-radius:10px; padding:14px; text-align:center;">
            <div style="font-family:'Syne',sans-serif; font-size:1.8rem; font-weight:800; color:<?= $diff_days >= 0 ? 'var(--green)' : 'var(--red)' ?>; line-height:1;">
              <?= abs($diff_days) ?>
            </div>
            <div style="font-size:0.75rem; color:var(--muted); margin-top:4px; font-weight:500;">
              Days <?= $diff_days >= 0 ? 'Remaining' : 'Overdue' ?>
            </div>
          </div>

        </div>

        <div style="font-size:0.82rem; color:var(--muted); border-top:1px solid var(--border); padding-top:16px; display:flex; flex-direction:column; gap:10px;">

          <div style="display:flex; justify-content:space-between; align-items:center;">
            <span><i class="fa fa-calendar-plus me-2" style="color:var(--orange);"></i>Registered</span>
            <strong style="color:var(--dark);">
              <?= $assoc['date_of_registration'] ? date('d M Y', strtotime($assoc['date_of_registration'])) : '—' ?>
            </strong>
          </div>

          <div style="display:flex; justify-content:space-between; align-items:center;">
            <span><i class="fa fa-calendar-alt me-2" style="color:var(--orange);"></i>Renewal</span>
            <strong style="color:var(--dark);">
              <?= $assoc['date_of_renewal'] ? date('d M Y', strtotime($assoc['date_of_renewal'])) : '—' ?>
            </strong>
          </div>

          <div style="display:flex; justify-content:space-between; align-items:center;">
            <span><i class="fa fa-map-marker-alt me-2" style="color:var(--orange);"></i>Location</span>
            <strong style="color:var(--dark);"><?= htmlspecialchars($assoc['location']) ?></strong>
          </div>

        </div>

        <!-- Change tracker -->
        <div style="margin-top:18px; padding:12px 14px; background:var(--orange-pale); border-radius:10px; border-left:3px solid var(--orange);">
          <div style="font-family:'Syne',sans-serif; font-size:0.78rem; font-weight:700; color:var(--orange); margin-bottom:4px;">
            <i class="fa fa-pencil-alt me-2"></i>PENDING CHANGES
          </div>
          <div style="font-size:0.8rem; color:var(--muted);" id="changeTracker">
            No changes yet
          </div>
        </div>

      </div>
    </div>

    <!-- ── Officials Card (full width) ── -->
    <div class="section-card full-width officials-section">
      <div class="section-card-header">
        <div class="section-card-header-left">
          <div class="section-icon orange"><i class="fa fa-users"></i></div>
          <div>
            <h5>Registered Officials</h5>
            <small>Edit, remove, or add officials for this association</small>
          </div>
        </div>
        <span class="row-badge existing" id="officialCountBadge"><?= count($officials) ?> official<?= count($officials) != 1 ? 's' : '' ?></span>
      </div>
      <div class="section-card-body" style="padding:0;">

        <div class="info-strip" style="margin:16px 16px 0; margin-bottom:0;">
          <i class="fa fa-info-circle"></i>
          Click the <strong style="color:var(--red); margin:0 3px;">✕</strong> button to mark an official for removal.
          Changes are saved when you click <strong style="margin:0 3px;">Save Changes</strong>.
        </div>

        <div id="officialsContainer">

          <?php if (empty($officials)): ?>
            <div id="noOfficialsMsg" style="text-align:center; padding:32px; color:var(--muted); font-size:0.88rem;">
              <i class="fa fa-user-slash" style="font-size:1.5rem; display:block; margin-bottom:8px; opacity:0.4;"></i>
              No officials registered yet. Add one below.
            </div>
          <?php else: ?>
            <div style="padding: 16px 16px 0;" id="noOfficialsMsg" style="display:none;"></div>

            <div class="officials-table-wrap" style="margin:16px; margin-bottom:0;">
              <table class="officials-table" id="officialsTable">
                <thead>
                  <tr>
                    <th style="width:36px;">#</th>
                    <th>Full Name</th>
                    <th style="width:150px;">Position</th>
                    <th style="width:160px;">Phone</th>
                    <th style="width:90px; text-align:center;">Status</th>
                    <th style="width:50px; text-align:center;">Del</th>
                  </tr>
                </thead>
                <tbody id="existingOfficialsBody">
                  <?php foreach ($officials as $idx => $off): ?>
                  <tr id="official-row-<?= $off['id'] ?>" data-id="<?= $off['id'] ?>">
                    <td style="color:var(--muted); font-size:0.78rem; font-weight:700;"><?= $idx + 1 ?></td>
                    <td>
                      <input type="text"
                             name="official_name[]"
                             class="official-row-input"
                             value="<?= htmlspecialchars($off['full_name']) ?>"
                             placeholder="Full Name"
                             required>
                      <input type="hidden" name="official_id[]" value="<?= $off['id'] ?>">
                    </td>
                    <td>
                      <select name="official_position[]" class="official-row-input">
                        <option value="Chairman"  <?= $off['position'] === 'Chairman'  ? 'selected' : '' ?>>Chairman</option>
                        <option value="Secretary" <?= $off['position'] === 'Secretary' ? 'selected' : '' ?>>Secretary</option>
                        <option value="Treasurer" <?= $off['position'] === 'Treasurer' ? 'selected' : '' ?>>Treasurer</option>
                        <option value="Member"    <?= $off['position'] === 'Member'    ? 'selected' : '' ?>>Member</option>
                        <option value="Vice Chairman" <?= $off['position'] === 'Vice Chairman' ? 'selected' : '' ?>>Vice Chairman</option>
                        <option value="PRO"       <?= $off['position'] === 'PRO'       ? 'selected' : '' ?>>PRO</option>
                      </select>
                    </td>
                    <td>
                      <input type="text"
                             name="official_phone[]"
                             class="official-row-input"
                             value="<?= htmlspecialchars($off['phone']) ?>"
                             placeholder="Phone number">
                    </td>
                    <td style="text-align:center;">
                      <span class="row-badge existing">Existing</span>
                    </td>
                    <td style="text-align:center;">
                      <button type="button" class="btn-del-row"
                              onclick="toggleDeleteOfficial(<?= $off['id'] ?>, this)"
                              title="Mark for deletion">
                        <i class="fa fa-times"></i>
                      </button>
                      <input type="hidden" name="delete_flag_<?= $off['id'] ?>" value="0" id="del-flag-<?= $off['id'] ?>">
                    </td>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>

          <!-- New officials appended here -->
          <div id="newOfficialsContainer" style="margin: 0 16px;"></div>

        </div>

        <!-- Delete registry (hidden inputs built by JS) -->
        <div id="deleteRegistry"></div>

        <div style="padding:16px;">
          <button type="button" class="btn-add-official" onclick="addNewOfficial()">
            <i class="fa fa-user-plus"></i> Add New Official
          </button>
        </div>

      </div>

      <!-- Form Footer / Actions -->
      <div class="form-actions">
        <a href="view_associations.php" class="btn-cancel">
          <i class="fa fa-times"></i> Cancel
        </a>
        <div style="display:flex; align-items:center; gap:12px;">
          <span class="changes-pill" id="changesPill" style="display:none;">
            <i class="fa fa-pencil-alt"></i>
            <span id="changesPillText">0 changes</span>
          </span>
          <button type="submit" class="btn-save" onclick="showSaving()">
            <i class="fa fa-save"></i> Save Changes
          </button>
        </div>
      </div>

    </div><!-- /officials card -->

  </div><!-- /edit-grid -->
</form>


<script>
// ─── State ────────────────────────────────────────────────────────────────────
let newOfficialCount = 0;
let deletedIds       = new Set();
let changeCount      = 0;

// ─── Track Changes ────────────────────────────────────────────────────────────
function countChanges() {
    changeCount = deletedIds.size;

    // Count new official rows
    const newRows = document.querySelectorAll('.new-official-row');
    newRows.forEach(row => {
        const nameVal = row.querySelector('input[name="new_official_name[]"]').value.trim();
        if (nameVal !== '') changeCount++;
    });

    // Count modified existing fields
    document.querySelectorAll('[data-original]').forEach(el => {
        if (el.value !== el.dataset.original) changeCount++;
    });

    const pill    = document.getElementById('changesPill');
    const tracker = document.getElementById('changeTracker');

    if (changeCount > 0) {
        pill.style.display = 'inline-flex';
        document.getElementById('changesPillText').textContent = changeCount + ' change' + (changeCount !== 1 ? 's' : '');
        tracker.innerHTML = `<span style="color:var(--orange); font-weight:600;">${changeCount} unsaved change${changeCount !== 1 ? 's' : ''}</span>`;
    } else {
        pill.style.display = 'none';
        tracker.textContent = 'No changes yet';
    }
}

// Attach change listeners to existing inputs
document.querySelectorAll('.official-row-input, .form-control').forEach(el => {
    el.dataset.original = el.value;
    el.addEventListener('input',  countChanges);
    el.addEventListener('change', countChanges);
});

// ─── Toggle Delete Existing Official ─────────────────────────────────────────
function toggleDeleteOfficial(id, btn) {
    const row  = document.getElementById('official-row-' + id);
    const flag = document.getElementById('del-flag-' + id);

    if (deletedIds.has(id)) {
        // Undo
        deletedIds.delete(id);
        flag.value = '0';
        row.classList.remove('official-deleted');
        btn.innerHTML = '<i class="fa fa-times"></i>';
        btn.title = 'Mark for deletion';
        btn.style.background = '';
        btn.style.color = '';
        row.querySelector('.row-badge').className = 'row-badge existing';
        row.querySelector('.row-badge').textContent = 'Existing';

        // Remove from delete registry
        const regInput = document.getElementById('del-reg-' + id);
        if (regInput) regInput.remove();

    } else {
        // Mark for delete
        deletedIds.add(id);
        flag.value = '1';
        row.classList.add('official-deleted');
        btn.innerHTML = '<i class="fa fa-undo"></i>';
        btn.title = 'Undo — restore this official';
        btn.style.background = '#F59E0B';
        btn.style.color = '#fff';
        row.querySelector('.row-badge').className = 'row-badge deleted';
        row.querySelector('.row-badge').textContent = 'Removing';

        // Add hidden input for delete
        const reg = document.getElementById('deleteRegistry');
        const inp = document.createElement('input');
        inp.type  = 'hidden';
        inp.name  = 'delete_official[]';
        inp.value = id;
        inp.id    = 'del-reg-' + id;
        reg.appendChild(inp);
    }

    updateOfficialCount();
    countChanges();
}

// ─── Add New Official Row ────────────────────────────────────────────────────
function addNewOfficial() {
    const container = document.getElementById('newOfficialsContainer');

    // Hide "no officials" message if visible
    const noMsg = document.getElementById('noOfficialsMsg');
    if (noMsg) noMsg.style.display = 'none';

    // Create table if it doesn't exist yet
    let table = document.getElementById('officialsTable');
    if (!table) {
        const wrap = document.createElement('div');
        wrap.className = 'officials-table-wrap';
        wrap.style.marginBottom = '0';
        wrap.innerHTML = `
            <table class="officials-table" id="officialsTable">
                <thead>
                    <tr>
                        <th style="width:36px;">#</th>
                        <th>Full Name</th>
                        <th style="width:150px;">Position</th>
                        <th style="width:160px;">Phone</th>
                        <th style="width:90px; text-align:center;">Status</th>
                        <th style="width:50px; text-align:center;">Del</th>
                    </tr>
                </thead>
                <tbody id="existingOfficialsBody"></tbody>
            </table>`;
        container.parentElement.insertBefore(wrap, container);
        table = document.getElementById('officialsTable');
    }

    const tbody = document.getElementById('existingOfficialsBody') || table.querySelector('tbody');
    const rowNum = tbody.querySelectorAll('tr').length + 1;
    const uid    = 'new_' + (++newOfficialCount);

    const tr = document.createElement('tr');
    tr.id        = 'new-official-' + uid;
    tr.className = 'new-official-row';
    tr.style.animation = 'fadeRow 0.3s ease both';

    tr.innerHTML = `
        <td style="color:var(--muted); font-size:0.78rem; font-weight:700;">${rowNum}</td>
        <td>
            <input type="text"
                   name="new_official_name[]"
                   class="official-row-input"
                   placeholder="Full Name"
                   oninput="countChanges()"
                   required>
        </td>
        <td>
            <select name="new_official_position[]" class="official-row-input" onchange="countChanges()">
                <option value="Chairman">Chairman</option>
                <option value="Secretary">Secretary</option>
                <option value="Treasurer">Treasurer</option>
                <option value="Member">Member</option>
                <option value="Vice Chairman">Vice Chairman</option>
                <option value="PRO">PRO</option>
            </select>
        </td>
        <td>
            <input type="text"
                   name="new_official_phone[]"
                   class="official-row-input"
                   placeholder="Phone number"
                   oninput="countChanges()">
        </td>
        <td style="text-align:center;">
            <span class="row-badge new">New</span>
        </td>
        <td style="text-align:center;">
            <button type="button" class="btn-del-row"
                    onclick="removeNewRow('${uid}', this)"
                    title="Remove this row">
                <i class="fa fa-times"></i>
            </button>
        </td>`;

    tbody.appendChild(tr);
    updateOfficialCount();
    tr.querySelector('input[name="new_official_name[]"]').focus();
    countChanges();
}

// ─── Remove new (unsaved) row ────────────────────────────────────────────────
function removeNewRow(uid, btn) {
    const row = document.getElementById('new-official-' + uid);
    if (row) {
        row.style.transition = 'opacity 0.25s, transform 0.25s';
        row.style.opacity    = '0';
        row.style.transform  = 'translateX(20px)';
        setTimeout(() => { row.remove(); updateOfficialCount(); countChanges(); }, 250);
    }
}

// ─── Update count badge ───────────────────────────────────────────────────────
function updateOfficialCount() {
    const allRows    = document.querySelectorAll('#existingOfficialsBody tr, .new-official-row');
    const activeRows = [...allRows].filter(r => !r.classList.contains('official-deleted'));
    const n          = activeRows.length;
    const badge      = document.getElementById('officialCountBadge');
    if (badge) badge.textContent = n + ' official' + (n !== 1 ? 's' : '');
}

// ─── Live renewal status preview ─────────────────────────────────────────────
document.getElementById('renewalDateInput').addEventListener('change', function () {
    const today   = new Date();
    today.setHours(0, 0, 0, 0);
    const renewal = new Date(this.value);
    const diff    = Math.floor((renewal - today) / (1000 * 60 * 60 * 24));
    const preview = document.getElementById('statusPreview');

    if (!this.value) return;

    if (diff < 0) {
        preview.className = 'status-display status-expired';
        preview.textContent = 'Expired';
    } else if (diff <= 30) {
        preview.className = 'status-display status-soon';
        preview.textContent = 'Renewing Soon';
    } else {
        preview.className = 'status-display status-active';
        preview.textContent = 'Active';
    }

    countChanges();
});

// ─── Saving overlay ───────────────────────────────────────────────────────────
function showSaving() {
    // Only show if form is valid
    if (document.getElementById('editForm').checkValidity()) {
        document.getElementById('savingOverlay').classList.add('show');
    }
}

// ─── Warn on unsaved changes ──────────────────────────────────────────────────
let formSubmitted = false;
document.getElementById('editForm').addEventListener('submit', () => { formSubmitted = true; });
window.addEventListener('beforeunload', function (e) {
    if (!formSubmitted && changeCount > 0) {
        e.preventDefault();
        e.returnValue = '';
    }
});

// ─── Animate rows on load ─────────────────────────────────────────────────────
document.querySelectorAll('#existingOfficialsBody tr').forEach((tr, i) => {
    tr.style.animationDelay = (i * 0.04) + 's';
    tr.style.animation = 'fadeRow 0.35s ease both';
});
</script>

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