<?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'] ?? '')));
        $district_id = strtoupper(trim((string)($_POST['district_id'] ?? '')));
        $name = trim((string)($_POST['name'] ?? ''));

        if ($id === '' || $district_id === '' || $name === '') {
            $error = "Block ID, District, and Name are required.";
        } else {
            try {
                $st = $pdo->prepare("INSERT INTO blocks (id, district_id, name) VALUES (?, ?, ?)");
                $st->execute([$id, $district_id, $name]);
                $success = "Block added.";
            } catch (Throwable $e) {
                $error = "Block ID already exists or district 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 !== '') {
            try {
                $st = $pdo->prepare("DELETE FROM blocks WHERE id=?");
                $st->execute([$id]);
                $success = "Block deleted.";
            } catch (Throwable $e) {
                $error = "Cannot delete. Some GPs/Visits are linked to this block.";
            }
        }
    }
}

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

$rows = $pdo->query("
  SELECT b.id, b.name, b.district_id, d.name AS district_name
  FROM blocks b
  LEFT JOIN districts d ON d.id = b.district_id
  ORDER BY d.name ASC, b.name ASC
")->fetchAll();

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

<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h5 class="mb-0">Blocks</h5>
    <div class="text-muted small">Add / Manage Blocks (District wise)</div>
  </div>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-dark btn-sm" href="/school-crm/public/admin/districts.php">Districts</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 Block</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-3">
      <label class="form-label">Block ID (e.g. CH1)</label>
      <input class="form-control" name="id" required data-uppercase>
    </div>

    <div class="col-12 col-md-4">
      <label class="form-label">District</label>
      <select class="form-select" name="district_id" required>
        <option value="">Select District</option>
        <?php foreach ($districts as $d): ?>
          <option value="<?= htmlspecialchars($d['id']) ?>"><?= htmlspecialchars($d['name']) ?> (<?= htmlspecialchars($d['id']) ?>)</option>
        <?php endforeach; ?>
      </select>
    </div>

    <div class="col-12 col-md-5">
      <label class="form-label">Block Name</label>
      <input class="form-control" name="name" required data-uppercase>
    </div>

    <div class="col-12 d-grid d-md-flex justify-content-md-end">
      <button class="btn btn-dark px-4">Save</button>
    </div>
  </form>
</div>

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

  <div class="table-responsive">
    <table class="table table-striped align-middle mb-0">
      <thead>
        <tr>
          <th>Block ID</th>
          <th>Block Name</th>
          <th>District</th>
          <th class="text-end">Action</th>
        </tr>
      </thead>
      <tbody>
      <?php if (!$rows): ?>
        <tr><td colspan="4" class="text-muted">No blocks 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><?= htmlspecialchars($r['district_name'] ?? '-') ?> (<?= htmlspecialchars($r['district_id'] ?? '-') ?>)</td>
          <td class="text-end">
            <form method="post" class="d-inline" onsubmit="return confirm('Delete this block?');">
              <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"; ?>
