<?php
session_start();
if (!isset($_SESSION['admin'])) {
    header("Location: ../auth/login.php");
    exit;
}

include("../config/db.php");

$id = $_GET['id'];

// fetch block
$data = $conn->query("SELECT * FROM blocks WHERE id=$id")->fetch_assoc();

// fetch districts
$districts = $conn->query("SELECT * FROM districts");

if (isset($_POST['update'])) {
    $name = $_POST['name'];
    $district_id = $_POST['district_id'];

    $conn->query("UPDATE blocks SET name='$name', district_id='$district_id' WHERE id=$id");
    header("Location: index.php");
}
?>

<?php include("../includes/header.php"); ?>
<?php include("../includes/sidebar.php"); ?>

<h3>Edit Block</h3>

<form method="POST">
    <div class="mb-3">
        <label>Block Name</label>
        <input type="text" name="name" class="form-control" value="<?= $data['name'] ?>" required>
    </div>

    <div class="mb-3">
        <label>Select District</label>
        <select name="district_id" class="form-control" required>
            <?php while($d = $districts->fetch_assoc()) { ?>
                <option value="<?= $d['id'] ?>" <?= ($d['id'] == $data['district_id']) ? 'selected' : '' ?>>
                    <?= $d['name'] ?>
                </option>
            <?php } ?>
        </select>
    </div>

    <button name="update" class="btn btn-primary">Update</button>
</form>

<?php include("../includes/footer.php"); ?>