<?php
const APP_BASE = 'https://tads.ctv.hanoi.vn';
require_once __DIR__ . '/../api/config.php';
require_once __DIR__ . '/../api/db.php';

$code = trim($_GET['c'] ?? '', '/ ');
if ($code === '') { header('Location: ' . APP_BASE, true, 302); exit; }

try {
    $pdo  = db();
    $stmt = $pdo->prepare("SELECT code,type,target_uuid,label,is_active FROM qr_redirects WHERE (code=? OR custom_slug=?) LIMIT 1");
    $stmt->execute([$code, $code]);
    $row  = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) { http_response_code(404); exit; }
    if (!$row['is_active']) { http_response_code(410); exit; }

    try {
        $pdo->prepare("INSERT INTO qr_scans (code,user_agent,ip_hash) VALUES (?,?,?)")
            ->execute([$row['code'], substr($_SERVER['HTTP_USER_AGENT']??'',0,500), hash('sha256',$_SERVER['REMOTE_ADDR']??'')]);
    } catch (Throwable $e) {}

    $uuid = urlencode($row['target_uuid']);
    // audio_point: can tra cuu site_id
    if ($row['type'] === 'audio_point') {
        try {
            $ap = $pdo->prepare("SELECT site_id, tour_id FROM audio_points WHERE id=? LIMIT 1");
            $ap->execute([$row['target_uuid']]);
            $apRow = $ap->fetch(PDO::FETCH_ASSOC);
            $siteId  = $apRow['site_id'] ?? $apRow['tour_id'] ?? '';
            $pointId = urlencode($row['target_uuid']);
            $dest = $siteId
                ? APP_BASE . '/detail.html?site=' . urlencode($siteId) . '&point=' . $pointId
                : APP_BASE . '/detail.html?point=' . $pointId;
        } catch (Throwable $e) {
            $dest = APP_BASE;
        }
    } else {
        $dest = match($row['type']) {
            'site'    => APP_BASE . '/detail.html?site='         . $uuid,
            'partner' => APP_BASE . '/partner-detail.html?uuid=' . $uuid,
            'tour'    => APP_BASE . '/tour.html?id='             . $uuid,
            default   => APP_BASE
        };
    }

    header('Location: ' . $dest, true, 302);
    header('Cache-Control: no-cache, no-store');
    exit;

} catch (Throwable $e) {
    header('Location: ' . APP_BASE, true, 302);
    exit;
}
