<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); }

require_once __DIR__.'/db.php';

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
  $gameId = isset($_GET['game_id']) ? intval($_GET['game_id']) : 0;
  if ($gameId <= 0) { http_response_code(400); echo json_encode(['error'=>'missing game_id']); exit(); }
  $stmt = $mysqli->prepare('SELECT level, question, opt_a, opt_b, opt_c, opt_d, opt_e, correct FROM game_questions WHERE game_id=?');
  $stmt->bind_param('i', $gameId);
  $stmt->execute();
  $res = $stmt->get_result();
  $out = [];
  while ($row = $res->fetch_assoc()) {
    $lvl = (int)$row['level'];
    // Filter out null or empty options
    $options = [$row['opt_a'], $row['opt_b'], $row['opt_c'], $row['opt_d'], $row['opt_e']];
    $options = array_filter($options, function($v) { return !is_null($v) && $v !== ''; });
    // Re-index array to be 0-based
    $options = array_values($options);
    
    $out[$lvl] = [
      'q' => $row['question'],
      'options' => $options,
      'correct' => (int)$row['correct']
    ];
  }
  echo json_encode($out);
  exit();
}

if ($method === 'POST') {
  $input = file_get_contents('php://input');
  $data = json_decode($input, true);
  if (!$data) { http_response_code(400); echo json_encode(['error'=>'invalid json']); exit(); }
  $gameId = isset($data['game_id']) ? intval($data['game_id']) : 0;
  $payload = isset($data['data']) ? $data['data'] : null;
  if ($gameId <= 0 || !is_array($payload)) { http_response_code(400); echo json_encode(['error'=>'missing game_id or data']); exit(); }

  $stmt = $mysqli->prepare('INSERT INTO game_questions (game_id, level, question, opt_a, opt_b, opt_c, opt_d, opt_e, correct) VALUES (?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE question=VALUES(question), opt_a=VALUES(opt_a), opt_b=VALUES(opt_b), opt_c=VALUES(opt_c), opt_d=VALUES(opt_d), opt_e=VALUES(opt_e), correct=VALUES(correct)');
  foreach ([1,2,3,4,5] as $lvl) { // Support up to 5 levels for now, or loop through payload keys
    if (!isset($payload[$lvl])) continue;
    $q = $payload[$lvl]['q'] ?? '';
    $opts = $payload[$lvl]['options'] ?? [];
    $corr = isset($payload[$lvl]['correct']) ? intval($payload[$lvl]['correct']) : 0;
    $a = $opts[0] ?? '';
    $b = $opts[1] ?? '';
    $c = $opts[2] ?? '';
    $d = $opts[3] ?? null; // Use null if not provided
    $e = $opts[4] ?? null;
    $stmt->bind_param('iissssssi', $gameId, $lvl, $q, $a, $b, $c, $d, $e, $corr);
    $stmt->execute();
  }
  echo json_encode(['ok'=>true]);
  exit();
}

http_response_code(405);
echo json_encode(['error'=>'method not allowed']);
