<?php
require_once '../element/connection.php';
session_start();

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['message' => '❌ You must be logged in.']);
    exit;
}

require_once 'tree_rewards.php'; // processLevelPayments() must exist here
require_once 'load_tree_functions.php'; // contains calculateUserCompletedLevels()

$user_id = $_SESSION['user_id'];

$levelRewards = [
    1 => 250,
    2 => 350,
    3 => 500,
    4 => 800,
    5 => 1200,
    6 => 1900,
    7 => 3200,
    8 => 5100,
    9 => 7500,
    10 => 10000,
    11 => 0
];

// Step 1: Get completed levels
$completedLevels = calculateUserCompletedLevels($conn, $user_id);

// Step 2: Process payouts
$rewardsGiven = processLevelPayments($conn, $user_id, $levelRewards, $completedLevels);

// Step 3: Update user rank
$rankNames = [
    1 => 'Bronze',
    2 => 'Silver',
    3 => 'Gold',
    4 => 'Platinum',
    5 => 'Diamond',
    6 => 'Crown',
    7 => 'Legend',
    8 => 'Royal',
    9 => 'Titan',
    10 => 'Immortal'
];

$finalLevel = min($completedLevels, max(array_keys($rankNames)));

if (isset($rankNames[$finalLevel])) {
    $rank = $rankNames[$finalLevel];
    $stmt = $conn->prepare("UPDATE users SET rank = ? WHERE user_id = ?");
    $stmt->bind_param("si", $rank, $user_id);
    $stmt->execute();
    $stmt->close();
} else {
    $rank = 'Unranked';
}

// Step 4: Return JSON
echo json_encode([
    'message' => "✅ Payout refreshed successfully. Levels Completed: $completedLevels.",
    'rank' => $rank
]);
?>
