<?php

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

include "../layout/header.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)
{
$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_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
");
}
?>

<!-- ===== PAGE HEADER ===== -->

<div class="card-box" style="display:flex;justify-content:space-between;align-items:center;">

<div>
<h4 style="margin:0;">Sarpanches</h4>
<p style="font-size:12px;color:#777;margin:0;">Village leadership</p>
</div>

<a href="add_sarpanch.php" class="btn-mobile btn-add">
    <i class="fa fa-plus"></i>
</a>

</div>

<!-- ===== LIST ===== -->

<?php if(mysqli_num_rows($sarpanches) > 0){ ?>

<?php while($row=mysqli_fetch_assoc($sarpanches)){ ?>

<div class="card-box">

<div style="display:flex;gap:12px;align-items:center;">

<!-- IMAGE (CIRCLE) -->
<div class="member-img">
<?php if(!empty($row['image'])){ ?>
<img src="../../uploads/sarpanches/<?php echo $row['image']; ?>">
<?php } else { ?>
<img src="https://via.placeholder.com/60">
<?php } ?>
</div>

<!-- DETAILS -->
<div style="flex:1;">

<h5 style="margin:0;"><?php echo $row['name']; ?></h5>

<p style="font-size:12px;color:#666;margin:2px 0;">
📍 <?php echo $row['village_name']; ?>
</p>

<p style="font-size:13px;margin:2px 0;">
🗓 <?php echo $row['duration']; ?>
</p>

<!-- ACTIONS -->
<div class="action-icons">

<a href="edit_sarpanch.php?id=<?php echo $row['id']; ?>" class="icon-btn edit">
    <i class="fa fa-pen"></i>
</a>

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

</div>

</div>

</div>

</div>

<?php } ?>

<?php } else { ?>

<div class="card-box" style="text-align:center;">
No sarpanches found
</div>

<?php } ?>

<!-- ===== BOTTOM NAV ===== -->



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