<?php
/**
 * settings-location.php — Unified District & Location Management
 * - Admin only + CSRF
 * - Manage Districts (add/edit/activate/deactivate/delete*)
 * - Manage Locations (add/edit/assign district/activate/deactivate/delete)
 * - Search & simple UI tabs (pure CSS/JS)
 * - Duplicate checks (case-insensitive)
 *
 * *Delete District is guarded: only allowed if no locations under it AND no members referencing the district.
 */

session_start();
require_once __DIR__ . "/db.php";

/* ===== Auth: admin only ===== */
if (!isset($_SESSION['user']) || (($_SESSION['user']['role'] ?? '') !== 'admin')) {
    header("Location: dashboard.php"); exit;
}

/* ===== CSRF token ===== */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$CSRF = $_SESSION['csrf_token'];

/* ===== Helpers ===== */
function flash_redirect(string $type, string $msg, array $q = []): void {
    $q[$type] = $msg;
    $qs = http_build_query($q);
    header("Location: settings-location.php" . ($qs ? "?$qs" : ""));
    exit;
}
function require_post_csrf(): void {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo "Method Not Allowed"; exit; }
    $token = $_POST['csrf_token'] ?? '';
    if (!$token || !hash_equals($_SESSION['csrf_token'] ?? '', $token)) { http_response_code(400); echo "Invalid CSRF token."; exit; }
}
function district_exists(mysqli $conn, int $id): bool {
    if ($id <= 0) return false;
    $stmt = $conn->prepare("SELECT id FROM districts WHERE id=? LIMIT 1");
    if (!$stmt) return false;
    $stmt->bind_param("i", $id);
    $stmt->execute(); $res = $stmt->get_result();
    $ok = (bool)($res && $res->fetch_assoc());
    $stmt->close();
    return $ok;
}
function district_name_exists_ci(mysqli $conn, string $name, ?int $excludeId = null): bool {
    if ($excludeId) {
        $sql = "SELECT id FROM districts WHERE LOWER(name)=LOWER(?) AND id<>? LIMIT 1";
        $st  = $conn->prepare($sql); if(!$st) return false;
        $st->bind_param("si", $name, $excludeId);
    } else {
        $sql = "SELECT id FROM districts WHERE LOWER(name)=LOWER(?) LIMIT 1";
        $st  = $conn->prepare($sql); if(!$st) return false;
        $st->bind_param("s", $name);
    }
    $st->execute(); $res = $st->get_result();
    $exists = (bool)($res && $res->fetch_assoc());
    $st->close();
    return $exists;
}
function location_exists_ci(mysqli $conn, string $name, ?int $excludeId = null): bool {
    if ($excludeId) {
        $sql = "SELECT id FROM locations WHERE LOWER(name)=LOWER(?) AND id<>? LIMIT 1";
        $stmt = $conn->prepare($sql); if(!$stmt) return false;
        $stmt->bind_param("si", $name, $excludeId);
    } else {
        $sql = "SELECT id FROM locations WHERE LOWER(name)=LOWER(?) LIMIT 1";
        $stmt = $conn->prepare($sql); if(!$stmt) return false;
        $stmt->bind_param("s", $name);
    }
    $stmt->execute(); $res = $stmt->get_result();
    $exists = (bool)($res && $res->fetch_assoc());
    $stmt->close();
    return $exists;
}
function count_locations_under(mysqli $conn, int $district_id): int {
    $stmt = $conn->prepare("SELECT COUNT(*) AS c FROM locations WHERE district_id=?");
    if(!$stmt) return 0;
    $stmt->bind_param("i", $district_id);
    $stmt->execute(); $r=$stmt->get_result()->fetch_assoc(); $stmt->close();
    return (int)($r['c'] ?? 0);
}
function count_members_in_district(mysqli $conn, int $district_id): int {
    $stmt = $conn->prepare("SELECT COUNT(*) AS c FROM members WHERE district_id=?");
    if(!$stmt) return 0;
    $stmt->bind_param("i", $district_id);
    $stmt->execute(); $r=$stmt->get_result()->fetch_assoc(); $stmt->close();
    return (int)($r['c'] ?? 0);
}
/** Fallback resolver: accept numeric ID (>0) or a name (case-insensitive). '0' / 0 / '' => NULL */
function district_id_from_maybe_name(mysqli $conn, $input): ?int {
    if ($input === '' || $input === null || $input === '0' || $input === 0) return null;
    if (is_numeric($input)) {
        $id = (int)$input;
        return ($id > 0 && district_exists($conn,$id)) ? $id : null;
    }
    $name = trim((string)$input);
    $st = $conn->prepare("SELECT id FROM districts WHERE LOWER(name)=LOWER(?) LIMIT 1");
    if(!$st) return null;
    $st->bind_param('s',$name);
    $st->execute(); $st->bind_result($id);
    $ok = $st->fetch(); $st->close();
    return $ok ? (int)$id : null;
}

