<?php
define('SECURE_ACCESS', true);

$pageTitle = "My Team";
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

requireLogin();

$currentUser = getCurrentUser();

$error = '';
$success = '';

// 1. Fetch Matrix Depth for the current user's designation
$matrix_depth = 0;
try {
    if ($pdo) {
        $stmt_depth = $pdo->prepare("
            SELECT d.matrix_depth 
            FROM users u
            LEFT JOIN designations d ON u.designation_id = d.id
            WHERE u.id = ?
        ");
        $stmt_depth->execute([$currentUser['id']]);
        $matrix_depth = (int)$stmt_depth->fetchColumn() ?: 0;
    }
} catch (PDOException $e) {}

// 2. Fetch Matrix Tree Downline limited to Allowed Matrix Depth
$downline = [];
if ($matrix_depth > 0) {
    try {
        if ($pdo) {
            $stmt_downline = $pdo->prepare("
                WITH RECURSIVE downline AS (
                    SELECT id, username, email, employee_code, parent_id, referrer_id, designation_id, 0 AS level
                    FROM users
                    WHERE id = ?
                    
                    UNION ALL
                    
                    SELECT u.id, u.username, u.email, u.employee_code, u.parent_id, u.referrer_id, u.designation_id, d.level + 1
                    FROM users u
                    INNER JOIN downline d ON u.parent_id = d.id
                    WHERE d.level < ?
                )
                SELECT d.id, d.username, d.email, d.employee_code, d.parent_id, d.referrer_id, d.level, des.title AS designation_title, p.username AS parent_name
                FROM downline d
                LEFT JOIN designations des ON d.designation_id = des.id
                LEFT JOIN users p ON d.parent_id = p.id
                WHERE d.level > 0
                ORDER BY d.level ASC, d.id ASC
            ");
            $stmt_downline->execute([$currentUser['id'], $matrix_depth]);
            $downline = $stmt_downline->fetchAll(PDO::FETCH_ASSOC) ?: [];
        }
    } catch (PDOException $e) {
        error_log("team.php database error: " . $e->getMessage());
        $error = "Failed to compile matrix tree. Please try again later.";
    }
}
// 3. Helper to render the visual tree recursively
$children_map = [];
if (!empty($downline)) {
    foreach ($downline as $node) {
        $parent_id = $node['parent_id'];
        $children_map[$parent_id][] = $node;
    }
}

// Fetch current user detail for root node
$currentUserDetail = [
    'id' => $currentUser['id'],
    'username' => $currentUser['username'],
    'employee_code' => $currentUser['employee_code'] ?? '',
    'designation_title' => 'Trainee'
];
try {
    if ($pdo) {
        $stmt_curr = $pdo->prepare("
            SELECT u.id, u.username, u.employee_code, d.title as designation_title 
            FROM users u
            LEFT JOIN designations d ON u.designation_id = d.id
            WHERE u.id = ?
        ");
        $stmt_curr->execute([$currentUser['id']]);
        $fetched_curr = $stmt_curr->fetch(PDO::FETCH_ASSOC);
        if ($fetched_curr) {
            $currentUserDetail = $fetched_curr;
        }
    }
} catch (PDOException $e) {}

function renderTreeNodeHtml($node_id, $username, $employee_code, $designation, $children_map) {
    echo '<li>';
    echo '<div class="tree-node shadow-sm p-3 border rounded bg-white text-center">';
    echo '<i class="bi bi-person-circle fs-3 text-success mb-1"></i>';
    echo '<h6 class="fw-bold mb-1 text-dark text-truncate mx-auto" style="max-width: 120px;">' . htmlspecialchars($username) . '</h6>';
    echo '<span class="badge bg-light text-dark border mb-1 font-monospace" style="font-size: 0.65rem;">' . htmlspecialchars($employee_code) . '</span><br>';
    echo '<span class="badge bg-success-subtle text-success font-monospace" style="font-size: 0.6rem;">' . htmlspecialchars($designation ?: 'Trainee') . '</span>';
    echo '</div>';
    
    if (isset($children_map[$node_id]) && !empty($children_map[$node_id])) {
        echo '<ul>';
        foreach ($children_map[$node_id] as $child) {
            renderTreeNodeHtml($child['id'], $child['username'], $child['employee_code'], $child['designation_title'], $children_map);
        }
        echo '</ul>';
    }
    echo '</li>';
}

require_once __DIR__ . '/../includes/header.php';
?>

<style>
/* CSS Tree Layout Styles */
.tree-wrapper {
    white-space: nowrap;
    overflow-x: auto;
    background-color: #f8f9fa;
}
.tree ul {
    padding-top: 20px; 
    position: relative;
    transition: all 0.5s;
    display: flex;
    justify-content: center;
    padding-left: 0;
    margin-bottom: 0;
}
.tree li {
    text-align: center;
    list-style-type: none;
    position: relative;
    padding: 20px 10px 0 10px;
    transition: all 0.5s;
}
/* Connecting connector lines */
.tree li::before, .tree li::after {
    content: '';
    position: absolute; 
    top: 0; 
    right: 50%;
    border-top: 2px solid #ccc;
    width: 50%; 
    height: 20px;
}
.tree li::after {
    right: auto; 
    left: 50%;
    border-left: 2px solid #ccc;
}
.tree li:only-child::after, .tree li:only-child::before {
    display: none;
}
.tree li:only-child { 
    padding-top: 0;
}
.tree li:first-child::before, .tree li:last-child::after {
    border: 0 none;
}
.tree li:last-child::before {
    border-right: 2px solid #ccc;
    border-radius: 0 5px 0 0;
}
.tree li:first-child::after {
    border-radius: 5px 0 0 0;
}
.tree ul ul::before {
    content: '';
    position: absolute; 
    top: 0; 
    left: 50%;
    border-left: 2px solid #ccc;
    width: 0; 
    height: 20px;
}
.tree-node {
    min-width: 140px;
    background-color: #fff;
    border: 1px solid #dee2e6;
    transition: all 0.3s ease;
    display: inline-block;
    position: relative;
    z-index: 10;
}
.tree-node:hover {
    transform: translateY(-5px);
    box-shadow: 0 .5rem 1rem rgba(0,0,0,.15)!important;
    border-color: #198754;
}
.tree-node:hover + ul::before,
.tree-node:hover + ul li::after,
.tree-node:hover + ul li::before,
.tree-node:hover + ul ul::before {
    border-color: #198754;
}
</style>

<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4">
    <div>
        <h1 class="h2 fw-bold text-dark mb-1">My Team</h1>
        <p class="text-muted mb-0">Explore Your Team</p>
    </div>
</div>

<?php if (!empty($error)): ?>
    <div class="alert alert-danger shadow-sm border-0 mb-4" role="alert">
        <i class="bi bi-x-circle-fill me-2"></i>
        <?php echo htmlspecialchars($error); ?>
    </div>
<?php endif; ?>

<div class="card border-0 shadow-sm bg-white">
    <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center flex-wrap gap-2">
        <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-diagram-3-fill me-2 text-success"></i>My Corporate Hierarchy</h5>
        <ul class="nav nav-pills card-header-pills" id="teamTab" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active btn-sm" id="visual-tab" data-bs-toggle="tab" data-bs-target="#visual-pane" type="button" role="tab" aria-controls="visual-pane" aria-selected="true"><i class="bi bi-diagram-3 me-1"></i>Visual Tree</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link btn-sm" id="list-tab" data-bs-toggle="tab" data-bs-target="#list-pane" type="button" role="tab" aria-controls="list-pane" aria-selected="false"><i class="bi bi-list-ul me-1"></i>List Directory</button>
            </li>
        </ul>
    </div>
    <div class="card-body p-0">
        <?php if ($matrix_depth <= 0): ?>
            <div class="text-center py-5 text-muted">
                <i class="bi bi-slash-circle fs-2 mb-2 d-block text-danger"></i>
                <span class="small">Your current designation rank does not qualify for team allocation structure access.</span>
            </div>
        <?php elseif (empty($downline)): ?>
            <div class="text-center py-5 text-muted">
                <i class="bi bi-diagram-2 fs-2 mb-2 d-block text-secondary"></i>
                <span class="small">No team members located under your corporate position up to depth level <?php echo $matrix_depth; ?>.</span>
            </div>
        <?php else: ?>
            <div class="tab-content" id="teamTabContent">
                <!-- VISUAL TREE TAB -->
                <div class="tab-pane fade show active" id="visual-pane" role="tabpanel" aria-labelledby="visual-tab" tabindex="0">
                    <div class="tree-wrapper overflow-auto p-4 bg-light border-bottom text-center">
                        <div class="tree d-inline-block">
                            <ul>
                                <?php renderTreeNodeHtml($currentUserDetail['id'], $currentUserDetail['username'], $currentUserDetail['employee_code'], $currentUserDetail['designation_title'], $children_map); ?>
                            </ul>
                        </div>
                    </div>
                </div>

                <!-- LIST DIRECTORY TAB -->
                <div class="tab-pane fade" id="list-pane" role="tabpanel" aria-labelledby="list-tab" tabindex="0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light text-secondary font-monospace small">
                                <tr>
                                    <th class="ps-4">Employee Code</th>
                                    <th>Username</th>
                                    <th>Designation</th>
                                    <th class="pe-4 text-end">Team Leader</th>
                                </tr>
                            </thead>
                            <tbody class="small">
                                <?php foreach ($downline as $down_row): ?>
                                    <tr>
                                        <td class="ps-4"><span class="badge bg-light text-dark border font-monospace"><?php echo htmlspecialchars($down_row['employee_code']); ?></span></td>
                                        <td class="fw-bold text-dark"><?php echo htmlspecialchars($down_row['username']); ?></td>
                                        <td><span class="badge bg-primary-subtle text-primary font-monospace"><?php echo htmlspecialchars($down_row['designation_title'] ?: 'Trainee'); ?></span></td>
                                        <td class="pe-4 text-end text-muted font-monospace"><?php echo htmlspecialchars($down_row['parent_name'] ?? 'None'); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php
include __DIR__ . '/../includes/footer.php';
?>
