<?php
require_once __DIR__ . '/../../../../function/connect.php';
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['extplayer'])) {
    echo json_encode(['status'=>'error','message'=>'Belum login']);
    exit;
}

$extplayer = $_SESSION['extplayer'];
$tanggal   = date('Y-m-d H:i:s');
$maxSpinPerDay = 2;

/* ================= CEK LIMIT SPIN ================= */
$qSpin = mysqli_prepare($koneksi, "
    SELECT COUNT(*) FROM tb_bonus
    WHERE id_user = ?
    AND id_bonus = '7'
    AND DATE(tanggal) = CURDATE()
");
mysqli_stmt_bind_param($qSpin, 's', $extplayer);
mysqli_stmt_execute($qSpin);
mysqli_stmt_bind_result($qSpin, $usedSpin);
mysqli_stmt_fetch($qSpin);
mysqli_stmt_close($qSpin);

if ($usedSpin >= $maxSpinPerDay) {
    echo json_encode(['status'=>'error','message'=>'Spin harian habis']);
    exit;
}

/* ================= AMBIL HADIAH DARI USER ================= */
$qUser = mysqli_prepare($koneksi, "
    SELECT roda_hadiah
    FROM tb_user
    WHERE extplayer = ?
    LIMIT 1
");
mysqli_stmt_bind_param($qUser, 's', $extplayer);
mysqli_stmt_execute($qUser);
mysqli_stmt_bind_result($qUser, $nominal);
mysqli_stmt_fetch($qUser);
mysqli_stmt_close($qUser);

$nominal = (int)$nominal;
if ($nominal <= 0) {
    $nominal = 1000; // fallback
}

/* ================= INSERT TURNOVER ================= */
$qInsert = mysqli_prepare($koneksi, "
    INSERT INTO tb_bonus
    (id_user, id_bonus, nominal, status, tanggal)
    VALUES (?, '7', ?, 'Pending', ?)
");
mysqli_stmt_bind_param($qInsert, 'sds', $extplayer, $nominal, $tanggal);
mysqli_stmt_execute($qInsert);
mysqli_stmt_close($qInsert);

/* ================= RESET CONFIG HADIAH ================= */
mysqli_query($koneksi, "
    UPDATE tb_user
    SET roda_hadiah = 1000
    WHERE extplayer = '$extplayer'
");

/* ================= RESPONSE ================= */
echo json_encode([
    'status'  => 'success',
    'nominal' => $nominal
]);