<?php 
    include "../../conn.php";
    include "../../functions2.php";

    // --- Optional debugging (dev only) ---
    // ini_set('display_errors', 1);
    // ini_set('display_startup_errors', 1);
    // error_reporting(E_ALL);

    header('Content-Type: application/json; charset=utf-8');
    header('Strict-Transport-Security: max-age=31536000');
    header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
    header('Access-Control-Allow-Credentials: true');
    $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
    header('Access-Control-Allow-Origin: ' . $origin);
    header('Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method');

    // CORS preflight
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
        http_response_code(204);
        exit;
    }

    date_default_timezone_set("Asia/Kolkata");
    $nowStr = date("Y-m-d H:i:s");

    // ---------- helpers ----------
    function hasColumn($conn, $table, $column) {
        $table_safe  = mysqli_real_escape_string($conn, $table);
        $column_safe = mysqli_real_escape_string($conn, $column);
        $sql = "SELECT 1 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                  AND TABLE_NAME = '{$table_safe}' 
                  AND COLUMN_NAME = '{$column_safe}'
                LIMIT 1";
        $res = $conn->query($sql);
        return $res && $res->num_rows > 0;
    }

    // ---------- defaults ----------
    $res = [
        'code' => 11,
        'msg' => 'Method not allowed',
        'msgCode' => 12,
        'serviceNowTime' => $nowStr,
    ];

    // ---------- only POST (or non-GET) ----------
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $res['code'] = 11;
        $res['msg'] = 'Method not allowed';
        $res['msgCode'] = 12;
        http_response_code(405);
        echo json_encode($res);
        exit;
    }

    // ---------- parse body ----------
    $raw = file_get_contents("php://input");
    $post = json_decode($raw, true);

    if (!isset($post['language'], $post['random'], $post['signature'], $post['timestamp'])) {
        $res['code'] = 7;
        $res['msg'] = 'Param is Invalid';
        $res['msgCode'] = 6;
        http_response_code(200);
        echo json_encode($res);
        exit;
    }

    // ---------- signature (FIXED) ----------
    // Build canonical JSON EXACTLY (no escaping/quoting changes) for hashing
    $payload = [
        'language' => $post['language'],
        'random'   => $post['random'],
    ];
    $canonical = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $serverSig = strtoupper(md5($canonical));
    $clientSig = strtoupper(trim((string)$post['signature']));

    if ($serverSig !== $clientSig) {
        $res['code'] = 5;
        $res['msg'] = 'Wrong signature';
        $res['msgCode'] = 3;
        $res['serviceNowTime'] = $nowStr;
        http_response_code(200);
        echo json_encode($res);
        exit;
    }

    // Only AFTER signature is valid, sanitize for SQL usage
    $language  = htmlspecialchars(mysqli_real_escape_string($conn, (string)$post['language']));
    $random    = htmlspecialchars(mysqli_real_escape_string($conn, (string)$post['random']));
    // $signature not used further

    // ---------- auth ----------
    $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
    $parts = explode(' ', $authHeader);
    $author = $parts[1] ?? '';

    $jwtCheck = is_jwt_valid($author);
    $authData = json_decode($jwtCheck, true);

    if (!isset($authData['status']) || $authData['status'] !== 'Success') {
        $res['code'] = 4;
        $res['msg'] = 'No operation permission';
        $res['msgCode'] = 2;
        http_response_code(401);
        echo json_encode($res);
        exit;
    }

    $sesquery = "SELECT akshinak FROM shonu_subjects WHERE akshinak = '".mysqli_real_escape_string($conn, $author)."'";
    $sesresult = $conn->query($sesquery);
    $sesnum = $sesresult ? mysqli_num_rows($sesresult) : 0;

    if ($sesnum !== 1) {
        $res['code'] = 4;
        $res['msg'] = 'No operation permission';
        $res['msgCode'] = 2;
        http_response_code(401);
        echo json_encode($res);
        exit;
    }

    $userId = (int)($authData['payload']['id'] ?? 0);
    if ($userId <= 0) {
        $res['code'] = 7;
        $res['msg'] = 'Invalid user';
        $res['msgCode'] = 6;
        http_response_code(400);
        echo json_encode($res);
        exit;
    }

    // ---------- load/ensure turntable ----------
    $userInvitedWheelAmount = 0.00;
    $userInvitedWheelCount  = 0;

    $qTurn = "SELECT invited_wheel_amount, total_spins FROM shonu_turntable WHERE user_id = {$userId} LIMIT 1";
    $rTurn = $conn->query($qTurn);
    if ($rTurn && $rTurn->num_rows > 0) {
        $row = $rTurn->fetch_assoc();
        $userInvitedWheelAmount = (float)($row['invited_wheel_amount'] ?? 0.00);
        $userInvitedWheelCount  = (int)($row['total_spins'] ?? 0);
    } else {
        // Ensure a row exists (optional)
        $conn->query("INSERT IGNORE INTO shonu_turntable (user_id, invited_wheel_amount, total_spins) VALUES ({$userId}, 0, 0)");
    }

    // ---------- BUSINESS RULES ----------
    // A) Allow EXACTLY 1 spin (barrier active otherwise)
    $conn->query("UPDATE shonu_turntable SET total_spins = 1 WHERE user_id = {$userId}");
    $userInvitedWheelCount = 0;

    // B) Sum only CREDITED prizes if schema supports it; else fallback to all
    $hasIsCredited = hasColumn($conn, 'shonu_turntable_spins', 'is_credited');
    if ($hasIsCredited) {
        $qSum = "SELECT COALESCE(SUM(prize_amount),0) AS total_prize
                 FROM shonu_turntable_spins
                 WHERE user_id = {$userId} AND is_credited = 1";
    } else {
        $qSum = "SELECT COALESCE(SUM(prize_amount),0) AS total_prize
                 FROM shonu_turntable_spins
                 WHERE user_id = {$userId}";
    }
    $rSum = $conn->query($qSum);
    $invitedWheelTotalPrizeAmount = 0.00;
    if ($rSum && $rSum->num_rows > 0) {
        $sumRow = $rSum->fetch_assoc();
        $invitedWheelTotalPrizeAmount = (float)$sumRow['total_prize'];
    }

    // C) Config: minimum withdraw amount
    $invitedWheelAmountofcodeAmount = 1.00;
    $rCfg = $conn->query("SELECT value FROM tbl_config WHERE name = 'min_withdraw_amount' LIMIT 1");
    if ($rCfg && $rCfg->num_rows > 0) {
        $cfg = $rCfg->fetch_assoc();
        $invitedWheelAmountofcodeAmount = (float)($cfg['value'] ?? 1.00);
    }

    // D) Is first spin (any history row counts, credited or not)
    $rFirst = $conn->query("SELECT COUNT(*) AS total_spins FROM shonu_turntable_spins WHERE user_id = {$userId}");
    $firstRow = $rFirst ? $rFirst->fetch_assoc() : ['total_spins' => 0];
    $isFirstInvitedWheel = ((int)$firstRow['total_spins'] === 0);

    // E) UI helpers
    $isOpenInvitedWheel = true;                             // keeps wheel open
    $expiredTime = date('Y-m-d H:i:s', strtotime('+24 hours'));
    $diskDisplayAmount = [500.0, 5.0, 10.0, 20.0, 30.0, 50.0, 80.0];
    $noWinningRandomAmount = [0.0, 10.0];

    // F) History (show PENDING/CREDITED if column exists)
    if ($hasIsCredited) {
        $qHist = "SELECT user_id, user_name, prize_amount, spin_time AS createTime, IFNULL(is_credited,0) AS is_credited
                  FROM shonu_turntable_spins
                  WHERE user_id = {$userId}
                  ORDER BY spin_time DESC LIMIT 10";
    } else {
        $qHist = "SELECT user_id, user_name, prize_amount, spin_time AS createTime
                  FROM shonu_turntable_spins
                  WHERE user_id = {$userId}
                  ORDER BY spin_time DESC LIMIT 10";
    }
    $rHist = $conn->query($qHist);
    $lastWheelRecordList = [];
    if ($rHist && $rHist->num_rows > 0) {
        while ($h = $rHist->fetch_assoc()) {
            $item = [
                'userId' => (int)$h['user_id'],
                'userName' => $h['user_name'] ?? 'User',
                'invitedWheelAmount' => (float)$userInvitedWheelAmount,
                'prizeAmount' => (float)$h['prize_amount'],
                'createTime' => $h['createTime'],
            ];
            if ($hasIsCredited) {
                $item['status'] = ((int)$h['is_credited'] === 1 ? 'CREDITED' : 'PENDING');
            }
            $lastWheelRecordList[] = $item;
        }
    } else {
        // Minimal placeholder if no records
        $placeholder = [
            'userId' => $userId,
            'userName' => 'User',
            'invitedWheelAmount' => (float)$userInvitedWheelAmount,
            'prizeAmount' => 0.00,
            'createTime' => date('Y-m-d H:i:s', strtotime('-1 hour')),
        ];
        if ($hasIsCredited) {
            $placeholder['status'] = 'PENDING';
        }
        $lastWheelRecordList[] = $placeholder;
    }

    // ---------- response ----------
    $data = [
        'isOpenInvitedWheel' => $isOpenInvitedWheel,
        'isFirstInvitedWheel' => $isFirstInvitedWheel,
        'userInvitedWheelCount' => (int)$userInvitedWheelCount,            // forced 1
        'userInvitedWheelAmount' => (float)$userInvitedWheelAmount,
        'invitedWheelTotalPrizeAmount' => (float)$invitedWheelTotalPrizeAmount, // credited-only if available
        'invitedWheelAmountofcodeAmount' => (float)$invitedWheelAmountofcodeAmount,
        'expiredTime' => $expiredTime,
        'diskDisplayAmount' => $diskDisplayAmount,
        'noWinningRandomAmount' => $noWinningRandomAmount,
        'lastWheelRecordList' => $lastWheelRecordList
    ];

    $res = [
        'code' => 0,
        'msg' => 'Succeed',
        'msgCode' => 0,
        'serviceNowTime' => $nowStr,
        'data' => $data
    ];

    http_response_code(200);
    echo json_encode($res);
    exit;
?>
