<?php
/*************
 * COMMISSION CRON SCRIPT
 * Run only by CRON after 12:00 AM (Asia/Dhaka)
 *************/

error_reporting(0);
date_default_timezone_set('Asia/Dhaka');

/* ========== SECURITY : CRON ONLY ========== */
$CRON_KEY = 'RUN_COMMISSION_123'; // অবশ্যই Cron command এর সাথে মিলবে

if (!isset($_GET['cron_key']) || $_GET['cron_key'] !== $CRON_KEY) {
    exit;
}

/* ========== TIME LOCK : AFTER 12 AM ========== */
if (date('H:i') < '00:00') {
    exit;
}

/* ========== DATABASE CONNECTION ========== */
// আপনার DB কানেকশন ফাইল
include_once DIR . '/db.php';

/* ========== RUN ONCE PER DAY CHECK ========== */
$today = date('Y-m-d');

$checkRun = mysqli_query(
    $conn,
    "SELECT id FROM commission_log WHERE run_date = '$today' LIMIT 1"
);

if (mysqli_num_rows($checkRun) > 0) {
    exit; // আজকে আগেই রান হয়েছে
}

/* ========== COMMISSION RATES (%) ========== */
$commissionRates = [
    0.85, // Level 1
    0.75, // Level 2
    0.50, // Level 3
];

/* ========== GET ALL UNPROCESSED BETS ========== */
$betsQuery = mysqli_query(
    $conn,
    "SELECT id, user_id, amount 
     FROM bets 
     WHERE commission_status = 0"
);

while ($bet = mysqli_fetch_assoc($betsQuery)) {

    $userId = $bet['user_id'];
    $amount = (float)$bet['amount'];

    if ($amount <= 0) continue;

    /* ========== GET REFERRAL CODES ========== */
    $refQ = mysqli_query(
        $conn,
        "SELECT code, code1, code2, code3, code4, code5
         FROM shonu_subjects
         WHERE id = '$userId'"
    );

    $ref = mysqli_fetch_assoc($refQ);

    $codes = [
        $ref['code'],
        $ref['code1'],
        $ref['code2'],
        $ref['code3'],
        $ref['code4'],
        $ref['code5']
    ];

    /* ========== DISTRIBUTE COMMISSION ========== */
    for ($i = 0; $i < 6; $i++) {

        if (empty($codes[$i])) continue;

        $percent = $commissionRates[$i];
        $commission = round(($amount * $percent) / 100, 2);

        if ($commission <= 0) continue;

        // Ref user ID
        $uidQ = mysqli_query(
            $conn,
            "SELECT id FROM shonu_subjects WHERE owncode = '{$codes[$i]}'"
        );
        $uid = mysqli_fetch_assoc($uidQ);

        if (!isset($uid['id'])) continue;

        $refUserId = $uid['id'];

        // Current balance
        $balQ = mysqli_query(
            $conn,
            "SELECT motta FROM shonu_kaichila WHERE balakedara = '$refUserId'"
        );
        $bal = mysqli_fetch_assoc($balQ);

        $oldBal = (float)$bal['motta'];
        $newBal = round($oldBal + $commission, 2);

        // Insert history
        mysqli_query(
            $conn,
            "INSERT INTO vyavahara
            (balakedara, ketebida, prakara, purba, bartaman, ayoga, tiarikala)
            VALUES
            ('$refUserId', '$amount', 'LVLCOMM".($i+1)."',
             '$oldBal', '$newBal', '$commission', NOW())"
        );

        // Update balance
        mysqli_query(
            $conn,
            "UPDATE shonu_kaichila
             SET motta = '$newBal'
             WHERE balakedara = '$refUserId'"
        );
    }

    // Mark bet as commission processed
    mysqli_query(
        $conn,
        "UPDATE bets SET commission_status = 1 WHERE id = '{$bet['id']}'"
    );
}

/* ========== SAVE DAILY LOG ========== */
mysqli_query(
    $conn,
    "INSERT INTO commission_log (run_date, run_time)
     VALUES ('$today', NOW())"
);

/* ========== FILE LOG (PROOF) ========== */
file_put_contents(
    DIR . '/commission_cron.log',
    date('Y-m-d H:i:s') . " - Commission executed successfully\n",
    FILE_APPEND
);

echo "COMMISSION SUCCESS";