<?php
/**
 * Heritage Voice — analytics.php
 * Handlers cho listen_events endpoints
 */

function analytics_listen(): void {
    $raw    = body();
    $events = isset($raw[0]) ? $raw : [$raw];
    $events = array_slice($events, 0, ANALYTICS_BATCH_LIMIT);

    $valid = [
        'view_site','start_audio','pause_audio','resume_audio','complete_audio',
        'skip_audio','scan_qr','download_offline','open_offline','open_transcript','share_site',
    ];

    $sql = "
        INSERT INTO listen_events
        (anonymous_id, user_id, site_id, tour_id, audio_point_id, qr_code_id,
         event_type, progress_sec, duration_sec, playback_speed,
         trigger_method, gps_accuracy_m, device_os, app_version, is_offline)
        VALUES
        (:anon, :uid, :site, :tour, :ap, :qr,
         :etype, :prog, :dur, :spd,
         :trigger, :gps, :os, :ver, :offline)
    ";

    $pdo      = db();
    $inserted = 0;

    foreach ($events as $ev) {
        if (empty($ev['site_id']) || empty($ev['event_type'])) continue;
        if (!in_array($ev['event_type'], $valid, true)) continue;
        try {
            $pdo->prepare($sql)->execute([
                ':anon'    => $ev['anonymous_id'] ?? anonymous_id(),
                ':uid'     => $ev['user_id']       ?? null,
                ':site'    => $ev['site_id'],
                ':tour'    => $ev['tour_id']        ?? null,
                ':ap'      => $ev['audio_point_id'] ?? null,
                ':qr'      => $ev['qr_code_id']     ?? null,
                ':etype'   => $ev['event_type'],
                ':prog'    => (int)($ev['progress_sec']  ?? 0),
                ':dur'     => (int)($ev['duration_sec']  ?? 0),
                ':spd'     => (float)($ev['playback_speed'] ?? 1.0),
                ':trigger' => $ev['trigger_method']  ?? null,
                ':gps'     => isset($ev['gps_accuracy_m']) ? (int)$ev['gps_accuracy_m'] : null,
                ':os'      => $ev['device_os']       ?? null,
                ':ver'     => $ev['app_version']     ?? null,
                ':offline' => (int)($ev['is_offline'] ?? 0),
            ]);
            $inserted++;
        } catch (Throwable $e) {
            error_log('[HV Analytics] ' . $e->getMessage());
        }
    }

    json_ok(['inserted' => $inserted], 'Analytics đã ghi nhận');
}

function analytics_summary(string $site_id): void {
    $from = str_param('from', date('Y-m-d', strtotime('-30 days')));
    $to   = str_param('to',   date('Y-m-d'));
    $p    = [':site' => $site_id, ':from' => "$from 00:00:00", ':to' => "$to 23:59:59"];

    $s1 = db()->prepare("
        SELECT event_type,
               COUNT(*) AS count,
               COUNT(DISTINCT anonymous_id) AS unique_users
        FROM listen_events
        WHERE site_id = :site AND created_at BETWEEN :from AND :to
        GROUP BY event_type
    ");
    $s1->execute($p);

    $s2 = db()->prepare("
        SELECT audio_point_id,
               SUM(CASE WHEN event_type = 'start_audio'    THEN 1 ELSE 0 END) AS starts,
               SUM(CASE WHEN event_type = 'complete_audio' THEN 1 ELSE 0 END) AS completes
        FROM listen_events
        WHERE site_id = :site
          AND event_type IN ('start_audio', 'complete_audio')
          AND created_at BETWEEN :from AND :to
        GROUP BY audio_point_id
        ORDER BY starts DESC
        LIMIT 10
    ");
    $s2->execute($p);

    json_ok([
        'site_id'    => $site_id,
        'date_from'  => $from,
        'date_to'    => $to,
        'by_event'   => $s1->fetchAll(),
        'top_points' => $s2->fetchAll(),
    ]);
}
