<?php

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

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

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

/* ===== AJAX SAVE ===== */
if(isset($_POST['ajax_save']))
{

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

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

$image="";

/* IMAGE UPLOAD */
if(isset($_FILES['image']) && $_FILES['image']['error'] == 0){

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

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

$ext = strtolower(pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION));
$allowed = ['jpg','jpeg','png','webp'];

if(in_array($ext,$allowed)){
$image="dev_".time().rand(100,999).".".$ext;
move_uploaded_file($_FILES['image']['tmp_name'],$target_dir.$image);
}
}

/* INSERT */
mysqli_query($conn,"
INSERT INTO village_development_works
(village_id,title,description,status,image)
VALUES
('$village_id','$title','$description','$status','$image')
");

header('Content-Type: application/json');
echo json_encode(["status"=>"success"]);
exit;

}

/* NORMAL PAGE */
include "../layout/header.php";
?>

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

<h2 class="mb-4">Add Development Work</h2>

<!-- 🔥 MESSAGE -->
<div id="msgBox" style="margin-bottom:10px;"></div>

<div class="form-box">

<form id="devForm" 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"></select>

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

<?php } ?>

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

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

<label>Status</label>
<select name="status" class="form-control">
<option value="Planned">Planned</option>
<option value="In Progress">In Progress</option>
<option value="Completed">Completed</option>
</select>

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

<!-- PREVIEW -->
<img id="preview" style="width:100%;margin-top:10px;border-radius:10px;display:none;">

<!-- PROGRESS -->
<div id="progressBox" style="display:none;margin-top:10px;">
<div style="background:#eee;border-radius:10px;">
<div id="progressBar" style="width:0%;background:#28a745;color:#fff;text-align:center;padding:4px;">
0%
</div>
</div>
</div>

<br>

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

</form>

</div>

</div>
</div>

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

<script>

/* IMAGE COMPRESS + PREVIEW */
let compressedFile=null;

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

let file=this.files[0];
if(!file) return;

let preview=document.getElementById("preview");
preview.src=URL.createObjectURL(file);
preview.style.display="block";

let img=new Image();
img.src=URL.createObjectURL(file);

img.onload=function(){

let canvas=document.createElement("canvas");
let ctx=canvas.getContext("2d");

let maxWidth=800;
let scale=maxWidth/img.width;

canvas.width=maxWidth;
canvas.height=img.height*scale;

ctx.drawImage(img,0,0,canvas.width,canvas.height);

canvas.toBlob(function(blob){
compressedFile=new File([blob],file.name,{type:"image/jpeg"});
},"image/jpeg",0.7);

};

});

/* AJAX SUBMIT */
document.getElementById("devForm").addEventListener("submit",function(e){

e.preventDefault();

let formData=new FormData(this);

if(compressedFile){
formData.set("image",compressedFile);
}

formData.append("ajax_save","1");

let xhr=new XMLHttpRequest();
xhr.open("POST","",true);

let progressBox=document.getElementById("progressBox");
let progressBar=document.getElementById("progressBar");
let msgBox=document.getElementById("msgBox");

xhr.upload.onprogress=function(e){
if(e.lengthComputable){
let percent=Math.round((e.loaded/e.total)*100);
progressBox.style.display="block";
progressBar.style.width=percent+"%";
progressBar.innerHTML=percent+"%";
}
};

xhr.onload=function(){

try{
let res=JSON.parse(xhr.responseText);

if(res.status==="success"){

msgBox.innerHTML=`<div style="background:#d4edda;color:#155724;padding:12px;border-radius:8px;">
✅ Development Work Added Successfully
</div>`;

window.scrollTo({top:0,behavior:"smooth"});

document.getElementById("devForm").reset();
document.getElementById("preview").style.display="none";
progressBar.style.width="0%";

}else{
throw "error";
}

}catch(e){

msgBox.innerHTML=`<div style="background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;">
❌ Something went wrong
</div>`;

}

};

xhr.send(formData);

});

/* DISTRICT → BLOCK */
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;
document.getElementById("village").innerHTML="";
});
});

/* BLOCK → VILLAGE */
document.getElementById("block")?.addEventListener("change",function(){
fetch("get_villages.php?block_id="+this.value)
.then(res=>res.text())
.then(data=>{
document.getElementById("village").innerHTML=data;
});
});

</script>