<?php
// rebit.php - Background VIP Level Upgrade & Rebate Claim Script
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once 'config.php';

// Frontend par data show karne ke liye header JSON set kar diya hai
header('Content-Type: application/json');

// Only run if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'msg' => 'Unauthorized']);
    exit;
}

$r_userId = $_SESSION['user_id'];
global $pdo;

$totalExp = 0;

// =========================================================================
// 1. ORIGINAL VIP UPGRADE SCRIPT (Jaisa aapne bheja tha, 100% same)
// =========================================================================
try {
    // 1. Fetch User's Total EXP (1 Rupee Bet = 1 EXP)
    // Adjust this query based on how you want to calculate EXP (e.g., from 'bets' or 'deposit_requests')
    $expStmt = $pdo->prepare("SELECT SUM(amount) FROM bets WHERE user_id = ?");
    $expStmt->execute([$r_userId]);
    $totalExp = (float)$expStmt->fetchColumn() ?: 0;

    // 2. Fetch User's Current VIP Level
    $uStmt = $pdo->prepare("SELECT vip_level FROM users WHERE id = ?");
    $uStmt->execute([$r_userId]);
    $currentUser = $uStmt->fetch(PDO::FETCH_ASSOC);
    $currentVip = $currentUser['vip_level'] ?? 1;

    // 3. Fetch All VIP Thresholds
    $lvlStmt = $pdo->query("SELECT level, required_recharge FROM vip_levels ORDER BY level ASC");
    $vipLevels = $lvlStmt->fetchAll(PDO::FETCH_ASSOC);

    // 4. Determine New Eligible VIP Level
    $newVipLevel = 1;
    if ($vipLevels) { // Added safe check in case table is empty
        foreach ($vipLevels as $lvl) {
            if ($totalExp >= $lvl['required_recharge']) {
                $newVipLevel = $lvl['level'];
            }
        }
    }

    // 5. Upgrade User if Eligible
    if ($newVipLevel > $currentVip) {
        // Update User Table
        $updStmt = $pdo->prepare("UPDATE users SET vip_level = ? WHERE id = ?");
        $updStmt->execute([$newVipLevel, $r_userId]);

        // Optional: Insert into vip_history to show in UI
        // Auto-create table if not exists safe check
        $pdo->exec("CREATE TABLE IF NOT EXISTS `vip_history` (
            `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `title` varchar(100), `description` text, `exp_change` decimal(10,2), `type` varchar(50), `created_at` timestamp DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`)
        )");

        $histIns = $pdo->prepare("INSERT INTO vip_history (user_id, title, description, exp_change, type) VALUES (?, ?, ?, ?, ?)");
        $histTitle = "VIP Level Upgraded";
        $histDesc = "VIP level upgraded to [VIP{$newVipLevel}]";
        $histIns->execute([$r_userId, $histTitle, $histDesc, 0, 'bonus']);
    }

} catch (Exception $e) {
    // Silently fail in background, log error if needed
    // error_log("Rebate Script Error: " . $e->getMessage());
}


// =========================================================================
// 2. NEW REBATE LOGIC (Jo abhi add karna tha)
// =========================================================================

// Auto-create Rebate History Table if missing
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `rebate_history` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `user_id` int(11) NOT NULL,
        `rebate_amount` decimal(10,2) NOT NULL,
        `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
} catch(Exception $e) {}

// Logic: 1 Rupee for every 1000 bet (0.1% or 0.001 multiplier)
// Hum upar calculate kiye gaye $totalExp ka hi use kar rahe hain!
$totalTheoreticalRebate = $totalExp * 0.001;

$claimedTotal = 0;
$claimedToday = 0;

try {
    // Fetch already claimed rebate total
    $stmtTotal = $pdo->prepare("SELECT SUM(rebate_amount) FROM rebate_history WHERE user_id = ?");
    $stmtTotal->execute([$r_userId]);
    $claimedTotal = (float)$stmtTotal->fetchColumn();

    // Fetch today's claimed rebate
    $stmtToday = $pdo->prepare("SELECT SUM(rebate_amount) FROM rebate_history WHERE user_id = ? AND DATE(created_at) = CURDATE()");
    $stmtToday->execute([$r_userId]);
    $claimedToday = (float)$stmtToday->fetchColumn();
} catch (Exception $e) {}

// Calculate remaining available rebate
$availableRebate = max(0, $totalTheoreticalRebate - $claimedTotal);

// 3. Handle Claim Action (When user clicks "One-Click Rebate" button)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'claim') {
    if ($availableRebate <= 0) {
        echo json_encode(['success' => false, 'msg' => 'No rebate available to claim.']);
        exit;
    }

    try {
        $pdo->beginTransaction();
        
        // Add to User Wallet
        $upd = $pdo->prepare("UPDATE wallets SET main_balance = main_balance + ? WHERE user_id = ?");
        $upd->execute([$availableRebate, $r_userId]);
        
        // Add to Rebate History
        $ins = $pdo->prepare("INSERT INTO rebate_history (user_id, rebate_amount) VALUES (?, ?)");
        $ins->execute([$r_userId, $availableRebate]);
        
        $pdo->commit();
        echo json_encode(['success' => true, 'msg' => "Successfully claimed ₹" . number_format($availableRebate, 2)]);
    } catch(Exception $e) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'msg' => 'Server error during claim.']);
    }
    exit;
}

// 4. Return Data to Frontend for normal page load
echo json_encode([
    'success' => true,
    'available' => number_format($availableRebate, 2, '.', ''),
    'today' => number_format($claimedToday, 2, '.', ''),
    'total' => number_format($claimedTotal, 2, '.', '')
]);
exit;
?>