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

$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']);

    // ── Insert Association ──────────────────────────────────────
    $sql = "INSERT INTO associations (association_name, location, date_of_registration, date_of_renewal)
            VALUES ('$association_name', '$location', '$date_of_registration', '$date_of_renewal')";

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

        $association_id = mysqli_insert_id($conn);

        // ── Insert Officials ────────────────────────────────────
        if (!empty($_POST['full_name'])) {
            foreach ($_POST['full_name'] as $key => $name) {

                $name = trim($name);
                if (empty($name)) continue; // skip blank rows

                // ✅ FIX: use $name (the loop variable), NOT $association_name
                $full_name = mysqli_real_escape_string($conn, $name);
                $position  = mysqli_real_escape_string($conn, $_POST['position'][$key]);
                $phone     = mysqli_real_escape_string($conn, trim($_POST['phone'][$key]));

                $query = "INSERT INTO officials (association_id, full_name, position, phone, reg_date)
                          VALUES ('$association_id', '$full_name', '$position', '$phone', NOW())";

                mysqli_query($conn, $query);
            }
        }

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

    } else {
        $error_msg = "Error saving association: " . $conn->error;
    }
}

// ── HTML output starts here ─────────────────────────────────────
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-pale: #FFF0E6;
    --orange-glow: rgba(232,93,4,0.12);
    --dark:        #1A1A2E;
    --mid:         #2A2A4A;
    --border:      #E4E4F0;
    --muted:       #8888AA;
    --bg:          #F5F5FA;
    --surface:     #FFFFFF;
    --green-pale:  #DCFCE7;
    --red-pale:    #FEE2E2;
    --radius:      12px;
    --shadow:      0 2px 12px rgba(26,26,46,0.07);
  }

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

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

  /* ── Page Header ── */
  .page-header {
    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);
  }

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

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

  /* ── Alerts ── */
  .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; }

  /* ── Cards ── */
  .form-card {
    background: var(--surface);
    border-radius: 16px;
    border: 1px solid var(--border);
    box-shadow: var(--shadow);
    overflow: hidden;
    margin-bottom: 22px;
  }

  .form-card-header {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 15px 22px;
    border-bottom: 1px solid var(--border);
    background: linear-gradient(135deg, #FAFAFA, #F5F5FA);
  }

  .card-icon {
    width: 36px;
    height: 36px;
    border-radius: 10px;
    background: var(--orange-pale);
    color: var(--orange);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.9rem;
    flex-shrink: 0;
  }

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

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

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

  /* ── Form Fields ── */
  .form-group { margin-bottom: 18px; }
  .form-group:last-child { margin-bottom: 0; }

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

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

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

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

  select.form-control { cursor: pointer; }

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

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

  .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; }

  /* ── Officials Table ── */
  .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), var(--mid));
  }

  .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;
    animation: fadeRow 0.3s ease both;
  }

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

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

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

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

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

  select.tbl-input { cursor: pointer; }

  /* ── Row number ── */
  .row-num {
    font-family: 'Syne', sans-serif;
    font-weight: 700;
    font-size: 0.78rem;
    color: var(--muted);
    width: 36px;
    text-align: center;
  }

  /* ── Remove button ── */
  .btn-remove-row {
    width: 30px;
    height: 30px;
    border-radius: 8px;
    border: none;
    background: var(--red-pale);
    color: #EF4444;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 0.8rem;
    transition: all 0.15s;
  }

  .btn-remove-row:hover { background: #EF4444; color: #fff; transform: scale(1.08); }

  /* ── Add More button ── */
  .btn-add-row {
    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-row:hover { background: var(--orange); color: #fff; border-style: solid; }

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

  .btn-submit {
    background: var(--orange);
    color: #fff;
    border: none;
    padding: 11px 30px;
    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;
  }

  .btn-submit:hover {
    background: #FF6B1A;
    transform: translateY(-1px);
    box-shadow: 0 6px 20px rgba(232,93,4,0.3);
  }

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

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

  /* ── Official count badge ── */
  .official-count {
    font-size: 0.78rem;
    font-weight: 600;
    color: var(--muted);
    margin-left: auto;
  }
</style>

<!-- ── Page Header ── -->
<div class="page-header">
  <div>
    <h2>Add New <span>Association</span></h2>
    <p>Register a new street trade association and its officials</p>
  </div>
  <a href="view_associations.php" class="btn-reset">
    <i class="fa fa-arrow-left"></i> Back to List
  </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; ?>

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

  <!-- Association Info Card -->
  <div class="form-card">
    <div class="form-card-header">
      <div class="card-icon"><i class="fa fa-building"></i></div>
      <div>
        <h5>Association Information</h5>
        <small>Basic details about the association</small>
      </div>
    </div>
    <div class="form-card-body">

      <div class="form-group">
        <label class="form-label">Association Name <span class="req">*</span></label>
        <div class="input-icon-wrap">
          <i class="fa fa-building"></i>
          <input type="text" name="association_name" class="form-control"
                 placeholder="e.g. Aba Road Traders Association"
                 value="<?= isset($_POST['association_name']) ? htmlspecialchars($_POST['association_name']) : '' ?>"
                 required>
        </div>
      </div>

      <div class="form-group">
        <label class="form-label">Location / Area <span class="req">*</span></label>
        <div class="input-icon-wrap">
          <i class="fa fa-map-marker-alt"></i>
          <input type="text" name="location" class="form-control"
                 placeholder="e.g. Mile 1, Port Harcourt"
                 value="<?= isset($_POST['location']) ? htmlspecialchars($_POST['location']) : '' ?>"
                 required>
        </div>
      </div>

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

    </div>
  </div>

  <!-- Officials Card -->
  <div class="form-card">
    <div class="form-card-header">
      <div class="card-icon"><i class="fa fa-users"></i></div>
      <div>
        <h5>Officials</h5>
        <small>Add the association's registered officials</small>
      </div>
      <span class="official-count" id="officialCount">1 official</span>
    </div>

    <div class="form-card-body" style="padding-bottom: 0;">

      <div class="officials-table-wrap">
        <table class="officials-table">
          <thead>
            <tr>
              <th style="width:40px; text-align:center;">#</th>
              <th>Full Name <span style="color:#EF4444;">*</span></th>
              <th style="width:160px;">Position</th>
              <th style="width:175px;">Phone</th>
              <th style="width:46px; text-align:center;">Del</th>
            </tr>
          </thead>
          <tbody id="officialsBody">

            <!-- Default first row -->
            <tr>
              <td class="row-num">1</td>
              <td>
                <input type="text"
                       name="full_name[]"
                       class="tbl-input"
                       placeholder="e.g. John Doe"
                       required>
              </td>
              <td>
                <select name="position[]" class="tbl-input">
                  <option value="Chairman">Chairman</option>
                  <option value="Vice Chairman">Vice Chairman</option>
                  <option value="Secretary">Secretary</option>
                  <option value="Treasurer">Treasurer</option>
                  <option value="PRO">PRO</option>
                  <option value="Member">Member</option>
                </select>
              </td>
              <td>
                <input type="text"
                       name="phone[]"
                       class="tbl-input"
                       placeholder="e.g. 08012345678">
              </td>
              <td style="text-align:center;">
                <button type="button" class="btn-remove-row" onclick="removeRow(this)" title="Remove row">
                  <i class="fa fa-times"></i>
                </button>
              </td>
            </tr>

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

      <div style="padding: 0 0 18px;">
        <button type="button" class="btn-add-row" onclick="addRow()">
          <i class="fa fa-user-plus"></i> Add More Officials
        </button>
      </div>

    </div>

    <!-- Form Actions -->
    <div class="form-footer">
      <button type="reset" class="btn-reset" onclick="resetForm()">
        <i class="fa fa-redo"></i> Clear Form
      </button>
      <button type="submit" class="btn-submit">
        <i class="fa fa-save"></i> Save Association
      </button>
    </div>

  </div>

</form>


<script>
// ── Add a new official row ─────────────────────────────────────
function addRow() {
    const tbody = document.getElementById('officialsBody');
    const rowCount = tbody.querySelectorAll('tr').length + 1;

    const tr = document.createElement('tr');
    tr.style.animation = 'fadeRow 0.3s ease both';
    tr.innerHTML = `
        <td class="row-num">${rowCount}</td>
        <td>
            <input type="text"
                   name="full_name[]"
                   class="tbl-input"
                   placeholder="e.g. Jane Smith"
                   required>
        </td>
        <td>
            <select name="position[]" class="tbl-input">
                <option value="Chairman">Chairman</option>
                <option value="Vice Chairman">Vice Chairman</option>
                <option value="Secretary">Secretary</option>
                <option value="Treasurer">Treasurer</option>
                <option value="PRO">PRO</option>
                <option value="Member">Member</option>
            </select>
        </td>
        <td>
            <input type="text"
                   name="phone[]"
                   class="tbl-input"
                   placeholder="e.g. 08012345678">
        </td>
        <td style="text-align:center;">
            <button type="button" class="btn-remove-row" onclick="removeRow(this)" title="Remove row">
                <i class="fa fa-times"></i>
            </button>
        </td>`;

    tbody.appendChild(tr);
    renumberRows();
    updateCount();
    tr.querySelector('input[name="full_name[]"]').focus();
}

// ── Remove a row ──────────────────────────────────────────────
function removeRow(btn) {
    const tbody = document.getElementById('officialsBody');

    // Always keep at least one row
    if (tbody.querySelectorAll('tr').length <= 1) {
        // Just clear the inputs instead of removing
        const row = btn.closest('tr');
        row.querySelectorAll('input').forEach(i => i.value = '');
        row.querySelector('select').selectedIndex = 0;
        return;
    }

    const row = btn.closest('tr');
    row.style.transition = 'opacity 0.2s, transform 0.2s';
    row.style.opacity    = '0';
    row.style.transform  = 'translateX(15px)';
    setTimeout(() => {
        row.remove();
        renumberRows();
        updateCount();
    }, 200);
}

// ── Re-number rows after add/remove ──────────────────────────
function renumberRows() {
    document.querySelectorAll('#officialsBody tr').forEach((tr, i) => {
        tr.querySelector('.row-num').textContent = i + 1;
    });
}

// ── Update the count badge ─────────────────────────────────────
function updateCount() {
    const n = document.querySelectorAll('#officialsBody tr').length;
    document.getElementById('officialCount').textContent = n + ' official' + (n !== 1 ? 's' : '');
}

// ── Reset form helper ─────────────────────────────────────────
function resetForm() {
    const tbody = document.getElementById('officialsBody');
    // Remove all rows except the first
    const rows = tbody.querySelectorAll('tr');
    rows.forEach((r, i) => { if (i > 0) r.remove(); });
    // Clear first row inputs
    rows[0].querySelectorAll('input').forEach(i => i.value = '');
    rows[0].querySelector('select').selectedIndex = 0;
    renumberRows();
    updateCount();
}
</script>

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