<?php
date_default_timezone_set('Asia/Kolkata');
include('../config.php');
@session_start();

/* ---- Session check ---- */
$user_id1 = $_SESSION['user_id1'] ?? '';
$idvfied1 = $_SESSION['idverified1'] ?? '';
$namevfied1 = $_SESSION['namevfied1'] ?? '';
if ($user_id1 === '') {
    header("Location: index.php");
    exit;
}

/* ---- Extend cookie session ---- */
$timeout = 60 * 60 * 24 * 365;
$s_name = session_name();
if (isset($_COOKIE[$s_name])) {
    setcookie($s_name, $_COOKIE[$s_name], time() + $timeout, '/');
}

/* ---- Fetch logged-in employee ---- */
$fetch1 = ['empid' => '', 'Employee_Number' => '', 'Employee_Full_Name' => ''];
$sel1   = mysqli_query($conn, "SELECT empid, Employee_Number, Employee_Full_Name FROM hr_dump WHERE empid='" . mysqli_real_escape_string($conn, $user_id1) . "' LIMIT 1");
if ($sel1 && mysqli_num_rows($sel1) > 0) {
    $fetch1 = mysqli_fetch_assoc($sel1);
}
$topManagerEmpNum = $fetch1['Employee_Number'] ?? '';

/* ---- Build employee maps ---- */
$query = "SELECT * FROM hr_dump WHERE status='Active'";
$result = mysqli_query($conn, $query);

$employees    = [];
$reportingMap = [];
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $empNum = $row['Employee_Number'];
        $employees[$empNum] = $row;
        $reportingMap[$row['Functional_Reporting']][] = $empNum;
    }
}

/* ---- Recursive rendering with cycle protection ---- */
function renderTeam($empNum, $employees, $reportingMap, $level = 0, &$visited = [])
{
    if (!isset($employees[$empNum])) return;
    if (isset($visited[$empNum])) return; // prevent cycles
    $visited[$empNum] = true;

    $emp   = $employees[$empNum];
    $empid = htmlspecialchars($emp['empid'] ?? '', ENT_QUOTES, 'UTF-8');
    $name  = htmlspecialchars($emp['Employee_Full_Name'] ?? '', ENT_QUOTES, 'UTF-8');
    $hasTeam = isset($reportingMap[$empNum]);
    $indent  = str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $level);

    echo "<tr><td>";
    echo "{$indent}{$name}<br>{$empid} ( <a href='team-dr-view.php?empid={$empid}'>View</a> )<br>";

    if ($hasTeam) {
        echo "<button class='btn btn-success toggle-button' data-division='{$empid}'>View Team</button>";
        echo "<div style='display:none' id='{$empid}'>";
        echo "<table class='table table-bordered bg{$level}'>";
        foreach ($reportingMap[$empNum] as $childEmpNum) {
            renderTeam($childEmpNum, $employees, $reportingMap, $level + 1, $visited);
        }
        echo "</table>";
        echo "</div>";
    } else {
        echo "<button class='btn btn-danger btn-sm'>No Team</button>";
    }

    echo "</td></tr>";
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, viewport-fit=cover" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>List Team Attendance</title>
  <style>
    .division-box { display: none; }
    .table { border: 1px solid; }
    .bg0 { background-color: #e0f7fa; }
    .bg1 { background-color: #f1f8e9; }
    .bg2 { background-color: #fff3e0; }
    .bg3 { background-color: #fce4ec; }
    .bg4 { background-color: #f8f9fa; }
  </style>
  <?php include('header.php'); ?>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</head>

<body>
<div id="appCapsule">
    <div class="section wallet-card-section pt-1">
        <div class="wallet-card">
            <?php include('include/wallet-balance.php'); ?>
            <div class="row mb-4">
                <h6 class="text-center">Team Attendance</h6>
                <div class="col-md-12">
                    <div class="table">
                        <table id="MyTable" class="table table-striped bootstrap-datatable datatable responsive">
                            <thead><tr><th>Team List</th></tr></thead>
                            <tbody>
                            <?php
                            if ($topManagerEmpNum && isset($reportingMap[$topManagerEmpNum])) {
                                foreach ($reportingMap[$topManagerEmpNum] as $directReportEmpNum) {
                                    renderTeam($directReportEmpNum, $employees, $reportingMap);
                                }
                            } else {
                                echo "<tr><td>No direct reports found.</td></tr>";
                            }
                            ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php include('include/copyright.php'); ?>
</div>
<?php include('footer.php'); ?>

<script>
function toggleDivision(divisionId) {
    const division = document.getElementById(divisionId);
    if (division) {
        division.style.display = (division.style.display === "none") ? "block" : "none";
    }
}
$(document).ready(function () {
    $(".toggle-button").on("click", function () {
        const divisionId = $(this).data("division");
        toggleDivision(divisionId);
    });
    $('#MyTable').DataTable();
});
</script>
</body>
</html>
