<?php

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

allowRoles([1,5,6]);

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

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

if($family_id == 0){
header("Location: view_families.php");
exit;
}

/* FETCH FAMILY */

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

if(!$family){
echo "Family not found";
exit;
}

/* FETCH MEMBERS */

$members = mysqli_query($conn,"
SELECT fm.id,fm.name,fm.gender,
IFNULL(fr.parent_id,0) as parent_id,
fr.relation_type
FROM family_members fm
LEFT JOIN family_relationships fr 
ON fr.member_id = fm.id
WHERE fm.family_id='$family_id'
ORDER BY fm.id ASC
");

$family_tree = [];

while($row = mysqli_fetch_assoc($members)){
$family_tree[$row['parent_id']][] = $row;
}


/* FUNCTION TO BUILD TREE */

function buildTree($parent_id,$tree){

if(!isset($tree[$parent_id])) return;

echo "<ul style='list-style:none;padding-left:25px;'>";

foreach($tree[$parent_id] as $member){

echo "<li style='margin-bottom:8px;'>";

if($member['gender']=="Male"){
echo '<i class="fa fa-mars" style="color:#3498db;"></i> ';
}else{
echo '<i class="fa fa-venus" style="color:#e84393;"></i> ';
}

echo htmlspecialchars($member['name']);

if($member['relation_type']!=''){
echo " <small style='color:gray;'>(".htmlspecialchars($member['relation_type']).")</small>";
}

/* CHILDREN */

buildTree($member['id'],$tree);

echo "</li>";
}

echo "</ul>";

}

?>

<div class="main">

<h2>Family Tree</h2>

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

<h3 style="color:#2c3e50;">
<i class="fa fa-user"></i>
<?php echo htmlspecialchars($family['family_head']); ?> (Head)
</h3>

<?php

/* FIRST LEVEL MEMBERS (parent = 0 means head children) */

buildTree(0,$family_tree);

?>

<br>

<a href="view_families.php"
style="background:#2c7be5;color:#fff;padding:6px 12px;border-radius:4px;text-decoration:none;">
← Back to Families
</a>

</div>

</div>

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