<?php
/**
 * Heritage Voice — review.php
 * Handlers cho review endpoints
 *
 * POST /api/review/submit          Editor gửi lên thẩm định
 * GET  /api/review/pending         Reviewer xem danh sách chờ
 * POST /api/review/approve         Reviewer approve
 * POST /api/review/reject          Reviewer reject
 * GET  /api/review/logs            Lịch sử thẩm định (admin+)
 */

// ── HELPERS ───────────────────────────────────────────────────

function _check_editor_permission(int $user_id, string $site_id): bool {
    $ps = db()->prepare("SELECT can_edit FROM user_site_permissions WHERE user_id=:u AND site_id=:s LIMIT 1");
    $ps->execute([':u' => $user_id, ':s' => $site_id]);
    $p = $ps->fetch();
    return $p && $p['can_edit'];
}

function _check_reviewer_permission(int $user_id, string $site_id): bool {
    $ps = db()->prepare("SELECT can_review FROM user_site_permissions WHERE user_id=:u AND site_id=:s LIMIT 1");
    $ps->execute([':u' => $user_id, ':s' => $site_id]);
    $p = $ps->fetch();
    return $p && $p['can_review'];
}

function _notify_review(string $to_email, string $to_name, string $action, string $target_title, string $site_name, string $note = ''): void {
    try {
        $subject = $action === 'submit'
            ? "[$site_name] Yêu cầu thẩm định: $target_title"
            : ($action === 'approve'
                ? "[$site_name] Đã duyệt: $target_title"
                : "[$site_name] Từ chối: $target_title");

        $body = $action === 'submit'
            ? "Xin chào,<br><br>Nội dung <b>$target_title</b> thuộc <b>$site_name</b> đang chờ thẩm định.<br><br>Vui lòng đăng nhập CMS để xem và xử lý."
            : ($action === 'approve'
                ? "Xin chào <b>$to_name</b>,<br><br>Nội dung <b>$target_title</b> đã được <b>phê duyệt</b> và hiện trên ứng dụng."
                : "Xin chào <b>$to_name</b>,<br><br>Nội dung <b>$target_title</b> đã bị <b>từ chối</b>." . ($note ? "<br><br>Lý do: $note" : "") . "<br><br>Vui lòng chỉnh sửa và gửi lại.");

        require_once __DIR__ . '/../PHPMailer/src/PHPMailer.php';
        require_once __DIR__ . '/../PHPMailer/src/SMTP.php';
        require_once __DIR__ . '/../PHPMailer/src/Exception.php';

        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
        $mail->isSMTP();
        $mail->Host       = 'tads.ctv.hanoi.vn';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'no-reply@tads.ctv.hanoi.vn';
        $mail->Password   = 'NoReply@2026';
        $mail->SMTPSecure = 'ssl';
        $mail->Port       = 465;
        $mail->CharSet    = 'UTF-8';
        $mail->setFrom('no-reply@tads.ctv.hanoi.vn', 'Heritage Voice');
        $mail->addAddress($to_email, $to_name);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->send();
    } catch (Throwable $e) {
        // Không làm gián đoạn API nếu mail lỗi
    }
}

