<?php
declare(strict_types=1);
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../cron_runner.php'; // inline cron: expire old rooms on each bot submit

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

function sr_out(array $d, int $s = 200): void {
    http_response_code($s);
    echo json_encode($d, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

// POST body (multipart/form-data — bot sends files=screenshot)
$roomCode   = trim((string)($_POST['room_code']   ?? ''));
$hostName   = trim((string)($_POST['host_name']   ?? ''));
$instanceId = trim((string)($_POST['instance_id'] ?? ''));
$secret     = trim((string)($_POST['secret']      ?? $_SERVER['HTTP_X_BOT_SECRET'] ?? ''));
$apiKey     = trim((string)($_POST['api_key']     ?? ''));
$apiSecret  = trim((string)($_POST['api_secret']  ?? ''));

if ($roomCode === '') sr_out(['ok'=>false,'error'=>'room_code required'], 400);

$pdo = lk_pdo();

// ── Auth ──
if ($apiKey !== '' && $apiSecret !== '') {
    try {
        $st = $pdo->prepare("SELECT id, api_secret_hash FROM users WHERE api_key=? AND is_active=1 LIMIT 1");
        $st->execute([$apiKey]);
        $user = $st->fetch(PDO::FETCH_ASSOC);
    } catch (Throwable $e) { sr_out(['ok'=>false,'error'=>'DB: '.$e->getMessage()], 500); }
    if (!$user || !hash_equals((string)$user['api_secret_hash'], $apiSecret)) {
        sr_out(['ok'=>false,'error'=>'Invalid credentials'], 401);
    }
} else {
    $configSecret = lk_setting('bot_submit_secret', '');
    if ($configSecret !== '' && ($secret === '' || !hash_equals($configSecret, $secret))) {
        sr_out(['ok'=>false,'error'=>'Invalid secret'], 401);
    }
}

// ── Duplicate check FIRST before saving screenshot ──
try {
    $chk = $pdo->prepare("SELECT id, screenshot_path FROM rooms WHERE room_code=? ORDER BY id DESC LIMIT 1");
    $chk->execute([$roomCode]);
    $existing = $chk->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $existing = null;
}

if ($existing) {
    // Already in DB — return success immediately, don't save screenshot again
    sr_out([
        'ok'        => true,
        'room_id'   => (int)$existing['id'],
        'room_code' => $roomCode,
        'duplicate' => true,
    ]);
}

// ── Screenshot upload (only for NEW rooms) ──
$screenshotPath = null;
if (!empty($_FILES['screenshot']) && $_FILES['screenshot']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = __DIR__ . '/../uploads/rooms/';
    if (!is_dir($uploadDir)) {
        @mkdir($uploadDir, 0755, true);
    }

    $tmpFile  = (string)$_FILES['screenshot']['tmp_name'];
    $origName = (string)($_FILES['screenshot']['name'] ?? 'shot.png');
    $ext      = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
    if (!in_array($ext, ['png','jpg','jpeg','webp'], true)) $ext = 'png';

    $imgInfo = @getimagesize($tmpFile);
    if ($imgInfo !== false) {
        $fileName = 'room_' . preg_replace('/[^A-Za-z0-9]/', '', $roomCode) . '_' . time() . '.' . $ext;
        $destPath = $uploadDir . $fileName;
        if (move_uploaded_file($tmpFile, $destPath)) {
            $screenshotPath = 'uploads/rooms/' . $fileName;
        }
    }
}

// ── Insert new room (expires_at = 15 min for waiting rooms) ──
try {
    if ($screenshotPath !== null) {
        $ins = $pdo->prepare("
            INSERT INTO rooms (room_code, host_name, instance_id, screenshot_path, status, is_assigned, created_at, expires_at)
            VALUES (?, ?, ?, ?, 'waiting', 0, NOW(), DATE_ADD(NOW(), INTERVAL 15 MINUTE))
        ");
        $ins->execute([$roomCode, $hostName, $instanceId, $screenshotPath]);
    } else {
        $ins = $pdo->prepare("
            INSERT INTO rooms (room_code, host_name, instance_id, status, is_assigned, created_at, expires_at)
            VALUES (?, ?, ?, 'waiting', 0, NOW(), DATE_ADD(NOW(), INTERVAL 15 MINUTE))
        ");
        $ins->execute([$roomCode, $hostName, $instanceId]);
    }
    $id = (int)$pdo->lastInsertId();
    sr_out([
        'ok'              => true,
        'room_id'         => $id,
        'room_code'       => $roomCode,
        'screenshot_saved'=> $screenshotPath !== null,
    ]);
} catch (Throwable $e) {
    sr_out(['ok'=>false,'error'=>'DB: '.$e->getMessage()], 500);
}
