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

/* ================= CEK SESSION ================= */
if (!isset($_SESSION['extplayer'])) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Session habis, silakan login ulang'
    ]);
    exit;
}

$id_user = $_SESSION['extplayer'];

/* ================= AMBIL USER ================= */
$qUser = mysqli_query(
    $koneksi,
    "SELECT username FROM tb_user WHERE extplayer = '$id_user' LIMIT 1"
);
$user = mysqli_fetch_assoc($qUser);
$username = $user['username'] ?? '';

/* ================= BATAS KLAIM PER HARI (⬅ TARUH DI SINI) ================= */
$today = date('Y-m-d');

$qLimit = mysqli_query($koneksi, "
    SELECT COUNT(*) AS total 
    FROM tb_scater 
    WHERE id_user = '$id_user'
    AND DATE(created_at) = '$today'
");

$dataLimit = mysqli_fetch_assoc($qLimit);
$totalClaimHariIni = $dataLimit['total'] ?? 0;

if ($totalClaimHariIni >= 2) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Batas klaim harian tercapai (maksimal 2x per hari)'
    ]);
    exit;
}
/* ================= END BATAS ================= */

/* ================= AMBIL DATA POST ================= */
$play_id       = $_POST['play_id'] ?? '';
$total_bet     = $_POST['total_bet'] ?? 0;
$jumlah_scater = $_POST['jumlah_scater'] ?? '';
$total_bonus   = $_POST['total_bonus'] ?? 0;

/* ================= VALIDASI ================= */
if (
    empty($username) ||
    empty($play_id) ||
    empty($jumlah_scater) ||
    empty($_FILES['bukti_ss']['name'])
) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Data belum lengkap'
    ]);
    exit;
}

/* ================= UPLOAD ================= */
$uploadDir = "../../uploads/bukti_scater/";
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

$fileName = time() .'_'. basename($_FILES['bukti_ss']['name']);
$tmp = $_FILES['bukti_ss']['tmp_name'];

if (!move_uploaded_file($tmp, $uploadDir . $fileName)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Upload bukti gagal'
    ]);
    exit;
}

/* ================= INSERT ================= */
$query = mysqli_query($koneksi, "
INSERT INTO tb_scater 
(id_user, username, play_id, total_bet, total_bonus, jumlah_scater, bukti_ss, status)
VALUES 
('$id_user','$username','$play_id','$total_bet','$total_bonus','$jumlah_scater','$fileName','pending')
");

if ($query) {
    echo json_encode([
        'status' => 'success',
        'message' => 'Claim scatter berhasil dikirim, menunggu approval'
    ]);
} else {
    echo json_encode([
        'status' => 'error',
        'message' => 'Gagal menyimpan data'
    ]);
}
exit;