<?php
include("../includes/auth.php");
include("../config/db.php");

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

if (isset($_POST['submit'])) {

    $name = $_POST['name'];
    $mobile = $_POST['mobile'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $village_id = $_POST['village_id'];

    $conn->query("
        INSERT INTO users (name, mobile, password, role, village_id, status)
        VALUES ('$name', '$mobile', '$password', 'village_admin', '$village_id', 'approved')
    ");

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

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

<h3>Add Village Admin</h3>

<form method="POST">

<div class="row">

<div class="col-md-6">
    <label>Name</label>
    <input type="text" name="name" class="form-control" required>
</div>

<div class="col-md-6">
    <label>Mobile</label>
    <input type="text" name="mobile" class="form-control" required>
</div>

<div class="col-md-6 mt-3">
    <label>Password</label>
    <input type="password" name="password" class="form-control" required>
</div>

<div class="col-md-6 mt-3">
    <label>Confirm Password</label>
    <input type="password" name="confirm_password" class="form-control" required>
</div>

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

<div class="col-md-4 mt-3">
    <label>Block</label>
    <select id="block" class="form-control"></select>
</div>

<div class="col-md-4 mt-3">
    <label>Village</label>
    <select name="village_id" id="village" class="form-control"></select>
</div>

</div>

<br>
<button name="submit" class="btn btn-success">Create Admin</button>

</form>

<script>
document.getElementById('district').addEventListener('change', function() {
    fetch('../villages/get_blocks.php?district=' + this.value)
    .then(res => res.text())
    .then(data => document.getElementById('block').innerHTML = data);
});

document.getElementById('block').addEventListener('change', function() {
    fetch('get_villages.php?block_id=' + this.value)
    .then(res => res.text())
    .then(data => document.getElementById('village').innerHTML = data);
});
</script>

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