// ── SUBMIT (Editor gửi lên thẩm định) ────────────────────────
function review_submit(): void {
    $user = require_auth();
    $role = $user['role'] ?? '';
    $b    = body();

    $target_type = $b['target_type'] ?? ''; // 'audio_point' | 'voice_tour'
    $target_id   = trim($b['target_id'] ?? '');
    $site_id     = trim($b['site_id']   ?? '');

    if (!in_array($target_type, ['audio_point','voice_tour'])) json_error('target_type không hợp lệ');
    if (empty($target_id) || empty($site_id)) json_error('Thiếu target_id hoặc site_id');

    // Admin/Superadmin bypass permission check
    if (!in_array($role, ['admin','superadmin'])) {
        if (!_check_editor_permission((int)$user['id'], $site_id)) {
            json_error('Bạn không có quyền biên tập điểm đến này', 403);
        }
    }

    // Đổi review_status → pending_review
    if ($target_type === 'audio_point') {
        db()->prepare("UPDATE audio_points SET review_status='pending_review' WHERE id=:id")
            ->execute([':id' => $target_id]);
        // Lấy thông tin để notify
        $s = db()->prepare("SELECT ap.title, hs.name AS site_name FROM audio_points ap LEFT JOIN heritage_sites hs ON hs.id=ap.site_id WHERE ap.id=:id");
        $s->execute([':id' => $target_id]);
    } else {
        db()->prepare("UPDATE voice_tours SET review_status='pending_review' WHERE id=:id")
            ->execute([':id' => $target_id]);
        $s = db()->prepare("SELECT vt.title, hs.name AS site_name FROM voice_tours vt LEFT JOIN heritage_sites hs ON hs.id=vt.site_id WHERE vt.id=:id");
        $s->execute([':id' => $target_id]);
    }
    $info = $s->fetch();

    // Notify reviewers của site này
    $reviewers = db()->prepare("
        SELECT u.email, u.display_name
        FROM user_site_permissions p
        JOIN users u ON u.id = p.user_id
        WHERE p.site_id = :s AND p.can_review = 1 AND u.status = 'active'
    ");
    $reviewers->execute([':s' => $site_id]);
    foreach ($reviewers->fetchAll() as $rv) {
        _notify_review($rv['email'], $rv['display_name'], 'submit', $info['title']??$target_id, $info['site_name']??$site_id);
    }

    json_ok(null, 'Đã gửi yêu cầu thẩm định');
}

// ── PENDING LIST (Reviewer xem danh sách chờ) ─────────────────
function review_pending(): void {
    $user = require_auth();
    $role = $user['role'] ?? '';

    // Admin: xem tất cả; Reviewer: chỉ xem site được assign
    if (in_array($role, ['admin','superadmin'])) {
        $ap = db()->prepare("
            SELECT ap.id, ap.title, ap.site_id, hs.name AS site_name,
                   'audio_point' AS target_type, ap.review_status,
                   ap.author AS created_by_name, ap.updated_at
            FROM audio_points ap
            LEFT JOIN heritage_sites hs ON hs.id = ap.site_id
            WHERE ap.review_status = 'pending_review'
            ORDER BY ap.updated_at DESC
        ");
        $ap->execute();

        $vt = db()->prepare("
            SELECT vt.id, vt.title, vt.site_id, hs.name AS site_name,
                   'voice_tour' AS target_type, vt.review_status,
                   NULL AS created_by_name, vt.updated_at
            FROM voice_tours vt
            LEFT JOIN heritage_sites hs ON hs.id = vt.site_id
            WHERE vt.review_status = 'pending_review'
            ORDER BY vt.updated_at DESC
        ");
        $vt->execute();
    } else {
        // Lấy danh sách site reviewer được assign
        $sites_q = db()->prepare("SELECT site_id FROM user_site_permissions WHERE user_id=:u AND can_review=1");
        $sites_q->execute([':u' => $user['id']]);
        $site_ids = array_column($sites_q->fetchAll(), 'site_id');

        if (empty($site_ids)) json_ok([]);

        $placeholders = implode(',', array_fill(0, count($site_ids), '?'));

        $ap = db()->prepare("
            SELECT ap.id, ap.title, ap.site_id, hs.name AS site_name,
                   'audio_point' AS target_type, ap.review_status,
                   ap.author AS created_by_name, ap.updated_at
            FROM audio_points ap
            LEFT JOIN heritage_sites hs ON hs.id = ap.site_id
            WHERE ap.review_status = 'pending_review' AND ap.site_id IN ($placeholders)
            ORDER BY ap.updated_at DESC
        ");
        $ap->execute($site_ids);

        $vt = db()->prepare("
            SELECT vt.id, vt.title, vt.site_id, hs.name AS site_name,
                   'voice_tour' AS target_type, vt.review_status,
                   NULL AS created_by_name, vt.updated_at
            FROM voice_tours vt
            LEFT JOIN heritage_sites hs ON hs.id = vt.site_id
            WHERE vt.review_status = 'pending_review' AND vt.site_id IN ($placeholders)
            ORDER BY vt.updated_at DESC
        ");
        $vt->execute($site_ids);
    }

    $results = array_merge($ap->fetchAll(), $vt->fetchAll());
    usort($results, fn($a,$b) => strtotime($b['updated_at']) - strtotime($a['updated_at']));
    json_ok($results);
}

// ── APPROVE ───────────────────────────────────────────────────
function review_approve(): void {
    $user = require_auth();
    $role = $user['role'] ?? '';
    $b    = body();

    $target_type = $b['target_type'] ?? '';
    $target_id   = trim($b['target_id'] ?? '');
    $site_id     = trim($b['site_id']   ?? '');

    if (!in_array($target_type, ['audio_point','voice_tour'])) json_error('target_type không hợp lệ');

    if (!in_array($role, ['admin','superadmin'])) {
        if (!_check_reviewer_permission((int)$user['id'], $site_id)) {
            json_error('Bạn không có quyền thẩm định điểm đến này', 403);
        }
    }

    if ($target_type === 'audio_point') {
        db()->prepare("UPDATE audio_points SET review_status='active', status='active', reviewer=:rv, reviewed_by=:rb, reviewed_at=NOW() WHERE id=:id")
            ->execute([':id' => $target_id, ':rv' => $user['display_name'], ':rb' => $user['id']]);
        $s = db()->prepare("SELECT ap.title, ap.author AS created_by, hs.name AS site_name FROM audio_points ap LEFT JOIN heritage_sites hs ON hs.id=ap.site_id WHERE ap.id=:id");
        $s->execute([':id' => $target_id]);
    } else {
        // Approve tour → approve tất cả audio_points trong tour
        db()->prepare("UPDATE voice_tours SET review_status='active', status='active' WHERE id=:id")
            ->execute([':id' => $target_id]);
        db()->prepare("UPDATE audio_points SET review_status='active', status='active' WHERE tour_id=:id AND review_status='pending_review'")
            ->execute([':id' => $target_id]);
        $s = db()->prepare("SELECT vt.title, NULL AS created_by, hs.name AS site_name FROM voice_tours vt LEFT JOIN heritage_sites hs ON hs.id=vt.site_id WHERE vt.id=:id");
        $s->execute([':id' => $target_id]);
    }
    $info = $s->fetch();

    // Log
    db()->prepare("INSERT INTO review_logs (reviewer_id,target_type,target_id,site_id,action) VALUES(:r,:t,:tid,:s,'approve')")
        ->execute([':r'=>$user['id'],':t'=>$target_type,':tid'=>$target_id,':s'=>$site_id]);

    // Notify editor
    if (!empty($info['created_by'])) {
        $editor = db()->prepare("SELECT email, display_name FROM users WHERE id=:id");
        $editor->execute([':id' => $info['created_by']]);
        $ed = $editor->fetch();
        if ($ed) _notify_review($ed['email'], $ed['display_name'], 'approve', $info['title']??$target_id, $info['site_name']??$site_id);
    }

    json_ok(null, 'Đã phê duyệt');
}

// ── REJECT ────────────────────────────────────────────────────
function review_reject(): void {
    $user = require_auth();
    $role = $user['role'] ?? '';
    $b    = body();

    $target_type = $b['target_type'] ?? '';
    $target_id   = trim($b['target_id'] ?? '');
    $site_id     = trim($b['site_id']   ?? '');
    $note        = trim($b['note']      ?? '');

    if (!in_array($target_type, ['audio_point','voice_tour'])) json_error('target_type không hợp lệ');

    if (!in_array($role, ['admin','superadmin'])) {
        if (!_check_reviewer_permission((int)$user['id'], $site_id)) {
            json_error('Bạn không có quyền thẩm định điểm đến này', 403);
        }
    }

    if ($target_type === 'audio_point') {
        db()->prepare("UPDATE audio_points SET review_status='rejected' WHERE id=:id")
            ->execute([':id' => $target_id]);
        $s = db()->prepare("SELECT ap.title, ap.author AS created_by, hs.name AS site_name FROM audio_points ap LEFT JOIN heritage_sites hs ON hs.id=ap.site_id WHERE ap.id=:id");
        $s->execute([':id' => $target_id]);
    } else {
        db()->prepare("UPDATE voice_tours SET review_status='rejected' WHERE id=:id")
            ->execute([':id' => $target_id]);
        $s = db()->prepare("SELECT vt.title, vt.created_by, hs.name AS site_name FROM voice_tours vt LEFT JOIN heritage_sites hs ON hs.id=vt.site_id WHERE vt.id=:id");
        $s->execute([':id' => $target_id]);
    }
    $info = $s->fetch();

    // Log với ghi chú
    db()->prepare("INSERT INTO review_logs (reviewer_id,target_type,target_id,site_id,action,note) VALUES(:r,:t,:tid,:s,'reject',:n)")
        ->execute([':r'=>$user['id'],':t'=>$target_type,':tid'=>$target_id,':s'=>$site_id,':n'=>$note]);

    // Notify editor
    if (!empty($info['created_by'])) {
        $editor = db()->prepare("SELECT email, display_name FROM users WHERE id=:id");
        $editor->execute([':id' => $info['created_by']]);
        $ed = $editor->fetch();
        if ($ed) _notify_review($ed['email'], $ed['display_name'], 'reject', $info['title']??$target_id, $info['site_name']??$site_id, $note);
    }

    json_ok(null, 'Đã từ chối');
}

// ── LOGS ──────────────────────────────────────────────────────
function review_logs(): void {
    require_admin_role();
    $site_id = str_param('site_id');
    $where = []; $params = [];
    if ($site_id) { $where[] = 'l.site_id=:s'; $params[':s'] = $site_id; }
    $w = $where ? 'WHERE '.implode(' AND ',$where) : '';

    $stmt = db()->prepare("
        SELECT l.*, u.display_name AS reviewer_name
        FROM review_logs l
        LEFT JOIN users u ON u.id = l.reviewer_id
        $w
        ORDER BY l.created_at DESC
        LIMIT 100
    ");
    foreach ($params as $k=>$v) $stmt->bindValue($k,$v);
    $stmt->execute();
    json_ok($stmt->fetchAll());
}
