<?php
require '../element/connection.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

$current_user_id = $_SESSION['user_id'] ?? 0;

header('Content-Type: application/json');

$response = [
    'status' => 'success',
    'message' => '',
    'paid_levels' => [],
    'total_paid' => 0,
    'c1_status' => false,
    'direct_count' => 0,
    'current_rank_level' => 0 // Add current rank level to response
];

if ($current_user_id == 0) {
    $response['status'] = 'error';
    $response['message'] = 'No user logged in';
    echo json_encode($response);
    exit;
}

try {
    $result = checkUserRewards($conn, $current_user_id);
    
    if ($result['paid'] > 0) {
        $levels_str = implode(', ', $result['levels']);
        $response['message'] = "✅ Levels {$levels_str} reward processed! Total: ₹{$result['total']}";
        $response['paid_levels'] = $result['levels'];
        $response['total_paid'] = $result['total'];
    } else {
        $response['message'] = $result['message'] ?? "No eligible rewards yet. Complete C1 (4 directs) and fill your levels to qualify.";
    }
    
    $response['c1_status'] = $result['c1_status'];
    $response['direct_count'] = $result['direct_count'];
    $response['current_rank_level'] = $result['current_rank_level'] ?? 0;
    
} catch (Exception $e) {
    $response['status'] = 'error';
    $response['message'] = $e->getMessage();
}

echo json_encode($response);

/**
 * Update user's rank_level based on completed levels
 */
function updateUserRankLevel($conn, $user_id) {
    // Get the highest paid level from level_rewards
    $result = $conn->query("SELECT MAX(level) as max_level FROM level_rewards WHERE user_id = $user_id AND paid = 1");
    $row = $result->fetch_assoc();
    $max_level = $row['max_level'] ?? 0;
    
    // Update the users table rank_level column
    $conn->query("UPDATE users SET rank_level = $max_level WHERE user_id = $user_id");
    
    return $max_level;
}

/**
 * Check and process rewards for a user:
 * 1. Must have C1 (4 direct users)
 * 2. Level 1 is paid immediately upon C1 (no date check)
 * 3. Levels 2-7 are paid only if they became complete AFTER C1
 */
function checkUserRewards($conn, $user_id) {
    $levelAmounts = [
        1 => 1000,
        2 => 1600,
        3 => 6500,
        4 => 28000,
        5 => 130000,
        6 => 540000,
        7 => 2250000
    ];
    
    $paidLevels = [];
    $totalPaid = 0;
    
    // Check C1
    $directCount = getDirectCount($conn, $user_id);
    $c1Complete = ($directCount >= 4);
    
    if (!$c1Complete) {
        // Even if C1 not complete, update rank_level based on any existing paid levels
        $current_level = updateUserRankLevel($conn, $user_id);
        
        return [
            'paid' => 0,
            'levels' => [],
            'total' => 0,
            'c1_status' => false,
            'direct_count' => $directCount,
            'current_rank_level' => $current_level,
            'message' => 'C1 not met (need 4 directs).'
        ];
    }
    
    // Get user's C1 date (if null, set it now)
    $user = $conn->query("SELECT c1_achieved_at FROM users WHERE user_id = $user_id")->fetch_assoc();
    $c1Date = $user['c1_achieved_at'];
    if (!$c1Date) {
        $conn->query("UPDATE users SET c1_achieved_at = NOW() WHERE user_id = $user_id");
        $c1Date = date('Y-m-d H:i:s');
    }
    
    // Get already processed levels (paid or skipped)
    $processed = [];
    $res = $conn->query("SELECT level, paid FROM level_rewards WHERE user_id = $user_id");
    while ($row = $res->fetch_assoc()) {
        $processed[$row['level']] = $row['paid'];
    }
    
    // === LEVEL 1 (paid immediately on C1, regardless of date) ===
    if (!isset($processed[1]) && isLevelComplete($conn, $user_id, 1)) {
        $amount = processLevelReward($conn, $user_id, 1, $levelAmounts[1]);
        if ($amount > 0) {
            $paidLevels[] = 1;
            $totalPaid += $amount;
        }
    }
    
    // === LEVELS 2–7 (require completion AFTER C1) ===
    for ($level = 2; $level <= 7; $level++) {
        if (isset($processed[$level])) continue;
        if (!isLevelComplete($conn, $user_id, $level)) break;
        
        $maxDate = getMaxJoinDateAtLevel($conn, $user_id, $level);
        if (!$maxDate) continue;
        
        if (strtotime($maxDate) >= strtotime($c1Date)) {
            $amount = processLevelReward($conn, $user_id, $level, $levelAmounts[$level]);
            if ($amount > 0) {
                $paidLevels[] = $level;
                $totalPaid += $amount;
            }
        } else {
            // Level completed before C1 → skip forever
            $conn->query("INSERT INTO level_rewards (user_id, level, amount, paid, paid_at) VALUES ($user_id, $level, {$levelAmounts[$level]}, 0, NOW())");
        }
    }
    
    // Update user's rank_level based on completed levels
    $current_level = updateUserRankLevel($conn, $user_id);
    
    return [
        'paid' => count($paidLevels),
        'levels' => $paidLevels,
        'total' => $totalPaid,
        'c1_status' => true,
        'direct_count' => $directCount,
        'current_rank_level' => $current_level,
        'message' => $paidLevels ? '' : 'No eligible levels after C1.'
    ];
}

