<?php

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

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

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

$building_name = mysqli_real_escape_string($conn,$_POST['building_name']);
$building_type = mysqli_real_escape_string($conn,$_POST['building_type']);
$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_govt_buildings WHERE id='$id'"));
$image = $data['image'];

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

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

if(!empty($image) && file_exists($target_dir.$image)){
unlink($target_dir.$image);
}

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

mysqli_query($conn,"
UPDATE village_govt_buildings SET
building_name='$building_name',
building_type='$building_type',
location='$location',
description='$description',
image='$image'
WHERE id='$id'
");

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

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

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

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

<h2>Edit Building</h2>

<div id="msgBox"></div>

<form id="editForm">

<input type="text" name="building_name" value="<?php echo $data['building_name']; ?>" class="form-control" required>
<input type="text" name="building_type" value="<?php echo $data['building_type']; ?>" class="form-control">
<input type="text" name="location" value="<?php echo $data['location']; ?>" class="form-control">

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

<img id="preview" style="width:100%;display:none;">

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

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

</form>

</div>
</div>

<script>
let compressedFile=null;

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

let file=this.files[0];
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"});
});
};
});

document.getElementById("editForm").addEventListener("submit",function(e){

e.preventDefault();

let formData=new FormData(this);

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

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

fetch("",{method:"POST",body:formData})
.then(res=>res.json())
.then(res=>{
document.getElementById("msgBox").innerHTML="✅ Updated successfully";
});
});
</script>

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