<?php

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

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

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

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

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

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

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

$image="";

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

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

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

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

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

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

mysqli_query($conn,"
INSERT INTO village_news
(village_id,title,news_date,image,description)
VALUES
('$village_id','$title','$news_date','$image','$description')
");

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

}

?>

<div class="main">
<div class="container-fluid">

<h2>Add News</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>Select Block</option>
</select>


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

<?php } ?>


<label>News Title</label>
<input type="text" name="title" class="form-control" required>


<label>News Date</label>
<input type="date" name="news_date" class="form-control">


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


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

<br>

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

</form>

</div>
</div>

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

<script>

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

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

if(district){

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

fetch("get_blocks.php?district_id="+this.value)
.then(res=>res.text())
.then(data=>{
block.innerHTML=data;
village.innerHTML="<option>Select Village</option>";
});

});

}

if(block){

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

fetch("get_villages.php?block_id="+this.value)
.then(res=>res.text())
.then(data=>{
village.innerHTML=data;
});

});

}

});

</script>