<?php
/**
 * referral_team_api.php
 * User-এর Real Downline-List + Team-Statistics দেখায়
 */
error_reporting(E_ALL);
ini_set('display_errors', 0);
ob_start();
header('Content-Type: application/json; charset=utf-8');
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    ob_end_clean();
    echo json_encode(['code' => 1, 'msg' => "PHP-Error: $errstr (Line: $errline)"]);
    exit;
});
register_shutdown_function(function() {
    $error = error_get_last();
    if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        if (ob_get_level() > 0) ob_end_clean();
        echo json_encode(['code' => 1, 'msg' => "Fatal-Error: " . $error['message']]);
    } else {
        if (ob_get_level() > 0) ob_end_flush();
    }
});

include __DIR__ . "/deepanshu/conn.php";
include __DIR__ . "/deepanshu/functions2.php";
if (isset($conn)) { $conn->set_charset("utf8mb4"); }

$bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION'] ?? '');
$author = $bearer[1] ?? '';
$is_jwt_valid = is_jwt_valid($author);
$data_auth = json_decode($is_jwt_valid, true);

if (($data_auth['status'] ?? '') !== 'Success') {
    echo json_encode(['code' => 1, 'msg' => 'Unauthorized']);
    exit;
}

$userId = $data_auth['payload']['id'];

$userStmt = $conn->prepare("SELECT owncode FROM shonu_subjects WHERE id = ?");
$userStmt->bind_param("s", $userId);
$userStmt->execute();
$userRow = $userStmt->get_result()->fetch_assoc();
$owncode = $userRow['owncode'] ?? '';

$downline = [];
$activeCount = 0;
$totalTeamDeposit = 0;

if ($owncode !== '') {
    // ✅ ঠিক করা হলো — "dinankavannuracisi" Column আসলে
    // shonu_subjects Table-এ নেই (ভুল Guess ছিল), তাই সরিয়ে
    // দেওয়া হলো, শুধু id দিয়ে Sort করা হচ্ছে
    $downlineStmt = $conn->prepare("SELECT id, mobile FROM shonu_subjects WHERE code = ? ORDER BY id DESC LIMIT 100");
    $downlineStmt->bind_param("s", $owncode);
    $downlineStmt->execute();
    $downlineResult = $downlineStmt->get_result();

    while ($row = $downlineResult->fetch_assoc()) {
        $downlineUserId = $row['id'];

        // ✅ প্রতিটা Downline-এর মোট Deposit বের করা
        $depStmt = $conn->prepare("SELECT SUM(motta) as total FROM thevani WHERE balakedara = ? AND sthiti = 1");
        $depStmt->bind_param("s", $downlineUserId);
        $depStmt->execute();
        $depositTotal = (float)($depStmt->get_result()->fetch_assoc()['total'] ?? 0);

        $isActive = $depositTotal > 0;
        if ($isActive) $activeCount++;
        $totalTeamDeposit += $depositTotal;

        // ✅ Mobile-Number Partial-Mask করা (Privacy)
        $maskedMobile = $row['mobile'] ? substr($row['mobile'], 0, 3) . '****' . substr($row['mobile'], -3) : 'N/A';

        $downline[] = [
            'mobile' => $maskedMobile,
            'joined_at' => 'সদস্য',
            'deposit_total' => round($depositTotal, 2),
            'is_active' => $isActive
        ];
    }
}

echo json_encode([
    'code' => 0,
    'owncode' => $owncode,
    'total_referrals' => count($downline),
    'active_referrals' => $activeCount,
    'total_team_deposit' => round($totalTeamDeposit, 2),
    'downline' => $downline
]);
