<?php
/**
 * rebate_turnover_api.php
 * action=summary → Claim না-করা মোট Turnover-Rebate দেখায়
 * action=claim   → Available Rebate, Balance-এ যোগ করে
 *
 * ✅ কোনো Existing File স্পর্শ করা হয়নি — Real game_bet_logs
 * Data থেকে On-Demand Calculate করা হয়
 */
error_reporting(E_ALL);
ini_set('display_errors', 0);
// ✅ নতুন যোগ — Output-Buffering, যাতে কোনো Accidental Whitespace/
// Warning/Notice, JSON-এর আগে চলে গিয়ে Response নষ্ট না করে
ob_start();
header('Content-Type: application/json; charset=utf-8');
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    ob_end_clean();
    echo json_encode(['code' => 1, 'msg' => "PHP-Error: $errstr (Line: $errline)"]);
    exit;
});
register_shutdown_function(function() {
    $error = error_get_last();
    if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        if (ob_get_level() > 0) ob_end_clean();
        echo json_encode(['code' => 1, 'msg' => "Fatal-Error: " . $error['message']]);
    } else {
        // ✅ স্বাভাবিক শেষে, Buffer-এ যা আছে (আসল JSON) Flush করা
        if (ob_get_level() > 0) ob_end_flush();
    }
});

include __DIR__ . "/deepanshu/conn.php";
include __DIR__ . "/deepanshu/functions2.php";
if (isset($conn)) { $conn->set_charset("utf8mb4"); }

define('REBATE_PERCENT', 0.5); // ০.৫%

$bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION'] ?? '');
$author = $bearer[1] ?? '';
$is_jwt_valid = is_jwt_valid($author);
$data_auth = json_decode($is_jwt_valid, true);

if (($data_auth['status'] ?? '') !== 'Success') {
    echo json_encode(['code' => 1, 'msg' => 'Login করা নেই']);
    exit;
}

$userId = $data_auth['payload']['id'];
$action = $_GET['action'] ?? '';

// ✅ rebate_claims Table না থাকলে, তৈরি করা (Auto-Setup, Safe)
$conn->query("CREATE TABLE IF NOT EXISTS rebate_claims (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id VARCHAR(50) NOT NULL,
    turnover_amount DECIMAL(15,2) NOT NULL,
    rebate_amount DECIMAL(15,2) NOT NULL,
    claimed_at DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

function calculateRebate($conn, $userId, $rate) {
    // ✅ এখন পর্যন্ত মোট কত Turnover (সব Bet মিলিয়ে)
    $turnoverStmt = $conn->prepare("SELECT SUM(bet_amount) as total FROM game_bet_logs WHERE user_id = ?");
    $turnoverStmt->bind_param("s", $userId);
    $turnoverStmt->execute();
    $totalTurnover = (float)($turnoverStmt->get_result()->fetch_assoc()['total'] ?? 0);

    // ✅ ইতিমধ্যে কত Rebate Claim করা হয়েছে
    $paidStmt = $conn->prepare("SELECT SUM(rebate_amount) as total FROM rebate_claims WHERE user_id = ?");
    $paidStmt->bind_param("s", $userId);
    $paidStmt->execute();
    $totalAlreadyPaid = (float)($paidStmt->get_result()->fetch_assoc()['total'] ?? 0);

    $totalEarned = round($totalTurnover * ($rate / 100), 2);
    $availableToClaim = max(0, round($totalEarned - $totalAlreadyPaid, 2));

    return [
        'total_turnover' => round($totalTurnover, 2),
        'total_earned' => $totalEarned,
        'total_already_paid' => round($totalAlreadyPaid, 2),
        'available_to_claim' => $availableToClaim
    ];
}

if ($action === 'summary') {
    $result = calculateRebate($conn, $userId, REBATE_PERCENT);
    $result['code'] = 0;
    $result['rebate_rate'] = REBATE_PERCENT;
    echo json_encode($result);
    exit;
}

if ($action === 'claim') {
    $result = calculateRebate($conn, $userId, REBATE_PERCENT);
    $claimAmount = $result['available_to_claim'];

    if ($claimAmount <= 0) {
        echo json_encode(['code' => 1, 'msg' => 'এখন Claim করার মতো কোনো Rebate নেই']);
        exit;
    }

    $conn->begin_transaction();
    try {
        $updateStmt = $conn->prepare("UPDATE shonu_kaichila SET motta = motta + ? WHERE balakedara = ?");
        $updateStmt->bind_param("ds", $claimAmount, $userId);
        $updateStmt->execute();

        $recordStmt = $conn->prepare("INSERT INTO rebate_claims (user_id, turnover_amount, rebate_amount) VALUES (?, ?, ?)");
        $recordStmt->bind_param("sdd", $userId, $result['total_turnover'], $claimAmount);
        $recordStmt->execute();

        $conn->commit();
        echo json_encode(['code' => 0, 'msg' => "সফল! ৳$claimAmount তোমার Balance-এ যোগ হয়েছে", 'claimed_amount' => $claimAmount]);
    } catch (Throwable $e) {
        $conn->rollback();
        echo json_encode(['code' => 1, 'msg' => 'একটা সমস্যা হয়েছে, আবার চেষ্টা করো']);
    }
    exit;
}

echo json_encode(['code' => 1, 'msg' => 'Invalid Action']);
