<?php

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

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


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

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

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

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

if($village_id == 0)
{
echo "<script>alert('Please select village');</script>";
exit;
}
}

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

$image="";

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

$target_dir="../../uploads/thoughts/";

if(!is_dir($target_dir))
{
mkdir($target_dir,0777,true);
}

$ext = pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION);

$image="thought_".time().rand(100,999).".".$ext;

move_uploaded_file($_FILES['image']['tmp_name'],$target_dir.$image);

}

mysqli_query($conn,"
INSERT INTO village_people_thoughts
(village_id,name,description,image)
VALUES
('$village_id','$name','$description','$image')
");

echo "<script>alert('Thought Added Successfully');</script>";

}

?>

<div class="main">

<h2>Add People Thought</h2>

<div class="form-box">

<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 ORDER BY district_name");

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>Name</label>
<input type="text" name="name" class="form-control" required>

<label>Description</label>
<textarea name="description" class="form-control" rows="5"></textarea>

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

<br>

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

</form>

</div>

</div>

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


<script>

/* LOAD BLOCKS */

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

var district_id=this.value;

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

.then(res=>res.text())

.then(data=>{

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

});

});


/* LOAD VILLAGES */

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

var block_id=this.value;

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

.then(res=>res.text())

.then(data=>{

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

});

});

</script>