<?php

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

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

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

/* FETCH RECORD */

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

$data = mysqli_fetch_assoc($query);

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

/* UPDATE */

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

$title = mysqli_real_escape_string($conn,$_POST['title']);
$description = mysqli_real_escape_string($conn,$_POST['description']);
$status = $_POST['status'];

$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 = pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION);

$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
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">

<h2>Edit Development Work</h2>

<div class="form-box">

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

<label>Title</label>
<input type="text" name="title"
value="<?php echo $data['title']; ?>"
required>

<label>Description</label>
<textarea name="description" rows="5"><?php echo $data['description']; ?></textarea>

<label>Status</label>

<select name="status">

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

<label>Image</label>
<input type="file" name="image">

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

<br><br>

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

</form>

</div>

</div>

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