<?php

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

$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){
    header("Location: development_works_list.php");
    exit;
}

/* ==========================
   SECURITY CHECK
========================== */

// Village admin can delete only own village data
if($role_id != 1 && $data['village_id'] != $_SESSION['village_id']){
    echo "<script>alert('Unauthorized Action'); window.location='development_works_list.php';</script>";
    exit;
}

/* ==========================
   DELETE IMAGE
========================== */

if(!empty($data['image'])){
    $path = "../../uploads/development/".$data['image'];

    if(file_exists($path)){
        unlink($path);
    }
}

/* ==========================
   DELETE RECORD
========================== */

mysqli_query($conn,"
DELETE FROM village_development_works WHERE id='$id'
");

/* ==========================
   REDIRECT
========================== */

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

exit;