<?php
/**
 * Heritage Voice — i18n.php
 * API đa ngôn ngữ
 *
 * GET    /api/audio-localizations              Danh sách tất cả localizations
 * POST   /api/audio-localizations              Thêm/cập nhật localization
 * DELETE /api/audio-localizations/{id}         Xóa localization
 *
 * GET    /api/content-translations             Danh sách translations
 * POST   /api/content-translations             Thêm/cập nhật translation
 */

function i18n_audio_list(): void {
    $audio_point_id = str_param('audio_point_id');
    $lang           = str_param('lang');

    $where  = [];
    $params = [];
    if ($audio_point_id) { $where[] = 'al.audio_point_id = :apid'; $params[':apid'] = $audio_point_id; }
    if ($lang)           { $where[] = 'al.language_code = :lang';  $params[':lang'] = $lang; }
    $w = $where ? 'WHERE ' . implode(' AND ', $where) : '';

    $stmt = db()->prepare("
        SELECT al.*, ap.title AS audio_point_title, ap.site_id
        FROM audio_localizations al
        LEFT JOIN audio_points ap ON ap.id = al.audio_point_id
        $w
        ORDER BY al.audio_point_id, al.language_code
    ");
    $stmt->execute($params);
    json_ok($stmt->fetchAll());
}

function i18n_audio_save(): void {
    require_editor();
    $b = body();
    $audio_point_id = trim($b['audio_point_id'] ?? '');
    $lang           = trim($b['language_code']  ?? '');
    $audio_url      = trim($b['audio_url']      ?? '');
    $duration_sec   = (int)($b['duration_sec']  ?? 0);
    $source         = in_array($b['source'] ?? '', ['manual','tts']) ? $b['source'] : 'manual';

    if (!$audio_point_id) json_error('Thiếu audio_point_id');
    if (!in_array($lang, ['vi','en','zh','ja','ko','fr'])) json_error('Ngôn ngữ không hợp lệ');
    if (!$audio_url) json_error('Thiếu audio_url');

    db()->prepare("
        INSERT INTO audio_localizations (audio_point_id, language_code, audio_url, duration_sec, source)
        VALUES (:apid, :lang, :url, :dur, :src)
        ON DUPLICATE KEY UPDATE
            audio_url    = VALUES(audio_url),
            duration_sec = VALUES(duration_sec),
            source       = VALUES(source)
    ")->execute([
        ':apid' => $audio_point_id,
        ':lang' => $lang,
        ':url'  => $audio_url,
        ':dur'  => $duration_sec,
        ':src'  => $source,
    ]);

    json_ok(null, 'Đã lưu audio ' . strtoupper($lang));
}

function i18n_audio_delete(string $id): void {
    require_editor();
    db()->prepare("DELETE FROM audio_localizations WHERE id=:id")->execute([':id' => $id]);
    json_ok(null, 'Đã xóa');
}

function i18n_text_list(): void {
    $entity_type = str_param('entity_type');
    $entity_id   = str_param('entity_id');
    $lang        = str_param('lang');

    $where  = [];
    $params = [];
    if ($entity_type) { $where[] = 'entity_type = :et'; $params[':et'] = $entity_type; }
    if ($entity_id)   { $where[] = 'entity_id = :eid';  $params[':eid'] = $entity_id; }
    if ($lang)        { $where[] = 'language_code = :lang'; $params[':lang'] = $lang; }
    $w = $where ? 'WHERE ' . implode(' AND ', $where) : '';

    $stmt = db()->prepare("SELECT * FROM content_translations $w ORDER BY entity_id, language_code, field_name");
    $stmt->execute($params);
    json_ok($stmt->fetchAll());
}

function i18n_text_save(): void {
    require_editor();
    $b           = body();
    $entity_type = trim($b['entity_type']   ?? '');
    $entity_id   = trim($b['entity_id']     ?? '');
    $lang        = trim($b['language_code'] ?? '');
    $field       = trim($b['field_name']    ?? '');
    $content_val = trim($b['content']       ?? '');
    $uid         = get_token_uid();

    $allowed_types  = ['audio_point','voice_tour','heritage_site'];
    $allowed_fields = ['title','short_description','script','name'];
    $allowed_langs  = ['vi','en','zh','ja','ko','fr'];

    if (!in_array($entity_type, $allowed_types))  json_error('entity_type không hợp lệ');
    if (!in_array($lang, $allowed_langs))          json_error('Ngôn ngữ không hợp lệ');
    if (!in_array($field, $allowed_fields))        json_error('field_name không hợp lệ');
    if (!$entity_id)                               json_error('Thiếu entity_id');
    if (!$content_val)                             json_error('Thiếu content');

    db()->prepare("
        INSERT INTO content_translations (entity_type, entity_id, language_code, field_name, content, created_by)
        VALUES (:et, :eid, :lang, :field, :content, :uid)
        ON DUPLICATE KEY UPDATE
            content    = VALUES(content),
            source     = 'manual',
            reviewed   = 0,
            updated_at = NOW()
    ")->execute([
        ':et'      => $entity_type,
        ':eid'     => $entity_id,
        ':lang'    => $lang,
        ':field'   => $field,
        ':content' => $content_val,
        ':uid'     => $uid,
    ]);

    json_ok(null, 'Đã lưu bản dịch');
}
