<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

$response = [
    'success' => false,
    'message' => '',
    'matrix_depth' => 0,
    'downline' => []
];

if (!isLoggedIn()) {
    $response['message'] = "Unauthorized.";
    echo json_encode($response);
    exit();
}

$currentUser = getCurrentUser();

try {
    // 1. Fetch matrix depth for user designation
    $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;
    $response['matrix_depth'] = $matrix_depth;

    // 2. Fetch downline
    $downline = [];
    if ($matrix_depth > 0) {
        try {
            $stmt_downline = $pdo->prepare("
                WITH RECURSIVE downline AS (
                    SELECT id, username, email, employee_code, profile_picture_url, 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.profile_picture_url, 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.profile_picture_url, 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) {
            $downline = [];
        }
    }
    $response['downline'] = $downline;
    $response['success'] = true;
} catch (PDOException $e) {
    error_log("team_tree.php database error: " . $e->getMessage());
    $response['message'] = "Failed to load team tree. Please try again later.";
}

echo json_encode($response);
