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

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

$id = $_GET['id'];

$data = $conn->query("SELECT * FROM villages WHERE id=$id")->fetch_assoc();
$districts = $conn->query("SELECT * FROM districts");

// blocks for selected district
$blocks = $conn->query("
    SELECT blocks.* FROM blocks
    LEFT JOIN districts ON blocks.district_id = districts.id
    WHERE districts.name = '".$data['district']."'
");

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

    $conn->query("UPDATE villages 
                  SET village_name='$village_name', district='$district', block_id='$block_id'
                  WHERE id=$id");

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

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

<h3>Edit Village</h3>

<form method="POST">

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

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

    <div class="mb-3">
        <label>Block</label>
        <select name="block_id" id="block" class="form-control">
            <?php while($b = $blocks->fetch_assoc()) { ?>
                <option value="<?= $b['id'] ?>" <?= ($b['id'] == $data['block_id']) ? 'selected' : '' ?>>
                    <?= $b['name'] ?>
                </option>
            <?php } ?>
        </select>
    </div>

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

<script>
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"); ?>