<?php

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

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

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

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

/* ADD VILLAGE */

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

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

$state_id = 1;

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

$check = mysqli_query($conn,"SELECT id FROM villages WHERE slug='$slug'");
if(mysqli_num_rows($check) > 0){
$slug = $slug."-".time();
}

/* ESCAPE */
$village_name = mysqli_real_escape_string($conn,$village_name);
$village_name_hi = mysqli_real_escape_string($conn,$village_name_hi);
$pincode = mysqli_real_escape_string($conn,$pincode);

/* INSERT */

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

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

}
?>

<div class="main">

<h2>Add Village</h2>

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

<label>Village Name (English)</label>
<input type="text" name="village_name" required>

<label>Village Name (Hindi)</label>
<input type="text" name="village_name_hi">

<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">

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

</form>

</div>

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

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