<?php

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

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

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

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

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

$image="";

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

$dir="../../uploads/gallery/";

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

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

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

/* INSERT */
mysqli_query($conn,"
INSERT INTO gallery_images
(village_id,category_id,title,image)
VALUES
('$village_id','$category_id','$title','$image')
");

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

}

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

/* HIDE SIDEBAR */
echo "<style>
.sidebar{display:none !important;}
.topbar{margin-left:0 !important;}
.main{margin-left:0 !important;padding-bottom:80px;}
</style>";
?>

<div class="app-content">

<div class="card-box">
<h4>Add Gallery Image</h4>
<p style="font-size:12px;color:#777;">Upload village image</p>
</div>

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

<div class="card-box">

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

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

<?php } ?>

<label>Category</label>
<select name="category_id" id="category" class="form-control" required>
<option value="">Select Category</option>

<?php
if($role_id != 1){
$c=mysqli_query($conn,"SELECT * FROM gallery_categories WHERE village_id='$village_id'");
while($row=mysqli_fetch_assoc($c)){
?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['category_name']; ?>
</option>
<?php }} ?>
</select>

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

<label>Upload Image</label>

<label style="
display:block;
background:#3498db;
color:#fff;
padding:12px;
border-radius:8px;
text-align:center;
cursor:pointer;
">
📁 Select Image
<input type="file" name="image" id="fileInput" accept="image/*" required style="display:none;">
</label>

<!-- 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-mobile" style="background:#27ae60;color:#fff;">
Upload Image
</button>

</form>

</div>
</div>

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

<script>

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

document.getElementById("fileInput").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("galleryForm").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;">
✅ Image Uploaded Successfully
</div>`;

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

document.getElementById("galleryForm").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;">
❌ Upload failed. Try again.
</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;
});
});

/* 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;
});
});

/* VILLAGE → CATEGORY */
document.getElementById("village")?.addEventListener("change",function(){
fetch("get_gallery_categories.php?village_id="+this.value)
.then(res=>res.text())
.then(data=>{
document.getElementById("category").innerHTML=data;
});
});

</script>