/* ===== Actions ===== */
$activeTab = $_GET['tab'] ?? 'locations';

/* ---------- Districts: create ---------- */
if (isset($_POST['action']) && $_POST['action'] === 'add_district') {
    require_post_csrf();
    $name   = trim($_POST['district_name'] ?? '');
    $active = isset($_POST['district_active']) ? 1 : 0;

    if ($name === '')                      flash_redirect('error','Please provide a district name.',['tab'=>'districts']);
    if (mb_strlen($name) > 120)            flash_redirect('error','District name too long (max 120).',['tab'=>'districts']);
    if (district_name_exists_ci($conn,$name,null)) {
        flash_redirect('error','District name already exists.',['tab'=>'districts']);
    }

    $st = $conn->prepare("INSERT INTO districts (name, is_active) VALUES (?, ?)");
    if(!$st) flash_redirect('error','Database error.',['tab'=>'districts']);
    $st->bind_param("si", $name, $active);
    $st->execute(); $st->close();
    flash_redirect('success','District created.',['tab'=>'districts']);
}

/* ---------- Districts: update ---------- */
if (isset($_POST['action']) && $_POST['action'] === 'update_district') {
    require_post_csrf();
    $id     = (int)($_POST['edit_district_id'] ?? 0);
    $name   = trim($_POST['edit_district_name'] ?? '');
    $active = isset($_POST['edit_district_active']) ? 1 : 0;

    if ($id <= 0)                           flash_redirect('error','Invalid district.', ['tab'=>'districts']);
    if (!district_exists($conn,$id))        flash_redirect('error','District not found.',['tab'=>'districts']);
    if ($name === '')                       flash_redirect('error','District name cannot be empty.', ['tab'=>'districts']);
    if (mb_strlen($name) > 120)             flash_redirect('error','District name too long (max 120).',['tab'=>'districts']);
    if (district_name_exists_ci($conn,$name,$id)) {
        flash_redirect('error','Another district already uses that name.',['tab'=>'districts']);
    }

    $st = $conn->prepare("UPDATE districts SET name=?, is_active=? WHERE id=?");
    if(!$st) flash_redirect('error','Database error.',['tab'=>'districts']);
    $st->bind_param("sii", $name, $active, $id);
    $st->execute(); $st->close();
    flash_redirect('success','District updated.',['tab'=>'districts']);
}

/* ---------- Districts: delete (guard) ---------- */
if (isset($_POST['action']) && $_POST['action'] === 'delete_district') {
    require_post_csrf();
    $id = (int)($_POST['delete_district_id'] ?? 0);
    if ($id <= 0) flash_redirect('error','Invalid district id.',['tab'=>'districts']);

    $locCount = count_locations_under($conn, $id);
    if ($locCount > 0) {
        flash_redirect('error',"Cannot delete: district has $locCount location(s).",['tab'=>'districts']);
    }
    $memCount = count_members_in_district($conn, $id);
    if ($memCount > 0) {
        flash_redirect('error',"Cannot delete: $memCount member(s) linked to this district.",['tab'=>'districts']);
    }

    $del = $conn->prepare("DELETE FROM districts WHERE id=? LIMIT 1");
    if(!$del) flash_redirect('error','Database error.',['tab'=>'districts']);
    $del->bind_param("i",$id);
    $del->execute(); $ok = ($del->affected_rows > 0); $del->close();
    $ok ? flash_redirect('success','District deleted.',['tab'=>'districts'])
        : flash_redirect('error','District not found or already removed.',['tab'=>'districts']);
}

