<?php
/**
 * spin_api.php
 * action=check → আজকে Spin করেছে কিনা, আর Prize-তালিকা দেয়
 * action=spin  → আসল Spin করে, Weighted-Random Prize দেয়,
 *                Balance-এ যোগ করে
 *
 * ✅ নতুন যোগ — Silent-Crash এড়াতে, যেকোনো PHP-Error এখন
 * সরাসরি JSON-Response-এই ফেরত আসবে (Blank-Response না)
 */
error_reporting(E_ALL);
ini_set('display_errors', 0);
header('Content-Type: application/json; charset=utf-8');

set_error_handler(function($errno, $errstr, $errfile, $errline) {
    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])) {
        echo json_encode(['code' => 1, 'msg' => "Fatal-Error: " . $error['message'] . " (সম্ভবত spin_prizes/spin_history Table তৈরি করা হয়নি)"]);
    }
});

include __DIR__ . "/deepanshu/conn.php";
include __DIR__ . "/deepanshu/functions2.php";

// ✅ নতুন যোগ — Bengali/Taka-Symbol সঠিকভাবে আসার জন্য
if (isset($conn)) { $conn->set_charset("utf8mb4"); }

$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'];
$today = date('Y-m-d');
$action = $_GET['action'] ?? '';

// ✅ Prize-তালিকা আনা (সব Action-এই দরকার)
$prizesResult = $conn->query("SELECT * FROM spin_prizes WHERE is_active = 1 ORDER BY id ASC");
$prizes = [];
while ($row = $prizesResult->fetch_assoc()) {
    $prizes[] = $row;
}

if ($action === 'check') {
    $checkStmt = $conn->prepare("SELECT prize_label, prize_amount FROM spin_history WHERE user_id = ? AND spin_date = ?");
    $checkStmt->bind_param("ss", $userId, $today);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();

    $alreadySpun = $checkResult->num_rows > 0;
    $lastPrize = $alreadySpun ? $checkResult->fetch_assoc() : null;

    echo json_encode([
        'code' => 0,
        'can_spin' => !$alreadySpun,
        'prizes' => $prizes,
        'last_prize' => $lastPrize
    ]);
    exit;
}

if ($action === 'spin') {
    // ✅ আজকে আগে Spin করেছে কিনা, আবার Check (Backend-Level Safety)
    $checkStmt = $conn->prepare("SELECT id FROM spin_history WHERE user_id = ? AND spin_date = ?");
    $checkStmt->bind_param("ss", $userId, $today);
    $checkStmt->execute();
    if ($checkStmt->get_result()->num_rows > 0) {
        echo json_encode(['code' => 1, 'msg' => 'আজকে তুমি ইতিমধ্যে Spin করে ফেলেছো, কাল আবার এসো']);
        exit;
    }

    if (empty($prizes)) {
        echo json_encode(['code' => 1, 'msg' => 'কোনো Prize Setup করা নেই']);
        exit;
    }

    // ✅ Weighted-Random Selection — যে Prize-এর Weight যত বেশি,
    // সেটা তত বেশি সম্ভাবনায় আসবে
    $totalWeight = 0;
    foreach ($prizes as $p) {
        $totalWeight += (float)$p['probability_weight'];
    }
    // ✅ ঠিক করা হলো — আগের 10000 Multiplier, 0.000001%-এর মতো
    // অতি-ছোট Probability সঠিকভাবে Represent করতে পারতো না
    // (Precision কম ছিল)। এখন 100000000 (১০ কোটি) ব্যবহার করা
    // হচ্ছে, যাতে এই খুব ছোট সম্ভাবনাও সত্যিকারের Random-ভাবে
    // (যদিও অত্যন্ত বিরলভাবে) Select হতে পারে।
    $precision = 100000000;
    $randomPoint = mt_rand(0, (int)($totalWeight * $precision)) / $precision;

    $selectedPrize = $prizes[0]; // Safe Fallback
    $cumulative = 0;
    foreach ($prizes as $p) {
        $cumulative += (float)$p['probability_weight'];
        if ($randomPoint <= $cumulative) {
            $selectedPrize = $p;
            break;
        }
    }

    // ✅ Transaction-Safe — Balance Update + History-Save একসাথে
    $conn->begin_transaction();
    try {
        $prizeAmount = (float)$selectedPrize['amount'];

        if ($prizeAmount > 0) {
            $updateStmt = $conn->prepare("UPDATE shonu_kaichila SET motta = motta + ? WHERE balakedara = ?");
            $updateStmt->bind_param("ds", $prizeAmount, $userId);
            $updateStmt->execute();
        }

        $historyStmt = $conn->prepare("INSERT INTO spin_history (user_id, prize_label, prize_amount, spin_date) VALUES (?, ?, ?, ?)");
        $historyStmt->bind_param("ssds", $userId, $selectedPrize['label'], $prizeAmount, $today);
        $historyStmt->execute();

        $conn->commit();

        echo json_encode([
            'code' => 0,
            'prize' => $selectedPrize,
            'prize_index' => array_search($selectedPrize, $prizes),
            'msg' => "অভিনন্দন! তুমি {$selectedPrize['label']} জিতেছো"
        ]);
    } catch (Throwable $e) {
        $conn->rollback();
        echo json_encode(['code' => 1, 'msg' => 'একটা সমস্যা হয়েছে, আবার চেষ্টা করো']);
    }
    exit;
}

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