<?php
include "../../conn.php";

/**
 * Detailed logging helper
 * - writes to __DIR__/vip_update.log
 * - logs timestamp, level, source file and line, and message
 */
$log_file = __DIR__ . '/vip_update.log';

function log_step($message, $level = 'INFO') {
    global $log_file;
    $ts = date('Y-m-d H:i:s');
    $bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
    $src = isset($bt[0]['file']) ? basename($bt[0]['file']) : '';
    $line = isset($bt[0]['line']) ? $bt[0]['line'] : '';
    $entry = "[$ts] [$level] [$src:$line] $message" . PHP_EOL;
    @file_put_contents($log_file, $entry, FILE_APPEND | LOCK_EX);
}

/**
 * Execute a SQL query with logging (query string, error, affected/returned rows)
 * Returns mysqli_result | true | false (same as $conn->query)
 */
function exec_query($conn, $sql, $label = 'SQL') {
    log_step("Executing ($label): $sql");
    $res = $conn->query($sql);
    if ($res === false) {
        log_step("SQL ERROR: (" . $conn->errno . ") " . $conn->error, 'ERROR');
    } else {
        if ($res === true) {
            log_step("Query OK. affected_rows=" . $conn->affected_rows);
        } else {
            log_step("Query returned resultset. num_rows=" . $res->num_rows);
        }
    }
    return $res;
}

/**
 * Helper to apply a reward (updates motta) and log it.
 */
function apply_level_reward($conn, $userid, $oldlvl, $newlvl, $giveamt) {
    log_step("Level transition: oldlvl={$oldlvl} => newlvl={$newlvl}; giveamt={$giveamt}");
    $q = "UPDATE shonu_kaichila SET motta = motta + '$giveamt' WHERE balakedara='$userid'";
    exec_query($conn, $q, 'update_motta');
}

/* ------------------ START SCRIPT LOGIC ------------------ */

log_step("Script start. Raw inputs: byabaharkarta=" . (isset($byabaharkarta) ? $byabaharkarta : '<undef>')
    . ", totalamount=" . (isset($totalamount) ? $totalamount : '<undef>')
    . ", shnunc=" . (isset($shnunc) ? $shnunc : '<undef>'));

// normalize/cast inputs (safe defaults)
$userid = isset($byabaharkarta) ? intval($byabaharkarta) : 0;
$totalamount = isset($totalamount) ? floatval($totalamount) : 0;
$shnunc = isset($shnunc) ? $conn->real_escape_string($shnunc) : date('Y-m-d H:i:s');

log_step("Normalized values: userid={$userid}, totalamount={$totalamount}, shnunc={$shnunc}");

// update rebet first (as in original)
$nabikarana = "UPDATE shonu_kaichila SET rebet = rebet + '$totalamount' WHERE balakedara='$userid'";
exec_query($conn, $nabikarana, 'update_rebet');

// fetch VIP row if exists
$vipquery = "SELECT expe, lvl FROM vip WHERE userid = $userid";
$vipresult = exec_query($conn, $vipquery, 'select_vip');

$viprow = 0;
if ($vipresult !== false && $vipresult !== true) {
    $viprow = $vipresult->num_rows;
}
log_step("VIP rows found: $viprow");

