<?php
include("config.php");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $district_name = trim($_POST['district_name']);
    $district_id = $_POST['district_id'] ?? null;

    if ($district_name !== '') {
        if ($district_id) {
            $stmt = $conn->prepare("UPDATE tbl_district SET district_name=? WHERE district_id=?");
            $stmt->bind_param("si", $district_name, $district_id);
        } else {
            $stmt = $conn->prepare("INSERT INTO tbl_district (district_name) VALUES (?)");
            $stmt->bind_param("s", $district_name);
        }
        $stmt->execute();
        $stmt->close();
    }
    header("Location: index.php?page=districts");
    exit();
}

if (isset($_GET['delete'])) {
    $delete_id = (int)$_GET['delete'];
    $conn->query("DELETE FROM tbl_district WHERE district_id = $delete_id");
    header("Location: index.php?page=districts");
    exit();
}

$edit_district = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $result = $conn->query("SELECT * FROM tbl_district WHERE district_id = $edit_id");
    $edit_district = $result->fetch_assoc();
}

$result = $conn->query("SELECT * FROM tbl_district ORDER BY district_id DESC");
?>

<h2>Manage Districts</h2>

<form method="post" class="mb-4">
    <input type="hidden" name="district_id" value="<?= $edit_district['district_id'] ?? '' ?>">
    <div class="mb-3">
        <label>District Name</label>
        <input type="text" name="district_name" class="form-control" required value="<?= $edit_district['district_name'] ?? '' ?>">
    </div>
    <button type="submit" class="btn btn-primary"><?= $edit_district ? 'Update' : 'Add' ?> District</button>
    <?php if ($edit_district): ?>
        <a href="index.php?page=districts" class="btn btn-secondary">Cancel</a>
    <?php endif; ?>
</form>

<table class="table table-bordered">
    <thead>
        <tr>
            <th>ID</th>
            <th>District Name</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php while ($row = $result->fetch_assoc()): ?>
        <tr>
            <td><?= $row['district_id'] ?></td>
            <td><?= $row['district_name'] ?></td>
            <td>
                <a href="index.php?page=districts&edit=<?= $row['district_id'] ?>" class="btn btn-sm btn-warning">Edit</a>
                <a href="index.php?page=districts&delete=<?= $row['district_id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this district?');">Delete</a>
            </td>
        </tr>
        <?php endwhile; ?>
    </tbody>
</table>