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

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 = $_SERVER['HTTP_ORIGIN'] ?? '';
header('Access-Control-Allow-Origin: '.$origin);
header('vary: Origin');

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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit(); }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  http_response_code(405);
  echo json_encode(['code'=>11,'msg'=>'Method not allowed','msgCode'=>12,'serviceNowTime'=>$now]); exit();
}

$body = file_get_contents("php://input");
$post = json_decode($body, true);
if (!is_array($post) ||
    !isset($post['language']) || !isset($post['random']) ||
    !isset($post['signature']) || !isset($post['timestamp'])) {
  echo json_encode(['code'=>7,'msg'=>'Param is Invalid','msgCode'=>6,'serviceNowTime'=>$now]); exit();
}

/* Signature (same rule as your original) */
$language  = htmlspecialchars(mysqli_real_escape_string($conn, $post['language']));
$random    = htmlspecialchars(mysqli_real_escape_string($conn, $post['random']));
$signature = htmlspecialchars(mysqli_real_escape_string($conn, $post['signature']));
$payload   = '{"language":'.$language.',"random":"'.$random.'"}';
$expected  = strtoupper(md5($payload));
if ($expected !== $signature) {
  echo json_encode(['code'=>5,'msg'=>'Wrong signature','msgCode'=>3,'serviceNowTime'=>$now]); exit();
}

/* JWT */
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$bearer = explode(" ", $authHeader);
$token  = $bearer[1] ?? '';
if (!$token) { http_response_code(401); echo json_encode(['code'=>4,'msg'=>'No operation permission','msgCode'=>2,'serviceNowTime'=>$now]); exit(); }
$jwtRes = is_jwt_valid($token);
$auth   = json_decode($jwtRes, true);
if (!is_array($auth) || ($auth['status'] ?? '') !== 'Success') { http_response_code(401); echo json_encode(['code'=>4,'msg'=>'No operation permission','msgCode'=>2,'serviceNowTime'=>$now]); exit(); }

/* Session check */
$sesquery = "SELECT akshinak FROM shonu_subjects WHERE akshinak = '".mysqli_real_escape_string($conn,$token)."' LIMIT 1";
$sesresult = $conn->query($sesquery);
if (!$sesresult || mysqli_num_rows($sesresult) !== 1) { http_response_code(401); echo json_encode(['code'=>4,'msg'=>'No operation permission','msgCode'=>2,'serviceNowTime'=>$now]); exit(); }

$userId = (int)$auth['payload']['id'];

/* Daily spin limit */
$dailyLimit = 10;
$cfg = $conn->query("SELECT value FROM tbl_config WHERE name = 'daily_spin_limit' LIMIT 1");
if ($cfg && mysqli_num_rows($cfg) > 0) { $dailyLimit = (int)mysqli_fetch_assoc($cfg)['value']; }

/* Ensure turntable row */
$availableSpins = 0;
$q = $conn->query("SELECT id,total_spins FROM shonu_turntable WHERE user_id = $userId LIMIT 1");
if (!$q || mysqli_num_rows($q) === 0) {
  $conn->query("INSERT INTO shonu_turntable (user_id, invited_wheel_amount, total_spins, created_at, updated_at)
                VALUES ($userId, 0.00, $dailyLimit, NOW(), NOW())");
  $availableSpins = $dailyLimit;
} else {
  $row = mysqli_fetch_assoc($q);
  $availableSpins = (int)$row['total_spins'];
}
if ($availableSpins <= 0) {
  echo json_encode(['code'=>8,'msg'=>'No spins left','msgCode'=>9,'serviceNowTime'=>$now]); exit();
}

/* First spin? */
$r = $conn->query("SELECT COUNT(*) AS total_spins FROM shonu_turntable_spins WHERE user_id = $userId");
$rr = $r ? mysqli_fetch_assoc($r) : ['total_spins'=>0];
$isFirst = ((int)$rr['total_spins'] === 0);

/* Username */
$userName = 'User';
$u = $conn->query("SELECT codechorkamukala FROM shonu_subjects WHERE id = $userId LIMIT 1");
if ($u && mysqli_num_rows($u) > 0) { $ur = mysqli_fetch_assoc($u); if (!empty($ur['codechorkamukala'])) $userName = $ur['codechorkamukala']; }

/* Prize calc */
$prizeAmount = 0.00; $isWin = false; $firstBoxes = null;
if ($isFirst) {
  $boxes = [
    ['amount'=>496.00,'isSelected'=>false],
    ['amount'=>495.00,'isSelected'=>false],
    ['amount'=>497.00,'isSelected'=>false],
    ['amount'=>498.00,'isSelected'=>false]
  ];
  $i = array_rand($boxes);
  $boxes[$i]['isSelected'] = true;
  $prizeAmount = (float)$boxes[$i]['amount'];
  $isWin = ($prizeAmount > 0);
  $firstBoxes = $boxes;
} else {
  $pr = [
    ['amount'=>1.12,'p'=>0.35,'w'=>true],
    ['amount'=>3.05,'p'=>0.25,'w'=>true],
    ['amount'=>4.10,'p'=>0.15,'w'=>true],
    ['amount'=>5.20,'p'=>0.10,'w'=>true],
    ['amount'=>2.50,'p'=>0.08,'w'=>true],
    ['amount'=>1.00,'p'=>0.05,'w'=>true],
    ['amount'=>2.00,'p'=>0.02,'w'=>true],
    ['amount'=>0.00,'p'=>0.00,'w'=>false],
  ];
  $sum=0.0; foreach($pr as $x) $sum+=$x['p'];
  $r = mt_rand()/mt_getrandmax(); $cum=0.0; $sel=null;
  foreach($pr as $x){ $cum += $x['p']/max($sum,1.0); if($r <= $cum){ $sel=$x; break; } }
  if(!$sel) $sel=['amount'=>0.00,'w'=>false];
  $prizeAmount = (float)$sel['amount']; $isWin = (bool)$sel['w'];
}

/* Writes: ONLY turntable; NEVER main wallet */
$spinTime = date('Y-m-d H:i:s');
$conn->query("INSERT INTO shonu_turntable_spins (user_id, prize_amount, spin_time, user_name)
              VALUES ($userId, $prizeAmount, '$spinTime', '".mysqli_real_escape_string($conn,$userName)."')");

if ($isWin && $prizeAmount > 0) {
  $conn->query("UPDATE shonu_turntable 
                SET invited_wheel_amount = invited_wheel_amount + $prizeAmount,
                    total_spins = total_spins - 1,
                    updated_at = NOW()
                WHERE user_id = $userId");
} else {
  $conn->query("UPDATE shonu_turntable 
                SET total_spins = total_spins - 1,
                    updated_at = NOW()
                WHERE user_id = $userId");
}

/* Response */
echo json_encode([
  'code'=>0,'msg'=>'Succeed','msgCode'=>0,'serviceNowTime'=>$now,
  'data'=>[
    'isFirstInvitedWheel'=>$isFirst,
    'prizeAmount'=>(float)$prizeAmount,
    'isWin'=>$isWin,
    'firstInvitedWheelDatas'=>$firstBoxes,
    'note'=>'Gift amount is locked in turntable. Main wallet is never credited.'
  ]
]); exit();