if ($viprow >= 1) {
    $viparr = $vipresult->fetch_assoc();
    log_step("Existing VIP fetched: expe={$viparr['expe']}, lvl={$viparr['lvl']}");
    $earnedExp = floor($totalamount / 100);
    log_step("earnedExp = floor({$totalamount} / 1000) = {$earnedExp}");

    $expe = intval($viparr['expe']) + $earnedExp;
    $orlvl = intval($viparr['lvl']);
    log_step("Computed new expe={$expe}; original lvl={$orlvl}");

    $lvl = 0; $giveamt = 0;

    // Check thresholds & apply rewards exactly like original logic, logging every branch
    if ($expe >= 60 && $expe < 300) {
        $lvl = 1;
        $diff = $lvl - $orlvl;
        log_step("branch: expe in [60,300) => lvl=1, diff={$diff}");
        if ($diff == 1) {
            $giveamt = 60 + 30;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        }
    } else if ($expe >= 300 && $expe < 500) {
        $lvl = 2;
        $diff = $lvl - $orlvl;
        log_step("branch: expe in [300,500) => lvl=2, diff={$diff}");
        if ($diff == 1) {
            $giveamt = 180 + 90;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        } else if ($diff == 2) {
            $giveamt = 60 + 30 + 180 + 90;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        }
    } else if ($expe >= 500 && $expe < 5000) {
        $lvl = 3;
        $diff = $lvl - $orlvl;
        log_step("branch: expe in [500,5000) => lvl=3, diff={$diff}");
        if ($diff == 1) {
            $giveamt = 690 + 290;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        } else if ($diff == 2) {
            $giveamt = 180 + 90 + 690 + 290;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        } else if ($diff == 3) {
            $giveamt = 60 + 30 + 180 + 90 + 690 + 290;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        }
    } else if ($expe >= 5000 && $expe < 50000) {
        $lvl = 4;
        $diff = $lvl - $orlvl;
        log_step("branch: expe in [5000,50000) => lvl=4, diff={$diff}");
        if ($diff == 1) {
            $giveamt = 1890 + 890;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        } else if ($diff == 2) {
            $giveamt = 690 + 290 + 1890 + 890;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        } else if ($diff == 3) {
            $giveamt = 180 + 90 + 690 + 290 + 1890 + 890;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        } else if ($diff == 4) {
            $giveamt = 60 + 30 + 180 + 90 + 690 + 290 + 1890 + 890;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        }
    } else if ($expe >= 20000000) {
        $lvl = 5;
        $diff = $lvl - $orlvl;
        log_step("branch: expe >= 20000000 => lvl=5, diff={$diff}");
        if ($diff == 1) {
            $giveamt = 6900 + 1890;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        } else if ($diff == 2) {
            $giveamt = 1890 + 890 + 6900 + 1890;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        } else if ($diff == 3) {
            $giveamt = 690 + 290 + 1890 + 890 + 6900 + 1890;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        } else if ($diff == 4) {
            $giveamt = 180 + 90 + 690 + 290 + 1890 + 890 + 6900 + 1890;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        } else if ($diff == 5) {
            $giveamt = 60 + 30 + 180 + 90 + 690 + 290 + 1890 + 890 + 6900 + 1890;
            apply_level_reward($conn, $userid, $orlvl, $lvl, $giveamt);
        }
    } else {
        $lvl = 0;
        $giveamt = 0;
        log_step("branch: expe doesn't meet any threshold -> lvl=0");
    }

    log_step("Final computed values for existing VIP: expe={$expe}, lvl={$lvl}, giveamt={$giveamt}");
    $nabikarana = "UPDATE vip SET expe = '$expe', lvl = '$lvl', createdate = '$shnunc' WHERE userid='$userid'";
    exec_query($conn, $nabikarana, 'update_vip');

} else {
    // no vip record -> create new
    $earnedExp = floor($totalamount / 100);
    $expe = $earnedExp;
    log_step("No VIP record; initial earnedExp={$earnedExp}, expe={$expe}");

    if ($expe >= 3000 && $expe < 30000) {
        $lvl = 1; $giveamt = 60 + 30;
    } else if ($expe >= 30000 && $expe < 400000) {
        $lvl = 2; $giveamt = 60 + 30 + 180 + 90;
    } else if ($expe >= 400000 && $expe < 4000000) {
        $lvl = 3; $giveamt = 60 + 30 + 180 + 90 + 690 + 290;
    } else if ($expe >= 4000000 && $expe < 20000000) {
        $lvl = 4; $giveamt = 60 + 30 + 180 + 90 + 690 + 290 + 1890 + 890;
    } else if ($expe >= 20000000) {
        $lvl = 5; $giveamt = 60 + 30 + 180 + 90 + 690 + 290 + 1890 + 890 + 6900 + 1890;
    } else {
        $lvl = 0; $giveamt = 0;
    }

    log_step("New VIP: lvl={$lvl}, giveamt={$giveamt}");
    $tathya = "INSERT INTO `vip` (`userid`,`expe`,`lvl`,`createdate`) VALUES ('$userid','$expe','$lvl','$shnunc')";
    exec_query($conn, $tathya, 'insert_vip');

    $nabikarana = "UPDATE shonu_kaichila SET motta = motta + '$giveamt' WHERE balakedara='$userid'";
    exec_query($conn, $nabikarana, 'update_motta_newvip');
}

log_step("Script end.");
?>
