<?php
function favorites_list(): void {
    $u = require_auth();
    $stmt = db()->prepare("
        SELECT uf.target_id AS site_id, uf.created_at,
               hs.name, hs.slug, hs.type, hs.cover_image,
               hs.description_short, hs.status,
               p.name_new AS province_name,
               (SELECT COUNT(*) FROM audio_points ap WHERE ap.site_id=hs.id AND ap.status='active') AS audio_points_count
        FROM user_favorites uf
        JOIN heritage_sites hs ON hs.id = uf.target_id
        LEFT JOIN provinces p ON p.id = hs.province_id
        WHERE uf.user_id = :uid AND uf.target_type = 'site'
        ORDER BY uf.created_at DESC
    ");
    $stmt->execute([':uid' => $u['id']]);
    json_ok($stmt->fetchAll());
}

function favorite_add(): void {
    $u    = require_auth();
    $b    = body();
    $site = $b['site_id'] ?? '';
    if (!$site) json_error('Thiếu site_id');
    $ck = db()->prepare("SELECT id FROM heritage_sites WHERE id=:id");
    $ck->execute([':id' => $site]);
    if (!$ck->fetch()) json_error('Không tìm thấy điểm đến', 404);
    db()->prepare("INSERT IGNORE INTO user_favorites(user_id,target_type,target_id,created_at) VALUES(:u,'site',:s,NOW())")
        ->execute([':u' => $u['id'], ':s' => $site]);
    json_ok(['site_id' => $site], 'Đã thêm yêu thích');
}

function favorite_remove(string $site_id): void {
    $u = require_auth();
    db()->prepare("DELETE FROM user_favorites WHERE user_id=:u AND target_type='site' AND target_id=:s")
        ->execute([':u' => $u['id'], ':s' => $site_id]);
    json_ok(['site_id' => $site_id], 'Đã xóa yêu thích');
}

function favorite_check(string $site_id): void {
    $u = require_auth();
    $stmt = db()->prepare("SELECT 1 FROM user_favorites WHERE user_id=:u AND target_type='site' AND target_id=:s");
    $stmt->execute([':u' => $u['id'], ':s' => $site_id]);
    json_ok(['is_favorite' => (bool)$stmt->fetch()]);
}

function history_list(): void {
    $u      = require_auth();
    $limit  = int_param('limit', 20, 1, 100);
    $page   = int_param('page', 1, 1);
    $offset = ($page-1)*$limit;
    $stmt = db()->prepare("
        SELECT le.audio_point_id, le.site_id, le.event_type, le.created_at,
               ap.title, ap.duration_sec, ap.thumbnail,
               hs.name AS site_name, hs.cover_image
        FROM listen_events le
        LEFT JOIN audio_points ap ON ap.id = le.audio_point_id
        LEFT JOIN heritage_sites hs ON hs.id = le.site_id
        WHERE le.user_id = :uid AND le.event_type = 'complete_audio'
        ORDER BY le.created_at DESC
        LIMIT :limit OFFSET :offset
    ");
    $stmt->bindValue(':uid',    $u['id'],  PDO::PARAM_INT);
    $stmt->bindValue(':limit',  $limit,    PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset,   PDO::PARAM_INT);
    $stmt->execute();
    json_ok($stmt->fetchAll());
}

function history_add(): void {
    $u = require_auth();
    $b = body();
    $site_id  = $b['site_id']        ?? null;
    $point_id = $b['audio_point_id'] ?? null;
    $event    = $b['event_type']     ?? 'complete_audio';
    $duration = (int)($b['duration_sec'] ?? 0);
    if (!$site_id) json_error('Thiếu site_id');

    $allowed = ['view_site','start_audio','pause_audio','resume_audio','complete_audio',
                'skip_audio','scan_qr','download_offline','open_offline','open_transcript','share_site'];
    if (!in_array($event, $allowed)) $event = 'complete_audio';

    $anonId = isset($_SERVER['HTTP_X_ANONYMOUS_ID']) ? $_SERVER['HTTP_X_ANONYMOUS_ID'] : bin2hex(random_bytes(8));

    db()->prepare("INSERT INTO listen_events(user_id,anonymous_id,site_id,audio_point_id,event_type,duration_sec,created_at)
        VALUES(:u,:a,:s,:p,:e,:d,NOW())")
        ->execute([':u'=>$u['id'],':a'=>$anonId,':s'=>$site_id,':p'=>$point_id,':e'=>$event,':d'=>$duration]);
    json_ok(null, 'OK');
}