function getDirectCount($conn, $user_id) {
    $res = $conn->query("SELECT COUNT(*) as cnt FROM users WHERE sponsor_id = $user_id");
    return ($res) ? (int)$res->fetch_assoc()['cnt'] : 0;
}

function isLevelComplete($conn, $user_id, $targetLevel) {
    $levelUsers = getUsersAtLevel($conn, $user_id, $targetLevel);
    $expectedCount = pow(4, $targetLevel);
    return (count($levelUsers) >= $expectedCount);
}

function getUsersAtLevel($conn, $user_id, $targetLevel) {
    $current = [$user_id];
    for ($d = 0; $d < $targetLevel; $d++) {
        $next = [];
        foreach ($current as $uid) {
            $r = $conn->query("SELECT left_1_id, left_2_id, right_1_id, right_2_id FROM users WHERE user_id = $uid");
            if ($r && $row = $r->fetch_assoc()) {
                if ($row['left_1_id'] != 0) $next[] = $row['left_1_id'];
                if ($row['left_2_id'] != 0) $next[] = $row['left_2_id'];
                if ($row['right_1_id'] != 0) $next[] = $row['right_1_id'];
                if ($row['right_2_id'] != 0) $next[] = $row['right_2_id'];
            }
        }
        $current = $next;
        if (empty($current)) break;
    }
    return ($d == $targetLevel) ? $current : [];
}

function getMaxJoinDateAtLevel($conn, $user_id, $level) {
    $users = getUsersAtLevel($conn, $user_id, $level);
    if (empty($users)) return null;
    $ids = implode(',', $users);
    $res = $conn->query("SELECT MAX(joining_date) as max_date FROM users WHERE user_id IN ($ids)");
    if ($res && $row = $res->fetch_assoc()) {
        return $row['max_date'];
    }
    return null;
}

function processLevelReward($conn, $user_id, $completed_level, $amount) {
    // No deductions
    $tds_amount = 0;
    $admin_amount = 0;
    $net_amount = $amount;
    
    $rankNames = [
        1 => 'STARTER',
        2 => 'BRONZE',
        3 => 'SILVER',
        4 => 'GOLD',
        5 => 'PLATINUM',
        6 => 'DIAMOND',
        7 => 'BLACK DIAMOND'
    ];
    $rank = $rankNames[$completed_level];
    
    $conn->begin_transaction();
    
    try {
        // Get current wallet
        $u = $conn->query("SELECT wallet FROM users WHERE user_id = $user_id")->fetch_assoc();
        $before = $u['wallet'];
        $after = $before + $net_amount;
        
        // Update wallet and rank
        $conn->query("UPDATE users SET wallet = wallet + $net_amount, rank = '$rank' WHERE user_id = $user_id");
        
        // Record in level_rewards
        $conn->query("INSERT INTO level_rewards (user_id, level, amount, paid, paid_at) VALUES ($user_id, $completed_level, $amount, 1, NOW())");
        
        // Record in income_history
        $txn = 'LVL' . time() . rand(100,999);
        $description = "Level $completed_level completion reward ($rank)";
        
        $conn->query("INSERT INTO income_history 
            (user_id, amount, description, credit_debit, admin_charges, tds, from_user_id, to_user_id, income_type, transaction_id, balance_before, balance_after, processed_at)
            VALUES 
            ($user_id, $net_amount, '$description', 1, $admin_amount, $tds_amount, 0, $user_id, 'Level Income', '$txn', $before, $after, NOW())");
        
        $conn->commit();
        
        // After processing reward, update rank_level (though it will be called again in main function)
        // This ensures rank_level is updated immediately
        
        return $amount;
        
    } catch (Exception $e) {
        $conn->rollback();
        error_log("Error processing reward: " . $e->getMessage());
        return 0;
    }
}
?>