<?php
/**
 * Heritage Voice — audio.php
 * Handlers cho audio_points endpoints
 */

function audio_list(): void {
    $tour_id = str_param('tour_id');
    $site_id = str_param('site_id');
    $status  = str_param('status', 'active');
    $lang    = str_param('lang', 'vi');
    $allowed_langs = ['vi','en','zh','ja','ko','fr'];
    if (!in_array($lang, $allowed_langs)) $lang = 'vi';

    $where  = [];
    $params = [];
    if ($status !== 'all') { $where[] = "ap.status = :status"; $params[':status'] = $status; }
    if ($tour_id) { $where[] = 'ap.tour_id = :tour_id'; $params[':tour_id'] = $tour_id; }
    if ($site_id) { $where[] = 'ap.site_id = :site_id'; $params[':site_id'] = $site_id; }
    $w = $where ? 'WHERE ' . implode(' AND ', $where) : '';

    // Thêm lang vào params cho subquery
    $params[':lang1'] = $lang;
    $params[':lang2'] = $lang;
    $params[':lang3'] = $lang;
    

    $stmt = db()->prepare("
        SELECT ap.id, ap.tour_id, ap.site_id,
               COALESCE(ct_title.content, ap.title) AS title,
               COALESCE(ct_desc.content,  ap.short_description) AS short_description,
               ap.latitude, ap.longitude, ap.trigger_radius_m,
               COALESCE(al.audio_url, ap.audio_url) AS audio_url,
               ap.duration_sec, ap.thumbnail,
               ap.order_index, ap.zone_name, ap.floor, ap.map_x, ap.map_y,
               ap.is_required_stop, ap.status,
               ap.author, ap.reviewer, ap.content_version,
               ap.review_status, ap.reviewed_by, ap.reviewed_at,
               (al.audio_url IS NOT NULL) AS has_localized_audio,
               (ct_title.content IS NOT NULL) AS has_localized_text
        FROM audio_points ap
        LEFT JOIN audio_localizations al
               ON al.audio_point_id = ap.id AND al.language_code = :lang1
        LEFT JOIN content_translations ct_title
               ON ct_title.entity_type = 'audio_point'
              AND ct_title.entity_id   = ap.id
              AND ct_title.language_code = :lang2
              AND ct_title.field_name  = 'title'
        LEFT JOIN content_translations ct_desc
               ON ct_desc.entity_type  = 'audio_point'
              AND ct_desc.entity_id    = ap.id
              AND ct_desc.language_code = :lang3
              AND ct_desc.field_name   = 'short_description'
        $w ORDER BY ap.floor ASC, ap.order_index ASC
    ");
    $stmt->execute($params);
    $rows = $stmt->fetchAll();
    foreach ($rows as &$r) {
        $r['latitude']         = (float)$r['latitude'];
        $r['has_localized_audio'] = (bool)($r['has_localized_audio'] ?? false);
        $r['has_localized_text']  = (bool)($r['has_localized_text']  ?? false);
        $r['longitude']        = (float)$r['longitude'];
        $r['trigger_radius_m'] = (int)$r['trigger_radius_m'];
        $r['duration_sec']     = (int)$r['duration_sec'];
        $r['is_required_stop'] = (bool)$r['is_required_stop'];
        $r['floor']            = (int)$r['floor'];
        $r['map_x']            = $r['map_x'] !== null ? (float)$r['map_x'] : null;
        $r['map_y']            = $r['map_y'] !== null ? (float)$r['map_y'] : null;
    }
    json_ok($rows);
}

function audio_detail(string $id): void {
    $stmt = db()->prepare("
        SELECT ap.*,
               qr.code     AS qr_code,
               qr.qr_url   AS qr_deep_link
        FROM audio_points ap
        LEFT JOIN (
            SELECT code, target_uuid,
                   CONCAT('https://tads.ctv.hanoi.vn/p/', code) AS qr_url
            FROM qr_redirects
            WHERE type = 'audio_point' AND is_active = 1
        ) qr ON qr.target_uuid = ap.id
        WHERE ap.id = :id AND ap.status = 'active'
    ");
    $stmt->execute([':id' => $id]);
    $row = $stmt->fetch();
    if (!$row) json_error('Không tìm thấy điểm nghe', 404);

    $row['latitude']         = (float)$row['latitude'];
    $row['longitude']        = (float)$row['longitude'];
    $row['trigger_radius_m'] = (int)$row['trigger_radius_m'];
    $row['duration_sec']     = (int)$row['duration_sec'];
    $row['is_required_stop'] = (bool)$row['is_required_stop'];
    $row['trigger_gps']      = (bool)$row['trigger_gps'];
    $row['trigger_qr']       = (bool)$row['trigger_qr'];
    $row['trigger_manual']   = (bool)$row['trigger_manual'];
    json_ok($row);
}

function audio_create(): void {
    required_body(['id','tour_id','site_id','title','latitude','longitude']);
    $b = body();
    db()->prepare("
        INSERT INTO audio_points
        (id,tour_id,site_id,title,short_description,
         latitude,longitude,trigger_radius_m,
         trigger_gps,trigger_qr,trigger_manual,
         audio_url,audio_file_size,duration_sec,transcript,tts_intro,thumbnail,
         order_index,is_required_stop,author,reviewer,voice_talent,
         source_refs,license,content_version,status)
        VALUES(:id,:tour,:site,:title,:short,
               :lat,:lng,:tr,:tgps,:tqr,:tman,
               :aurl,:asize,:dur,:tx,:tts,:thumb,
               :ord,:req,:auth,:rev,:voice,:refs,:lic,:ver,:status)
    ")->execute([
        ':id'    => $b['id'],             ':tour'  => $b['tour_id'],
        ':site'  => $b['site_id'],        ':title' => $b['title'],
        ':short' => $b['short_description']  ?? null,
        ':lat'   => $b['latitude'],        ':lng'   => $b['longitude'],
        ':tr'    => $b['trigger_radius_m'] ?? 25,
        ':tgps'  => (int)($b['trigger_gps']    ?? 1),
        ':tqr'   => (int)($b['trigger_qr']     ?? 1),
        ':tman'  => (int)($b['trigger_manual'] ?? 1),
        ':aurl'  => $b['audio_url']        ?? null,
        ':asize' => $b['audio_file_size']  ?? null,
        ':dur'   => $b['duration_sec']     ?? 0,
        ':tx'    => $b['transcript']       ?? null,
        ':tts'   => $b['tts_intro']         ?? null,
        ':thumb' => $b['thumbnail']        ?? null,
        ':ord'   => $b['order_index']      ?? 1,
        ':req'   => (int)($b['is_required_stop'] ?? 0),
        ':auth'  => $b['author']           ?? null,
        ':rev'   => $b['reviewer']         ?? null,
        ':voice' => $b['voice_talent']     ?? null,
        ':refs'  => isset($b['source_refs']) ? json_encode($b['source_refs'], JSON_UNESCAPED_UNICODE) : null,
        ':lic'   => $b['license']          ?? 'Connect Vietnam Internal',
        ':ver'   => $b['content_version']  ?? '1.0.0',
        ':status'=> $b['status']           ?? 'draft',
    ]);
    json_ok(['id' => $b['id']], 'Tạo điểm nghe thành công');
}

function audio_update(string $id): void {
    $b      = body();
    $fields = ['title','short_description','latitude','longitude','trigger_radius_m',
               'audio_url','duration_sec','transcript','tts_intro','thumbnail',
               'order_index','zone_name','floor','map_x','map_y',
               'is_required_stop','status','content_version',
               'author','reviewer','voice_talent'];
    $set = []; $params = [':id' => $id];
    foreach ($fields as $f) {
        if (array_key_exists($f, $b)) { $set[] = "`$f`=:$f"; $params[":$f"] = $b[$f]; }
    }
    if (!$set) json_error('Không có trường nào để cập nhật');

    // Nếu editor/admin sửa nội dung → reset review_status về draft
    $content_fields = ['title','short_description','audio_url','duration_sec','transcript','latitude','longitude'];
    $is_content_update = !empty(array_intersect($content_fields, array_keys($b)));
    if ($is_content_update) {
        $set[] = "review_status='draft'";
        $set[] = "reviewed_by=NULL";
        $set[] = "reviewed_at=NULL";
        // Reset status về draft nếu đang active
        if (!isset($b['status'])) {
            $set[] = "status='draft'";
        } elseif ($b['status'] === 'active') {
            // Không cho phép set active trực tiếp khi edit content
            foreach ($set as $k => $v) {
                if ($v === "`status`=:status") { unset($set[$k]); unset($params[':status']); }
            }
            $set[] = "status='draft'";
        }
    }

    db()->prepare("UPDATE audio_points SET " . implode(',', $set) . " WHERE id=:id")->execute($params);
    json_ok(['id' => $id], 'Cập nhật thành công');
}

function audio_delete(string $id): void {
    db()->prepare("UPDATE audio_points SET status='inactive' WHERE id=:id")->execute([':id' => $id]);
    json_ok(['id' => $id], 'Đã vô hiệu hóa điểm nghe');
}
