<?php

include "../../config/master.php";

/* Only Super Admin can access */
allowRoles([1]);

include "../layout/header.php";
include "../layout/sidebar.php";

/* FETCH DISTRICTS */
$districts = mysqli_query($conn,"SELECT * FROM districts");

/* ADD VILLAGE */

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

$village_name = trim($_POST['village_name']);
$district_id  = intval($_POST['district_id']);
$block_id     = intval($_POST['block_id']);
$pincode      = trim($_POST['pincode']);

$state_id = 1;   // default state (Haryana)

/* CREATE SLUG */

$slug = strtolower($village_name);
$slug = preg_replace('/[^a-z0-9]+/','-',$slug);
$slug = trim($slug,'-');

/* CHECK IF SLUG ALREADY EXISTS */

$check = mysqli_query($conn,"SELECT id FROM villages WHERE slug='$slug'");

if(mysqli_num_rows($check) > 0)
{
$slug = $slug."-".time();
}

/* ESCAPE INPUTS */

$village_name = mysqli_real_escape_string($conn,$village_name);
$pincode      = mysqli_real_escape_string($conn,$pincode);

/* INSERT QUERY */

$insert = mysqli_query($conn,"INSERT INTO villages
(state_id,district_id,block_id,village_name,slug,pincode)
VALUES
('$state_id','$district_id','$block_id','$village_name','$slug','$pincode')");

if($insert)
{
echo "<script>alert('Village Added Successfully');</script>";
}
else
{
echo "<script>alert('Error adding village');</script>";
}

}

?>

<div class="main">

<h2>Add Village</h2>

<form method="POST" class="form-box">

<label>Village Name</label>
<input type="text" name="village_name" placeholder="Enter Village Name" required>

<label>Select District</label>
<select name="district_id" id="district" required>

<option value="">Select District</option>

<?php while($d=mysqli_fetch_assoc($districts)) { ?>

<option value="<?php echo $d['id']; ?>">
<?php echo $d['district_name']; ?>
</option>

<?php } ?>

</select>

<label>Select Block</label>

<select name="block_id" id="block" required>
<option value="">Select Block</option>
</select>

<label>Pincode</label>

<input type="text" name="pincode" placeholder="Enter Pincode">

<button type="submit" name="add" class="btn-save">Add Village</button>

</form>

</div>

<script>

document.getElementById("district").addEventListener("change", function(){

var district_id = this.value;

fetch("get_blocks.php?district_id="+district_id)
.then(response => response.text())
.then(data => {

document.getElementById("block").innerHTML = data;

});

});

</script>

<?php include "../layout/footer.php"; ?>