<?php

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

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


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

/* FETCH RECORD */

$query = mysqli_query($conn,"
SELECT * FROM village_people_thoughts
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']))
{

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

$image = $data['image'];

/* IMAGE UPDATE */

if(!empty($_FILES['image']['name']))
{

$target_dir="../../uploads/thoughts/";

if(!is_dir($target_dir))
{
mkdir($target_dir,0777,true);
}

$ext = pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION);

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

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

}

mysqli_query($conn,"
UPDATE village_people_thoughts
SET
name='$name',
description='$description',
image='$image'
WHERE id='$id'
");

echo "<script>
alert('Thought Updated Successfully');
window.location='people_thoughts_list.php';
</script>";

}

?>

<div class="main">

<h2>Edit People Thought</h2>

<div class="form-box">

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

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

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

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

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

<br><br>

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

</form>

</div>

</div>

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