<?php

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

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

/* GET VILLAGE */

$role_id = $_SESSION['role_id'];

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

/* FETCH EXISTING DATA */

$data = null;

if($village_id){
$res = mysqli_query($conn,"SELECT * FROM village_contact WHERE village_id='$village_id'");
$data = mysqli_fetch_assoc($res);
}

/* SAVE */

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

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

$check = mysqli_query($conn,"SELECT id FROM village_contact WHERE village_id='$village_id'");

if(mysqli_num_rows($check) > 0){

mysqli_query($conn,"UPDATE village_contact SET
title='$title',
description='$desc',
map_iframe='$map'
WHERE village_id='$village_id'");

echo "<script>alert('Updated Successfully');</script>";

}else{

mysqli_query($conn,"INSERT INTO village_contact
(village_id,title,description,map_iframe)
VALUES
('$village_id','$title','$desc','$map')");

echo "<script>alert('Saved Successfully');</script>";
}

}

?>

<div class="main">

<h2>Contact Page</h2>

<form method="POST" class="form-box">

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

<label>Select Village</label>
<select name="village_id" required>

<option value="">Select Village</option>

<?php
$v = mysqli_query($conn,"
SELECT v.id,v.village_name,b.block_name,d.district_name
FROM villages v
LEFT JOIN blocks b ON v.block_id=b.id
LEFT JOIN districts d ON v.district_id=d.id
ORDER BY v.village_name
");

while($row=mysqli_fetch_assoc($v)){
?>

<option value="<?php echo $row['id']; ?>">
<?php echo $row['village_name']; ?> (<?php echo $row['block_name']; ?> / <?php echo $row['district_name']; ?>)
</option>

<?php } ?>

</select>

<?php } ?>

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

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

<label>Google Map Iframe</label>
<textarea name="map"><?php echo $data['map_iframe'] ?? ''; ?></textarea>

<button name="save" class="btn-save">Save</button>

</form>

</div>

<!-- CKEDITOR -->
<script src="https://cdn.ckeditor.com/4.21.0/standard/ckeditor.js"></script>
<script>
CKEDITOR.replace('editor');
</script>

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