<?php

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

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

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

/* GET FAMILY ID */

$family_id = isset($_GET['family_id']) ? intval($_GET['family_id']) : 0;

if($family_id == 0){
echo "<script>
alert('Family not selected');
window.location='../families/view_families.php';
</script>";
exit;
}


/* FETCH FAMILY */

$fam = mysqli_query($conn,"SELECT * FROM families WHERE id='$family_id' LIMIT 1");
$family = mysqli_fetch_assoc($fam);

if(!$family){
echo "<script>
alert('Family not found');
window.location='../families/view_families.php';
</script>";
exit;
}


/* FETCH MEMBERS */

$members = mysqli_query($conn,"
SELECT 
fm.*,
fr.relation_type,
fr.parent_id,
p.name AS parent_name
FROM family_members fm
LEFT JOIN family_relationships fr 
ON fr.member_id = fm.id
LEFT JOIN family_members p
ON fr.parent_id = p.id
WHERE fm.family_id='$family_id'
ORDER BY fm.id ASC
");

?>

<div class="main">

<h2>Family Members</h2>

<div style="background:#fff;padding:20px;border-radius:6px;box-shadow:0 2px 6px rgba(0,0,0,0.1);">

<h3>Family Head: <?php echo htmlspecialchars($family['family_head']); ?></h3>
<p>House No: <?php echo htmlspecialchars($family['house_number']); ?></p>

<a href="add_member.php?family_id=<?php echo $family_id; ?>" 
style="background:#2c7be5;color:#fff;padding:8px 15px;text-decoration:none;border-radius:4px;">
+ Add Member
</a>

<br><br>

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

<tr style="background:#34495e;color:white;">
<th>ID</th>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Mobile</th>
<th>Relation</th>
<th>Action</th>
</tr>

<?php

if(mysqli_num_rows($members) > 0){

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

?>

<tr>

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

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

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

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

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

<td>

<?php

if($row['relation_type']!=''){

if($row['parent_id']==0){
echo htmlspecialchars($row['relation_type'])." of Head";
}
else{
echo htmlspecialchars($row['relation_type'])." of ".htmlspecialchars($row['parent_name']);
}

}else{

echo "Head Family Member";

}

?>

</td>

<td>

<a href="edit_member.php?id=<?php echo $row['id']; ?>">Edit</a> |

<a href="delete_member.php?id=<?php echo $row['id']; ?>"
onclick="return confirm('Delete this member?')">Delete</a>

</td>

</tr>

<?php

}

}else{

echo "<tr><td colspan='7' align='center'>No Members Found</td></tr>";

}

?>

</table>

</div>

</div>

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