<?php

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

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


$role_id = $_SESSION['role_id'] ?? 0;
$id = intval($_GET['id'] ?? 0);

/* ==========================
   FETCH RECORD
========================== */

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

if(!$data){
    echo "<div class='main'><h3>Record not found</h3></div>";
    include "../layout/footer.php";
    exit;
}

/* 🔒 SECURITY: Village Restriction */

if($role_id != 1 && $data['village_id'] != $_SESSION['village_id']){
    echo "<script>alert('Unauthorized Access'); window.location='development_works_list.php';</script>";
    exit;
}

/* ==========================
   UPDATE
========================== */

if(isset($_POST['update'])){

    if($role_id == 1){
        $village_id = intval($_POST['village_id'] ?? 0);

        if($village_id == 0){
            echo "<script>alert('Please select village');</script>";
            exit;
        }
    }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']);

    if(empty($title)){
        echo "<script>alert('Title is required');</script>";
        exit;
    }

    $image = $data['image'];

    /* IMAGE UPDATE */
    if(!empty($_FILES['image']['name'])){

        $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)){
            echo "<script>alert('Only JPG, PNG, WEBP allowed');</script>";
            exit;
        }

        $image="dev_".time().rand(100,999).".".$ext;

        move_uploaded_file($_FILES['image']['tmp_name'],$target_dir.$image);
    }

    mysqli_query($conn,"
    UPDATE village_development_works SET
    village_id='$village_id',
    title='$title',
    description='$description',
    status='$status',
    image='$image'
    WHERE id='$id'
    ");

    echo "<script>
    alert('Development Work Updated Successfully');
    window.location='development_works_list.php';
    </script>";
}

?>

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

<h2>Edit Development Work</h2>

<div class="form-box">

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

<?php if($role_id == 1){ ?>

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

<!-- BLOCK -->
<label>Block</label>
<select id="block" class="form-control">
<option value="">Select Block</option>
</select>

<!-- VILLAGE -->
<label>Village</label>
<select name="village_id" id="village" class="form-control" required>
<option value="<?php echo $data['village_id']; ?>">Selected Village</option>
</select>

<?php } ?>

<!-- TITLE -->
<label>Title</label>
<input type="text" name="title" class="form-control"
value="<?php echo $data['title']; ?>" required>

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

<!-- STATUS -->
<label>Status</label>
<select name="status" class="form-control">

<option value="Planned" <?php if($data['status']=="Planned") echo "selected"; ?>>Planned</option>

<option value="In Progress" <?php if($data['status']=="In Progress") echo "selected"; ?>>In Progress</option>

<option value="Completed" <?php if($data['status']=="Completed") echo "selected"; ?>>Completed</option>

</select>

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

<?php if(!empty($data['image'])){ ?>
<br>
<img src="../../uploads/development/<?php echo $data['image']; ?>" width="120">
<?php } ?>

<br><br>

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

</form>

</div>

</div>
</div>

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

<script>

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

const district = document.getElementById("district");
const block = document.getElementById("block");
const village = document.getElementById("village");

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

});
}

/* LOAD VILLAGES */
if(block){
block.addEventListener("change", function(){

fetch("get_villages.php?block_id="+this.value)
.then(res=>res.text())
.then(data=>{
village.innerHTML=data;
});

});
}

});

</script>