<?php

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

allowRoles([1,5,6]);

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

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

$search = $_GET['search'] ?? '';

$where = "WHERE 1";

if($role_id != 1)
{
    $where .= " AND village_id='".intval($village_id)."'";
}

if($search != '')
{
    $search_safe = mysqli_real_escape_string($conn,$search);
    $where .= " AND family_head LIKE '%$search_safe%'";
}

/* +1 added for family head */

$query = mysqli_query($conn,"
SELECT f.*,
(SELECT COUNT(*) FROM family_members m WHERE m.family_id=f.id)+1 as members
FROM families f
$where
ORDER BY f.id DESC
");

?>

<div class="main">

<h2>Families</h2>

<br>

<form method="GET">

<input type="text" name="search" placeholder="Search Family Head"
value="<?php echo htmlspecialchars($search); ?>"
style="padding:8px;width:250px;">

<button type="submit">Search</button>

<a href="view_families.php">Reset</a>

</form>

<br>

<table border="1" width="100%" cellpadding="8" style="border-collapse:collapse;">

<tr style="background:#2c3e50;color:white">

<th>ID</th>
<th>House No</th>
<th>Family Head</th>
<th>Mobile</th>
<th>Total Members</th>
<th>Action</th>

</tr>

<?php 

if(mysqli_num_rows($query) > 0){

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

<tr>

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

<td><?php echo htmlspecialchars($row['house_number']); ?></td>

<td>
<b style="color:#2c3e50;">
<?php echo htmlspecialchars($row['family_head']); ?>
</b>
<br>
<small style="color:gray;">(Head)</small>
</td>

<td><?php echo htmlspecialchars($row['mobile']); ?></td>

<td style="text-align:center;font-weight:bold;">
<?php echo $row['members']; ?>
</td>

<td>

<a href="../members/view_members.php?family_id=<?php echo $row['id']; ?>"
style="background:#28a745;color:white;padding:5px 10px;border-radius:4px;text-decoration:none;">
View Members
</a>

|

<a href="../members/add_member.php?family_id=<?php echo $row['id']; ?>"
style="background:#007bff;color:white;padding:5px 10px;border-radius:4px;text-decoration:none;">
Add Member
</a>

|

<a href="edit_family.php?id=<?php echo $row['id']; ?>"
style="background:#f39c12;color:white;padding:5px 10px;border-radius:4px;text-decoration:none;">
Edit
</a>

|

<a href="delete_family.php?id=<?php echo $row['id']; ?>"
onclick="return confirm('Delete family?')"
style="background:#e74c3c;color:white;padding:5px 10px;border-radius:4px;text-decoration:none;">
Delete
</a>

</td>

</tr>

<?php } 

}else{

echo "<tr><td colspan='6' align='center'>No families found</td></tr>";

}

?>

</table>

</div>

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