<?php
declare(strict_types=1);

require_once __DIR__ . "/../../config/db.php";
require_once __DIR__ . "/../../config/auth.php";

require_admin();

$success = "";
$error = "";

// Create
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    if (!csrf_validate($_POST['csrf'] ?? '')) {
        $error = "Invalid request.";
    } else {
        $id = strtoupper(trim((string)($_POST['id'] ?? '')));
        $name = trim((string)($_POST['name'] ?? ''));

        if ($id === '' || $name === '') {
            $error = "District ID and Name are required.";
        } else {
            try {
                $st = $pdo->prepare("INSERT INTO districts (id, name) VALUES (?, ?)");
                $st->execute([$id, $name]);
                $success = "District added.";
            } catch (Throwable $e) {
                $error = "District ID already exists or invalid.";
            }
        }
    }
}

// Delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete') {
  if (!csrf_validate($_POST['csrf'] ?? '')) {
    $error = "Invalid request.";
  } else {
    $id = strtoupper(trim((string)($_POST['id'] ?? '')));
    if ($id !== '') {
      // Check if any blocks belong to this district
      $st = $pdo->prepare("SELECT COUNT(*) FROM blocks WHERE district_id = ?");
      $st->execute([$id]);
      $count = (int)($st->fetchColumn() ?? 0);
      if ($count > 0) {
        $error = "Cannot delete district: there are blocks assigned to this district.";
      } else {
        try {
          $st = $pdo->prepare("DELETE FROM districts WHERE id=?");
          $st->execute([$id]);
          $success = "District deleted.";
        } catch (Throwable $e) {
          $error = "Delete failed. Please try again.";
        }
      }
    }
  }
}

$rows = $pdo->query("SELECT id, name FROM districts ORDER BY name ASC")->fetchAll();

$page_title = "Admin - Districts";
require_once __DIR__ . "/../partials/header.php";
?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h5 class="mb-0">Districts</h5>
    <div class="text-muted small">Add / Manage Districts</div>
  </div>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-dark btn-sm" href="/school-crm/public/admin/blocks.php">Blocks</a>
    <a class="btn btn-outline-dark btn-sm" href="/school-crm/public/admin/gps.php">GPs</a>
  </div>
</div>

<?php if ($success): ?><div class="alert alert-success py-2"><?= htmlspecialchars($success) ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-danger py-2"><?= htmlspecialchars($error) ?></div><?php endif; ?>

<div class="card card-soft shadow-soft p-3 p-md-4 mb-3">
  <h6 class="mb-3">Add District</h6>
  <form method="post" class="row g-3">
    <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
    <input type="hidden" name="action" value="create">

    <div class="col-12 col-md-4">
      <label class="form-label">District ID (e.g. MALDA)</label>
      <input class="form-control" name="id" required data-uppercase>
    </div>
    <div class="col-12 col-md-6">
      <label class="form-label">District Name</label>
      <input class="form-control" name="name" required data-uppercase>
    </div>
    <div class="col-12 col-md-2 d-grid d-md-flex align-items-end">
      <button class="btn btn-dark w-100">Save</button>
    </div>
  </form>
</div>

<div class="card card-soft shadow-soft p-3 p-md-4">
  <h6 class="mb-3">District List</h6>

  <div class="table-responsive">
    <table class="table table-striped align-middle mb-0">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th class="text-end">Action</th>
        </tr>
      </thead>
      <tbody>
      <?php if (!$rows): ?>
        <tr><td colspan="3" class="text-muted">No districts yet</td></tr>
      <?php endif; ?>

      <?php foreach ($rows as $r): ?>
        <tr>
          <td class="text-nowrap fw-semibold"><?= htmlspecialchars($r['id']) ?></td>
          <td><?= htmlspecialchars($r['name']) ?></td>
          <td class="text-end">
            <form method="post" class="d-inline" onsubmit="return confirm('Delete this district?');">
              <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?= htmlspecialchars($r['id']) ?>">
              <button class="btn btn-sm btn-outline-danger">Delete</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<?php require_once __DIR__ . "/../partials/footer.php"; ?>
