<?php
/**
 * boompay_callback.php — Boompay Deposit Callback
 * Commission model: L1=15%/6%, L2=6%/3%, L3=2%/2% (first/subsequent deposit)
 */
require_once __DIR__ . '/config.php';

// Force Pakistan Timezone
date_default_timezone_set('Asia/Karachi');

$log = __DIR__ . '/boompay_callback_log.txt';

$post = $_POST;
if (empty($post)) {
    $raw = file_get_contents('php://input');
    $post = json_decode($raw, true) ?: [];
    if (empty($post)) parse_str($raw, $post);
}

file_put_contents($log, date('Y-m-d H:i:s')." | IN: ".json_encode($post)."\n", FILE_APPEND);

if (empty($post['order_id'])) { echo "invalid"; exit; }

$status_ok = ((strtolower($post['status'] ?? '')) === 'success');

if (!$status_ok) { 
    file_put_contents($log, date('Y-m-d H:i:s')." | Status not success\n", FILE_APPEND);
    echo "ok"; exit; 
}

$order_id = $post['order_id'];

// Find deposit record
$st = $pdo->prepare("SELECT * FROM deposits WHERE order_id=? AND status='pending'");
$st->execute([$order_id]);
$deposit = $st->fetch();

if (!$deposit) {
    file_put_contents($log, date('Y-m-d H:i:s')." | Already processed or not found: $order_id\n", FILE_APPEND);
    echo "ok"; exit;
}

// Security: Check if the amount sent by callback matches the pending deposit
// Usually gateways send amount, but it might be missing or slightly different (e.g., decimal).
// The safest is to rely on what was recorded if the callback doesn't have a secure signature check documented,
// However, Boompay didn't document a signature for the callback in the prompt. We will use the deposit amount.
$dep_id = (int)$deposit['id'];
$uid    = (int)$deposit['user_id'];
$amt    = (float)$deposit['amount'];

// --- BONUS CALCULATION START ---
$bonus = 0;
$bonus_wager = 0;
$created_at = $deposit['created_at'] ?? date('Y-m-d H:i:s');

// Check if deposit date is on or after May 15, 2026
if (strtotime($created_at) >= strtotime('2026-05-15 00:00:00')) {
    // Fetch dynamic settings
    $settings_st = $pdo->query("SELECT setting_key, setting_value FROM admin_settings WHERE setting_key IN ('base_deposit_wager_multiplier', 'bonus_wager_multiplier', 'deposit_wager_multiplier', 'deposit_bonus_tiers')");
    $settings = $settings_st->fetchAll(PDO::FETCH_KEY_PAIR);
    
    $base_wager_multiplier = (float)($settings['base_deposit_wager_multiplier'] ?? 1);
    $bonus_wager_multiplier = (float)($settings['bonus_wager_multiplier'] ?? ($settings['deposit_wager_multiplier'] ?? 1));
    $bonus_tiers = json_decode($settings['deposit_bonus_tiers'] ?? '[]', true) ?: [];

    foreach ($bonus_tiers as $tier) {
        if ($amt >= $tier['min']) {
            $bonus = $tier['bonus'];
            break;
        }
    }
    
    // Dynamic Wagers
    $bonus_wager = $bonus * $bonus_wager_multiplier;
    $total_wager = ($amt * $base_wager_multiplier) + $bonus_wager;
} else {
    $total_wager = $amt; // Default 1x wager for old deposits with no bonus
}

$total_credit = $amt + $bonus;
// --- BONUS CALCULATION END ---


// Is this the user's first deposit?
$prev_deps = (int)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM deposits WHERE user_id=$uid AND status='approved'")->fetchColumn();
$is_first  = ($prev_deps <= 0);

// Commission rates
$rates = $is_first
    ? [1 => 0.15, 2 => 0.06, 3 => 0.02]  // First deposit: 15%, 6%, 2%
    : [1 => 0.06, 2 => 0.03, 3 => 0.02]; // Other deposits: 6%, 3%, 2%

$pdo->beginTransaction();
try {
    // Mark deposit approved
    $pdo->prepare("UPDATE deposits SET status='approved', updated_at=NOW() WHERE id=?")->execute([$dep_id]);

    // Credit balance + total wager + real total_deposits
    $pdo->prepare("UPDATE users SET balance=COALESCE(balance,0)+?, wager=COALESCE(wager,0)+?, total_deposits=COALESCE(total_deposits,0)+? WHERE id=?")
        ->execute([$total_credit, $total_wager, $amt, $uid]);

    // Walk up referral chain (L1 → L2 → L3)
    $depositor = $pdo->prepare("SELECT referedby FROM users WHERE id=?");
    $depositor->execute([$uid]); $depositor = $depositor->fetch();
    $refcode = $depositor['referedby'] ?? null;

    for ($lvl = 1; $lvl <= 3 && $refcode; $lvl++) {
        $ref = $pdo->prepare("SELECT id FROM users WHERE refercode=?");
        $ref->execute([$refcode]); $ref = $ref->fetch();
        if (!$ref) break;

        // Important: Commission is ONLY calculated on the base $amt, not the bonus!
        $comm = round($amt * $rates[$lvl], 2);
        
        $pdo->prepare("INSERT INTO referral_commissions (user_id,from_user_id,deposit_id,amount,level,is_first_deposit) VALUES(?,?,?,?,?,?)")
            ->execute([$ref['id'], $uid, $dep_id, $comm, $lvl, $is_first ? 1 : 0]);
            
        $pdo->prepare("UPDATE users SET unclaimed_earnings=COALESCE(unclaimed_earnings,0)+?, total_commission=COALESCE(total_commission,0)+? WHERE id=?")
            ->execute([$comm, $comm, $ref['id']]);

        // Move to next level
        $nxt = $pdo->prepare("SELECT referedby FROM users WHERE id=?");
        $nxt->execute([$ref['id']]); $nxt = $nxt->fetch();
        $refcode = $nxt['referedby'] ?? null;
    }

    $pdo->commit();
    file_put_contents($log, date('Y-m-d H:i:s')." | SUCCESS: dep#$dep_id uid#$uid Base:Rs$amt Bonus:Rs$bonus first_dep=$is_first\n", FILE_APPEND);
    echo "ok";
} catch (Exception $e) {
    $pdo->rollBack();
    file_put_contents($log, date('Y-m-d H:i:s')." | ERROR: ".$e->getMessage()."\n", FILE_APPEND);
    echo "fail";
}