/* ---------- Locations: create ---------- */
if (isset($_POST['action']) && $_POST['action'] === 'add_location') {
    require_post_csrf();
    $location    = trim($_POST['location'] ?? '');
    $district_in = $_POST['district_id'] ?? '';      // may be '', '0', id, or name
    $district_id = district_id_from_maybe_name($conn, $district_in);
    $active      = isset($_POST['location_active']) ? 1 : 0;

    if ($location === '')           flash_redirect('error', 'Please provide a location name.');
    if (mb_strlen($location) > 191) flash_redirect('error', 'Location name is too long (max 191 chars).');
    if ($district_in !== '' && $district_in !== '0' && !$district_id) {
        flash_redirect('error', 'Selected district is invalid.');
    }
    if (location_exists_ci($conn, $location, null)) {
        flash_redirect('error', 'Location name already exists.');
    }

    if ($district_id !== null) {
        $stmt = $conn->prepare("INSERT INTO locations (name, district_id, active) VALUES (?, ?, ?)");
        if(!$stmt) flash_redirect('error','Database error.');
        $stmt->bind_param("sii", $location, $district_id, $active);
    } else {
        $stmt = $conn->prepare("INSERT INTO locations (name, district_id, active) VALUES (?, NULL, ?)");
        if(!$stmt) flash_redirect('error','Database error.');
        $stmt->bind_param("si", $location, $active);
    }
    $stmt->execute(); $stmt->close();
    flash_redirect('success', 'Location added.');
}

/* ---------- Locations: update ---------- */
if (isset($_POST['action']) && $_POST['action'] === 'update_location') {
    require_post_csrf();
    $id           = (int)($_POST['edit_location_id'] ?? 0);
    $name         = trim($_POST['edit_location_name'] ?? '');
    $active       = isset($_POST['edit_active']) ? 1 : 0;
    $district_in  = $_POST['edit_district_id'] ?? '';             // may be '', '0', id, or name
    $district_id  = district_id_from_maybe_name($conn, $district_in); // NULL if '', '0'

    if ($id <= 0)                   flash_redirect('error', 'Invalid location ID.');
    if ($name === '')               flash_redirect('error', 'Location name cannot be empty.');
    if (mb_strlen($name) > 191)     flash_redirect('error', 'Location name is too long (max 191 chars).');
    if ($district_in !== '' && $district_in !== '0' && !$district_id) {
        flash_redirect('error', 'Selected district is invalid.');
    }
    if (location_exists_ci($conn, $name, $id)) {
        flash_redirect('error', 'Another location with this name already exists.');
    }

    if ($district_id !== null) {
        $stmt = $conn->prepare("UPDATE locations SET name = ?, district_id = ?, active = ? WHERE id = ?");
        if(!$stmt) flash_redirect('error','Database error.');
        $stmt->bind_param("siii", $name, $district_id, $active, $id);
    } else {
        $stmt = $conn->prepare("UPDATE locations SET name = ?, district_id = NULL, active = ? WHERE id = ?");
        if(!$stmt) flash_redirect('error','Database error.');
        $stmt->bind_param("sii", $name, $active, $id);
    }
    $stmt->execute(); $stmt->close();
    flash_redirect('success', 'Location updated.');
}

/* ---------- Locations: delete ---------- */
if (isset($_POST['action']) && $_POST['action'] === 'delete_location') {
    require_post_csrf();
    $id = (int)($_POST['delete_id'] ?? 0);
    if ($id <= 0) flash_redirect('error', 'Invalid location ID.');
    $stmt = $conn->prepare("DELETE FROM locations WHERE id = ?");
    if(!$stmt) flash_redirect('error','Database error.');
    $stmt->bind_param("i", $id);
    $stmt->execute(); $affected = $stmt->affected_rows; $stmt->close();
    $affected > 0 ? flash_redirect('success', 'Location deleted.')
                  : flash_redirect('error', 'Location not found or already removed.');
}

/* ===== Data (for view) ===== */
// Districts: include counts
$districts = [];
$resD = $conn->query("
  SELECT d.id, d.name, d.is_active,
         (SELECT COUNT(*) FROM locations l WHERE l.district_id=d.id) AS loc_count,
         (SELECT COUNT(*) FROM members  m WHERE m.district_id=d.id) AS member_count
  FROM districts d
  ORDER BY d.name ASC
");
if ($resD) { while ($r = $resD->fetch_assoc()) $districts[] = $r; }

// Locations with district name
$sql = "SELECT l.id, l.name, l.active, l.district_id, d.name AS district_name
          FROM locations l
          LEFT JOIN districts d ON d.id = l.district_id
         ORDER BY COALESCE(d.name,''), l.name ASC";
$result = $conn->query($sql);
$locations = [];
$activeCount = 0;
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $locations[] = $row;
        if ((int)$row['active'] === 1) $activeCount++;
    }
}
$totalCount = count($locations);

