<?php

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

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

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

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

$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']);

$image = "";

/* IMAGE UPLOAD */
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)){
        $image = "chaupal_".time().rand(100,999).".".$ext;
        move_uploaded_file($_FILES['image']['tmp_name'],$target_dir.$image);
    }
}

/* INSERT */
mysqli_query($conn,"
INSERT INTO village_chaupals
(village_id,chaupal_name,location,image,description)
VALUES
('$village_id','$chaupal_name','$location','$image','$description')
");

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

}

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

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

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

<div class="form-box">

<form id="chaupalForm" 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 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">
<option value="">Select Block</option>
</select>

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

<?php } ?>

<label>Chaupal Name</label>
<input type="text" name="chaupal_name" class="form-control" required>

<label>Location</label>
<input type="text" name="location" class="form-control">

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

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

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

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

<br>

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

</form>

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

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

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

<script>
document.addEventListener("DOMContentLoaded", function(){

/* DISTRICT → BLOCK → VILLAGE */
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;
});
});
}

/* IMAGE COMPRESS + PREVIEW */
const imageInput = document.getElementById("imageInput");
const preview = document.getElementById("preview");

let compressedFile = null;

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

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

/* PREVIEW */
preview.src = URL.createObjectURL(file);
preview.style.display = "block";

/* COMPRESS */
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 */
const form = document.getElementById("chaupalForm");
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);

/* USE COMPRESSED IMAGE */
if(compressedFile){
formData.set("image", compressedFile);
}

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

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

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

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 added successfully!
</div>`;

form.reset();
preview.style.display="none";
progressBar.style.width="0%";

}else{
throw "error";
}

}catch(e){

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

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

}

};

xhr.send(formData);

});

});
</script>