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

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

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

if (isset($_POST['submit'])) {
    $village_name = $_POST['village_name'];
    $district = $_POST['district'];
    $block_id = $_POST['block_id'];

    $conn->query("INSERT INTO villages (village_name, district, block_id) 
                  VALUES ('$village_name', '$district', '$block_id')");

    header("Location: index.php");
}
?>

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

<h3>Add Village</h3>

<form method="POST">

    <div class="mb-3">
        <label>Village Name</label>
        <input type="text" name="village_name" class="form-control" required>
    </div>

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

    <div class="mb-3">
        <label>Select Block</label>
        <select name="block_id" id="block" class="form-control" required>
            <option value="">-- Select Block --</option>
        </select>
    </div>

    <button name="submit" class="btn btn-success">Save</button>
</form>

<script>
// LOAD BLOCKS BASED ON DISTRICT
document.getElementById('district').addEventListener('change', function() {
    let district = this.value;

    fetch('get_blocks.php?district=' + district)
        .then(res => res.text())
        .then(data => {
            document.getElementById('block').innerHTML = data;
        });
});
</script>

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