ob_start();
?>
<style>
  /* Layout & basic UI */
  .wrap { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; }
  .crumbs { font-size:.9rem; color:#666; }
  .crumbs a { color:inherit; text-decoration:none; }
  .crumbs a:hover { text-decoration:underline; }

  .btn { appearance:none; border:1px solid #1f6feb; background:#1f6feb; color:#fff; padding:8px 12px; border-radius:8px; cursor:pointer; font-size:.95rem; }
  .btn:disabled { opacity:.6; cursor:not-allowed; }
  .btn.light { background:#f5f8ff; color:#1f3a7a; border-color:#c7d2fe; }
  .btn.ghost { background:transparent; color:#1f6feb; border-color:#1f6feb; }
  .btn.danger { border-color:#dc3545; background:#dc3545; }
  .badge { display:inline-block; padding:4px 8px; border-radius:999px; font-size:.8rem; line-height:1; }
  .badge.primary { background:#e6f0ff; color:#1f3a7a; border:1px solid #c7d2fe; }
  .badge.success { background:#eafaf1; color:#0f5132; border:1px solid #bcded0; }
  .badge.secondary { background:#f1f3f5; color:#495057; border:1px solid #dee2e6; }

  .card { background:#fff; border:1px solid #e9ecef; border-radius:12px; box-shadow:0 1px 2px rgba(0,0,0,.04); }
  .card .card-body { padding:16px; }
  .alert { border-radius:8px; padding:10px 12px; margin:10px 0 16px; }
  .alert.success { background:#e6ffed; color:#0f5132; border:1px solid #b7e2c5; }
  .alert.error   { background:#fff1f0; color:#842029; border:1px solid #f5c2c7; }
  .alert .close { float:right; border:0; background:transparent; font-size:18px; line-height:1; cursor:pointer; color:inherit; }

  .input { width:100%; padding:8px 10px; border:1px solid #ced4da; border-radius:8px; font-size:.95rem; }
  .input:focus { outline:none; border-color:#1f6feb; box-shadow:0 0 0 3px rgba(31,111,235,.15); }

  .table { width:100%; border-collapse:collapse; }
  .table th, .table td { padding:10px 12px; border-bottom:1px solid #edf2f7; text-align:left; }
  .table thead th { background:#f8f9fa; font-weight:600; }
  .table tbody tr:hover { background:#fbfdff; }

  /* Tabs */
  .tabs { display:flex; gap:8px; border-bottom:1px solid #e9ecef; margin-top:10px; }
  .tab { padding:8px 12px; border:1px solid #e9ecef; border-bottom:none; border-radius:10px 10px 0 0; background:#f8fafc; cursor:pointer; }
  .tab.active { background:#fff; border-bottom:1px solid #fff; font-weight:600; }

  /* Modal */
  .modal { position:fixed; inset:0; background:rgba(0,0,0,.45); display:none; align-items:center; justify-content:center; padding:16px; z-index:2000; }
  .modal.open { display:flex; }
  .modal .panel { width:100%; max-width:600px; background:#fff; border-radius:12px; overflow:hidden; border:1px solid #e9ecef; }
  .modal .panel .head { padding:12px 16px; border-bottom:1px solid #edf2f7; font-weight:600; }
  .modal .panel .body { padding:16px; }
  .modal .panel .foot { padding:12px 16px; border-top:1px solid #edf2f7; display:flex; gap:8px; justify-content:flex-end; }

  .muted { color:#6c757d; font-size:.9rem; }
  .grid { display:grid; gap:10px; }
  @media (min-width: 640px) { .grid.two { grid-template-columns: 1fr auto; align-items:center; } }
</style>

<div class="wrap">
  <div>
    <h2 style="margin:0;">District & Location Settings</h2>
    <div class="crumbs"><a href="dashboard.php">Dashboard</a> › <a href="settings.php">Settings</a> › <span>Districts & Locations</span></div>
  </div>
  <div class="wrap" style="gap:8px;">
    <span class="badge primary">Locations: <?= (int)$totalCount ?></span>
    <span class="badge success">Active: <?= (int)$activeCount ?></span>
    <button class="btn" id="btnOpenAddLocation">+ Add Location</button>
    <button class="btn light" id="btnOpenAddDistrict">+ Add District</button>
  </div>
</div>

<?php if (isset($_GET['success'])): ?>
  <div class="alert success"><button class="close" onclick="this.parentElement.remove()">×</button><?= htmlspecialchars($_GET['success']) ?></div>
<?php endif; ?>
<?php if (isset($_GET['error'])): ?>
  <div class="alert error"><button class="close" onclick="this.parentElement.remove()">×</button><?= htmlspecialchars($_GET['error']) ?></div>
<?php endif; ?>

<div class="tabs" id="tabs">
  <a class="tab <?= ($activeTab==='locations'?'active':'') ?>" href="?tab=locations">Locations</a>
  <a class="tab <?= ($activeTab==='districts'?'active':'') ?>" href="?tab=districts">Districts</a>
</div>

<?php if ($activeTab === 'districts'): ?>
  <!-- ===== Districts card ===== -->
  <div class="card">
    <div class="card-body">
      <div class="grid two" style="margin-bottom:12px;">
        <div class="muted">Tambah / sunting nama daerah & status aktif. Hapus dibenarkan hanya jika tiada lokasi & tiada ahli merujuk daerah tersebut.</div>
        <div><input class="input" id="districtFilter" placeholder="Search district..."></div>
      </div>

      <div class="table-wrap">
        <table class="table" id="districtTable">
          <thead>
            <tr>
              <th style="width:72px;">#</th>
              <th>District</th>
              <th style="width:140px;">Status</th>
              <th style="width:160px;"># Locations</th>
              <th style="width:160px;"># Members</th>
              <th style="width:260px;">Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php if (!$districts): ?>
            <tr><td colspan="6" class="muted" style="text-align:center; padding:28px;">No districts yet. Click <b>+ Add District</b>.</td></tr>
          <?php else: $i=1; foreach ($districts as $d):
                $dataKey = mb_strtolower($d['name'] ?? '');
                $isAct   = ((int)($d['is_active'] ?? 0) === 1);
                $locC    = (int)($d['loc_count'] ?? 0);
                $memC    = (int)($d['member_count'] ?? 0);
          ?>
            <tr data-key="<?= htmlspecialchars($dataKey) ?>">
              <td><?= $i++ ?></td>
              <td style="font-weight:600;"><?= htmlspecialchars($d['name']) ?></td>
              <td><?= $isAct ? '<span class="badge success">Active</span>' : '<span class="badge secondary">Inactive</span>' ?></td>
              <td><?= $locC ?></td>
              <td><?= $memC ?></td>
              <td>
                <div class="actions">
                  <button
                    class="btn light"
                    data-edit-district
                    data-id="<?= (int)$d['id'] ?>"
                    data-name="<?= htmlspecialchars($d['name']) ?>"
                    data-active="<?= $isAct ? 1 : 0 ?>"
                  >Edit</button>

                  <form method="post"
                        onsubmit="return confirm('Delete this district? Only allowed if it has NO locations and NO members linked.');"
                        style="display:inline;">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">
                    <input type="hidden" name="action" value="delete_district">
                    <input type="hidden" name="delete_district_id" value="<?= (int)$d['id'] ?>">
                    <button type="submit" class="btn danger" <?= ($locC>0||$memC>0)?'disabled':'' ?>>Delete</button>
                  </form>
                </div>
              </td>
            </tr>
          <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
<?php else: ?>
  <!-- ===== Locations card ===== -->
  <div class="card">
    <div class="card-body">
      <div class="grid two" style="margin-bottom:12px;">
        <div class="muted">Click <b>Edit</b> to change name, district or status.</div>
        <div><input class="input" id="locationFilter" placeholder="Search location or district..."></div>
      </div>

      <div class="table-wrap">
        <table class="table" id="locationTable">
          <thead>
            <tr>
              <th style="width:72px;">#</th>
              <th>Location</th>
              <th>District</th>
              <th style="width:160px;">Status</th>
              <th style="width:260px;">Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php if (!$locations): ?>
            <tr><td colspan="5" class="muted" style="text-align:center; padding:28px;">No locations yet. Click <b>+ Add Location</b> to create one.</td></tr>
          <?php else: ?>
            <?php $i=1; foreach ($locations as $row):
                  $dname  = $row['district_name'] ?: '-';
                  $dataKey = mb_strtolower(($row['name'] ?? '').' '.$dname);
                  $didAttr = (isset($row['district_id']) && $row['district_id'] !== null) ? (int)$row['district_id'] : '';
            ?>
              <tr data-key="<?= htmlspecialchars($dataKey) ?>">
                <td><?= $i++ ?></td>
                <td style="font-weight:600;"><?= htmlspecialchars($row['name']) ?></td>
                <td><?= htmlspecialchars($dname) ?></td>
                <td>
                  <?php if ((int)$row['active'] === 1): ?>
                    <span class="badge success">Active</span>
                  <?php else: ?>
                    <span class="badge secondary">Inactive</span>
                  <?php endif; ?>
                </td>
                <td>
                  <div class="actions">
                    <button
                      class="btn light"
                      data-edit
                      data-id="<?= (int)$row['id'] ?>"
                      data-name="<?= htmlspecialchars($row['name']) ?>"
                      data-active="<?= (int)$row['active'] ?>"
                      data-district-id="<?= $didAttr ?>"
                    >Edit</button>

                    <form method="post" onsubmit="return confirm('Delete this location? This action cannot be undone.');" style="display:inline;">
                      <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">
                      <input type="hidden" name="action" value="delete_location">
                      <input type="hidden" name="delete_id" value="<?= (int)$row['id'] ?>">
                      <button type="submit" class="btn danger">Delete</button>
                    </form>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
<?php endif; ?>

<!-- ===== Modal: Add Location ===== -->
<div class="modal" id="modalAddLoc" aria-hidden="true">
  <div class="panel">
    <div class="head">Add Location</div>
    <form method="post">
      <div class="body">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">
        <input type="hidden" name="action" value="add_location">

        <label for="add_location_name" style="display:block; margin-bottom:6px;">Location Name</label>
        <input class="input" type="text" name="location" id="add_location_name" maxlength="191" required>

        <label for="add_district_id" style="display:block; margin-top:10px; margin-bottom:6px;">District</label>
        <select class="input" name="district_id" id="add_district_id">
          <option value="">-- None --</option>
          <?php foreach ($districts as $d): ?>
            <option value="<?= (int)$d['id'] ?>">
              <?= htmlspecialchars($d['name']) ?><?= ((int)$d['is_active']===1?'':' (inactive)') ?>
            </option>
          <?php endforeach; ?>
        </select>

        <label style="display:flex; align-items:center; gap:8px; margin-top:10px;">
          <input type="checkbox" name="location_active" checked> Active
        </label>
      </div>
      <div class="foot">
        <button type="button" class="btn ghost" data-close="#modalAddLoc">Cancel</button>
        <button type="submit" class="btn">Add</button>
      </div>
    </form>
  </div>
</div>

<!-- ===== Modal: Edit Location ===== -->
<div class="modal" id="modalEditLoc" aria-hidden="true">
  <div class="panel">
    <div class="head">Edit Location</div>
    <form method="post">
      <div class="body">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">
        <input type="hidden" name="action" value="update_location">
        <input type="hidden" name="edit_location_id" id="edit_location_id">

        <label for="edit_location_name" style="display:block; margin-bottom:6px;">Location Name</label>
        <input class="input" type="text" name="edit_location_name" id="edit_location_name" maxlength="191" required>

        <label for="edit_location_district_id" style="display:block; margin-top:10px; margin-bottom:6px;">District</label>
        <select class="input" name="edit_district_id" id="edit_location_district_id">
          <option value="">-- None --</option>
          <?php foreach ($districts as $d): ?>
            <option value="<?= (int)$d['id'] ?>"><?= htmlspecialchars($d['name']) ?><?= ((int)$d['is_active']===1?'':' (inactive)') ?></option>
          <?php endforeach; ?>
        </select>

        <label style="display:flex; align-items:center; gap:8px; margin-top:10px;">
          <input type="checkbox" id="edit_active" name="edit_active"> Active
        </label>
      </div>
      <div class="foot">
        <button type="button" class="btn ghost" data-close="#modalEditLoc">Cancel</button>
        <button type="submit" class="btn">Save Changes</button>
      </div>
    </form>
  </div>
</div>

<!-- ===== Modal: Add District ===== -->
<div class="modal" id="modalAddDist" aria-hidden="true">
  <div class="panel">
    <div class="head">Add District</div>
    <form method="post">
      <div class="body">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">
        <input type="hidden" name="action" value="add_district">

        <label for="add_district_name" style="display:block; margin-bottom:6px;">District Name</label>
        <input class="input" type="text" name="district_name" id="add_district_name" maxlength="120" required>

        <label style="display:flex; align-items:center; gap:8px; margin-top:10px;">
          <input type="checkbox" name="district_active" checked> Active
        </label>
      </div>
      <div class="foot">
        <button type="button" class="btn ghost" data-close="#modalAddDist">Cancel</button>
        <button type="submit" class="btn">Add</button>
      </div>
    </form>
  </div>
</div>

<!-- ===== Modal: Edit District ===== -->
<div class="modal" id="modalEditDist" aria-hidden="true">
  <div class="panel">
    <div class="head">Edit District</div>
    <form method="post">
      <div class="body">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">
        <input type="hidden" name="action" value="update_district">
        <input type="hidden" name="edit_district_id" id="edit_district_id">

        <label for="edit_district_name" style="display:block; margin-bottom:6px;">District Name</label>
        <input class="input" type="text" name="edit_district_name" id="edit_district_name" maxlength="120" required>

        <label style="display:flex; align-items:center; gap:8px; margin-top:10px;">
          <input type="checkbox" id="edit_district_active" name="edit_district_active"> Active
        </label>
      </div>
      <div class="foot">
        <button type="button" class="btn ghost" data-close="#modalEditDist">Cancel</button>
        <button type="submit" class="btn">Save Changes</button>
      </div>
    </form>
  </div>
</div>

<script>
  // Simple modal open/close
  function openModal(sel){ const m=document.querySelector(sel); if(m){ m.classList.add('open'); } }
  function closeModal(sel){ const m=document.querySelector(sel); if(m){ m.classList.remove('open'); } }
  document.getElementById('btnOpenAddLocation')?.addEventListener('click', ()=> openModal('#modalAddLoc'));
  document.getElementById('btnOpenAddDistrict')?.addEventListener('click', ()=> openModal('#modalAddDist'));
  document.querySelectorAll('[data-close]')?.forEach(btn=>{
    btn.addEventListener('click', ()=> closeModal(btn.getAttribute('data-close')));
  });
  document.querySelectorAll('.modal').forEach(m=>{
    m.addEventListener('click', e=>{ if(e.target===m){ m.classList.remove('open'); } });
  });

  // Populate Edit Location modal
  document.querySelectorAll('[data-edit]').forEach(btn=>{
    btn.addEventListener('click', ()=>{
      const id = btn.getAttribute('data-id');
      const name = btn.getAttribute('data-name');
      const active = btn.getAttribute('data-active') === '1';
      const districtId = btn.getAttribute('data-district-id') || '';

      document.getElementById('edit_location_id').value = id;
      document.getElementById('edit_location_name').value = name;
      document.getElementById('edit_active').checked = active;
      const sel = document.getElementById('edit_location_district_id'); // <- id baharu, elak clash
      if (sel) sel.value = districtId; // '' will select "-- None --"
      openModal('#modalEditLoc');
    });
  });

  // Populate Edit District modal
  document.querySelectorAll('[data-edit-district]').forEach(btn=>{
    btn.addEventListener('click', ()=>{
      const id = btn.getAttribute('data-id');
      const name = btn.getAttribute('data-name');
      const active = btn.getAttribute('data-active') === '1';

      document.getElementById('edit_district_id').value = id; // hidden input (unik)
      document.getElementById('edit_district_name').value = name;
      document.getElementById('edit_district_active').checked = active;
      openModal('#modalEditDist');
    });
  });

  // Filters
  (function(){
    const input = document.getElementById('locationFilter');
    const rows  = document.querySelectorAll('#locationTable tbody tr');
    if (!input || !rows.length) return;
    input.addEventListener('input', function(){
      const q = this.value.trim().toLowerCase();
      rows.forEach(tr=>{
        const key = (tr.getAttribute('data-key') || '');
        tr.style.display = key.includes(q) ? '' : 'none';
      });
    });
  })();
  (function(){
    const input = document.getElementById('districtFilter');
    const rows  = document.querySelectorAll('#districtTable tbody tr');
    if (!input || !rows.length) return;
    input.addEventListener('input', function(){
      const q = this.value.trim().toLowerCase();
      rows.forEach(tr=>{
        const key = (tr.getAttribute('data-key') || '');
        tr.style.display = key.includes(q) ? '' : 'none';
      });
    });
  })();
</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
