<?php

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

$id = $_GET['id'] ?? 0;

/* ===== AJAX UPDATE (BEFORE HEADER) ===== */
if(isset($_POST['ajax_update']))
{

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

$data = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM village_chaupals WHERE id='$id'"));

$image = $data['image'];

/* IMAGE UPDATE */
if(isset($_FILES['image']) && $_FILES['image']['error'] == 0)
{
$target_dir="../../uploads/chaupals/";

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)){

/* DELETE OLD IMAGE */
if(!empty($image) && file_exists($target_dir.$image)){
unlink($target_dir.$image);
}

$image="chaupal_".time().rand(100,999).".".$ext;
move_uploaded_file($_FILES['image']['tmp_name'],$target_dir.$image);
}
}

/* UPDATE */
mysqli_query($conn,"
UPDATE village_chaupals SET
chaupal_name='$chaupal_name',
location='$location',
description='$description',
image='$image'
WHERE id='$id'
");

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

}

/* ===== NORMAL LOAD ===== */
$data = mysqli_fetch_assoc(mysqli_query($conn,"
SELECT * FROM village_chaupals WHERE id='$id'
"));

if(!$data){
echo "<script>alert('Invalid Chaupal');window.location='chaupals.php';</script>";
exit;
}

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

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

<h2 class="mb-4">Edit Chaupal</h2>

<div class="form-box">

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

<label>Chaupal Name</label>
<input type="text" name="chaupal_name" class="form-control"
value="<?php echo $data['chaupal_name']; ?>" required>

<label>Location</label>
<input type="text" name="location" class="form-control"
value="<?php echo $data['location']; ?>">

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

<!-- OLD IMAGE -->
<?php if(!empty($data['image'])){ ?>
<br>
<img src="../../uploads/chaupals/<?php echo $data['image']; ?>" 
style="width:100%;max-height:180px;border-radius:8px;">
<?php } ?>

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

<!-- 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>

<label>Description</label>
<textarea name="description" class="form-control"><?php echo $data['description']; ?></textarea>

<br>

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

</form>

<div id="msgBox" style="margin-top:10px;"></div>

</div>
</div>
</div>

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

<script>

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

const imageInput = document.getElementById("imageInput");
const preview = document.getElementById("preview");

let compressedFile = null;

/* IMAGE PREVIEW + COMPRESS */
imageInput.addEventListener("change", function(){

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

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 UPDATE */
const form = document.getElementById("editForm");
const progressBox = document.getElementById("progressBox");
const progressBar = document.getElementById("progressBar");
const msgBox = document.getElementById("msgBox");

form.addEventListener("submit", function(e){

e.preventDefault();

let formData = new FormData(form);

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

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

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

/* PROGRESS */
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 + "%";
}
};

/* RESPONSE */
xhr.onload = function(){

let text = xhr.responseText.trim();

try{

let res = JSON.parse(text);

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

msgBox.innerHTML = `
<div style="background:#d4edda;color:#155724;padding:10px;border-radius:6px;">
✅ Chaupal updated successfully!
</div>`;

}else{
throw "error";
}

}catch(e){

console.log("Server Response:", text);

msgBox.innerHTML = `
<div style="background:#f8d7da;color:#721c24;padding:10px;border-radius:6px;">
❌ Update failed. Try again.
</div>`;

}

};

xhr.send(formData);

});

});

</script>