<?php

include "../../config/master.php";
allowRoles([1,5]);

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

$role_id = $_SESSION['role_id'] ?? 0;

/* DEFAULT VILLAGE */

if($role_id == 1){
$village_id = $_POST['village_id'] ?? 0;
}else{
$village_id = $_SESSION['village_id'];
}

/* SAVE CATEGORY */

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

if($role_id == 1){
$village_id = $_POST['village_id'];
}

$category_name = mysqli_real_escape_string($conn,$_POST['category_name']);

/* IMAGE UPLOAD */

$image="";

if(!empty($_FILES['image']['name'])){

$filename = time().'_'.$_FILES['image']['name'];

move_uploaded_file(
$_FILES['image']['tmp_name'],
"../../uploads/gallery/".$filename
);

$image = $filename;

}

/* INSERT */

mysqli_query($conn,"
INSERT INTO gallery_categories
(village_id,category_name,image)
VALUES
('$village_id','$category_name','$image')
");

echo "<script>alert('Category Created');</script>";

}

?>

<div class="main">

<h2>Create Gallery Category</h2>

<form method="post" enctype="multipart/form-data">

<?php if($role_id == 1){ ?>

<label>District</label>
<select id="district" class="form-control">

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

<?php
$dq=mysqli_query($conn,"SELECT * FROM districts");
while($d=mysqli_fetch_assoc($dq)){
?>

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

<?php } ?>

</select>


<label>Block</label>
<select id="block" class="form-control">
<option value="">Select Block</option>
</select>


<label>Village</label>
<select name="village_id" id="village" class="form-control" required>
<option value="">Select Village</option>
</select>

<?php } ?>


<label>Category Name</label>
<input type="text" name="category_name" class="form-control" required>


<label>Category Image</label>
<input type="file" name="image" class="form-control">

<br>

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

</form>

</div>

<script>

document.addEventListener("DOMContentLoaded", function(){

const district = document.getElementById("district");
const block = document.getElementById("block");
const village = document.getElementById("village");

/* DISTRICT → BLOCK */

if(district){

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

let district_id = this.value;

fetch("get_blocks.php?district_id=" + district_id)

.then(response => response.text())

.then(data => {

block.innerHTML = data;
village.innerHTML = "<option value=''>Select Village</option>";

});

});

}

/* BLOCK → VILLAGE */

if(block){

block.addEventListener("change", function(){

let block_id = this.value;

fetch("get_villages.php?block_id=" + block_id)

.then(response => response.text())

.then(data => {

village.innerHTML = data;

});

});

}

});

</script>

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