<?php

include "../../config/master.php";

/* Allow Super Admin + Village Admin */
allowRoles([1,5]);

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

$role_id = $_SESSION['role_id'] ?? 0;


/* DELETE */

if(isset($_GET['delete']))
{

$id = intval($_GET['delete']);

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

echo "<script>
alert('Sarpanch Deleted');
window.location='sarpanches_list.php';
</script>";

}


/* FETCH DATA */

if($role_id == 1)
{

/* SUPER ADMIN → SHOW ALL VILLAGES */

$sarpanches = mysqli_query($conn,"
SELECT vs.*, v.village_name
FROM village_sarpanches vs
LEFT JOIN villages v ON vs.village_id = v.id
ORDER BY vs.id DESC
");

}
else
{

/* VILLAGE ADMIN → ONLY HIS VILLAGE */

$village_id = $_SESSION['village_id'];

$sarpanches = mysqli_query($conn,"
SELECT vs.*, v.village_name
FROM village_sarpanches vs
LEFT JOIN villages v ON vs.village_id = v.id
WHERE vs.village_id='$village_id'
ORDER BY vs.id DESC
");

}

?>

<div class="main">

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">

<h2>Sarpanches List</h2>

<a href="add_sarpanch.php" class="btn-success" style="padding:8px 14px;text-decoration:none;">
Add Sarpanch
</a>

</div>

<div class="table-responsive">

<table>

<thead>

<tr>
<th>#</th>
<th>Village</th>
<th>Image</th>
<th>Name</th>
<th>Duration</th>
<th>Action</th>
</tr>

</thead>

<tbody>

<?php

$i=1;

while($row=mysqli_fetch_assoc($sarpanches))
{

?>

<tr>

<td><?php echo $i++; ?></td>

<td><?php echo $row['village_name']; ?></td>

<td>

<?php if($row['image']){ ?>

<img src="../../uploads/sarpanches/<?php echo $row['image']; ?>" width="60">

<?php } ?>

</td>

<td><?php echo $row['name']; ?></td>

<td><?php echo $row['duration']; ?></td>

<td>

<a href="edit_sarpanch.php?id=<?php echo $row['id']; ?>" class="btn-primary">
Edit
</a>

<a href="?delete=<?php echo $row['id']; ?>"
class="btn-danger"
onclick="return confirm('Delete this sarpanch?')">
Delete
</a>

</td>

</tr>

<?php } ?>

</tbody>

</table>

</div>

</div>

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