<?php
/**
 * Heritage Voice — guide.php
 * API cho đăng ký Hướng dẫn viên
 *
 * GET    /api/guide/my-permissions     Lấy danh sách site user được guide
 * POST   /api/guide/apply              Gửi đơn đăng ký HDV
 * GET    /api/guide/my-application     Xem trạng thái đơn của mình
 * GET    /api/guide/applications       Danh sách đơn pending (admin)
 * POST   /api/guide/applications/{id}/approve  Duyệt đơn (admin)
 * POST   /api/guide/applications/{id}/reject   Từ chối đơn (admin)
 * GET    /api/guide/analytics          Thống kê HDV (admin)
 */

// ── 1. Lấy danh sách site user được guide ────────────────────
function guide_my_permissions(): void {
    $uid = get_token_uid();
    if (!$uid) json_error('Unauthorized', 401);

    $stmt = db()->prepare("
        SELECT p.site_id, p.can_guide, hs.name AS site_name, hs.cover_image,
               (SELECT COUNT(*) FROM tour_sessions ts
                WHERE ts.host_user_id = :uid1 AND ts.site_id = p.site_id
                  AND ts.status = 'ended') AS total_tours
        FROM user_site_permissions p
        LEFT JOIN heritage_sites hs ON hs.id = p.site_id
        WHERE p.user_id = :uid2 AND p.can_guide = 1
        ORDER BY hs.name ASC
    ");
    $stmt->execute([':uid1' => $uid, ':uid2' => $uid]);
    json_ok($stmt->fetchAll());
}

// ── 2. Gửi đơn đăng ký HDV ───────────────────────────────────
function guide_apply(): void {
    $uid = get_token_uid();
    if (!$uid) json_error('Unauthorized', 401);

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

    if (!$site_id) json_error('Thiếu site_id');

    // Kiểm tra site tồn tại
    $s = db()->prepare("SELECT id, name FROM heritage_sites WHERE id=:id AND status='active'");
    $s->execute([':id' => $site_id]);
    if (!$s->fetch()) json_error('Di sản không tồn tại', 404);

    // Kiểm tra đã có quyền chưa
    $ck = db()->prepare("SELECT can_guide FROM user_site_permissions WHERE user_id=:u AND site_id=:s");
    $ck->execute([':u' => $uid, ':s' => $site_id]);
    $perm = $ck->fetch();
    if ($perm && $perm['can_guide']) json_error('Bạn đã có quyền hướng dẫn viên tại di sản này', 409);

    // Kiểm tra đã có đơn pending chưa
    $ck2 = db()->prepare("SELECT id, status FROM guide_applications WHERE user_id=:u AND site_id=:s");
    $ck2->execute([':u' => $uid, ':s' => $site_id]);
    $existing = $ck2->fetch();
    if ($existing && $existing['status'] === 'pending') json_error('Đơn của bạn đang chờ xét duyệt', 409);

    // Upsert đơn
    db()->prepare("
        INSERT INTO guide_applications (user_id, site_id, note, status, created_at)
        VALUES (:u, :s, :n, 'pending', NOW())
        ON DUPLICATE KEY UPDATE note=VALUES(note), status='pending', updated_at=NOW()
    ")->execute([':u' => $uid, ':s' => $site_id, ':n' => $note]);

    json_ok(null, 'Đã gửi đơn đăng ký. Admin sẽ xét duyệt sớm!');
}

// ── 3. Xem trạng thái đơn của mình ───────────────────────────
function guide_my_application(): void {
    $uid = get_token_uid();
    if (!$uid) json_error('Unauthorized', 401);

    $stmt = db()->prepare("
        SELECT ga.*, hs.name AS site_name, hs.cover_image
        FROM guide_applications ga
        LEFT JOIN heritage_sites hs ON hs.id = ga.site_id
        WHERE ga.user_id = :uid
        ORDER BY ga.updated_at DESC
    ");
    $stmt->execute([':uid' => $uid]);
    json_ok($stmt->fetchAll());
}

// ── 4. Danh sách đơn pending (admin) ─────────────────────────
function guide_applications_list(): void {
    require_admin_role();
    $status = str_param('status', 'pending');

    $where  = $status !== 'all' ? 'WHERE ga.status = :status' : '';
    $params = $status !== 'all' ? [':status' => $status] : [];

    $stmt = db()->prepare("
        SELECT ga.*, 
               u.display_name AS user_name, u.email AS user_email, u.avatar_url,
               hs.name AS site_name, hs.cover_image
        FROM guide_applications ga
        LEFT JOIN users u ON u.id = ga.user_id
        LEFT JOIN heritage_sites hs ON hs.id = ga.site_id
        $where
        ORDER BY ga.created_at DESC
    ");
    $stmt->execute($params);
    json_ok($stmt->fetchAll());
}

// ── 5. Duyệt đơn (admin) ─────────────────────────────────────
function guide_approve(string $id): void {
    require_admin_role();
    $me = get_token_uid();

    $s = db()->prepare("SELECT * FROM guide_applications WHERE id=:id");
    $s->execute([':id' => $id]);
    $app = $s->fetch();
    if (!$app) json_error('Không tìm thấy đơn', 404);

    // Cập nhật status đơn
    db()->prepare("
        UPDATE guide_applications 
        SET status='approved', reviewed_by=:by, updated_at=NOW()
        WHERE id=:id
    ")->execute([':by' => $me, ':id' => $id]);

    // Set can_guide = 1
    db()->prepare("
        INSERT INTO user_site_permissions (user_id, site_id, can_guide, created_by)
        VALUES (:u, :s, 1, :by)
        ON DUPLICATE KEY UPDATE can_guide=1
    ")->execute([':u' => $app['user_id'], ':s' => $app['site_id'], ':by' => $me]);

    json_ok(null, 'Đã duyệt. User có thể dẫn tour tại di sản này.');
}

// ── 6. Từ chối đơn (admin) ────────────────────────────────────
function guide_reject(string $id): void {
    require_admin_role();
    $me   = get_token_uid();
    $b    = body();
    $note = trim($b['admin_note'] ?? '');

    db()->prepare("
        UPDATE guide_applications
        SET status='rejected', admin_note=:note, reviewed_by=:by, updated_at=NOW()
        WHERE id=:id
    ")->execute([':note' => $note, ':by' => $me, ':id' => $id]);

    json_ok(null, 'Đã từ chối đơn.');
}

// ── 7. Analytics HDV ─────────────────────────────────────────
function guide_analytics(): void {
    require_admin_role();

    // Tổng HDV
    $s1 = db()->prepare("SELECT COUNT(DISTINCT user_id) FROM user_site_permissions WHERE can_guide=1");
    $s1->execute();
    $total_guides = (int)$s1->fetchColumn();

    // Tour hôm nay
    $s2 = db()->prepare("SELECT COUNT(*) FROM tour_sessions WHERE DATE(created_at)=CURDATE()");
    $s2->execute();
    $tours_today = (int)$s2->fetchColumn();

    // Khách hôm nay
    $s3 = db()->prepare("SELECT COALESCE(SUM(member_count),0) FROM tour_sessions WHERE DATE(created_at)=CURDATE()");
    $s3->execute();
    $guests_today = (int)$s3->fetchColumn();

    // Đơn pending
    $s4 = db()->prepare("SELECT COUNT(*) FROM guide_applications WHERE status='pending'");
    $s4->execute();
    $pending_apps = (int)$s4->fetchColumn();

    // Top HDV
    $top = db()->prepare("
        SELECT u.display_name, u.email, u.avatar_url,
               COUNT(ts.id) AS total_tours,
               COALESCE(SUM(ts.member_count),0) AS total_guests,
               GROUP_CONCAT(DISTINCT hs.name SEPARATOR ', ') AS sites
        FROM tour_sessions ts
        JOIN users u ON u.id = ts.host_user_id
        LEFT JOIN heritage_sites hs ON hs.id = ts.site_id
        WHERE ts.status = 'ended'
        GROUP BY ts.host_user_id
        ORDER BY total_tours DESC
        LIMIT 10
    ");
    $top->execute();
    $top_guides = $top->fetchAll();

    // Ngôn ngữ phổ biến
    $langs = db()->prepare("
        SELECT lang, COUNT(*) AS cnt
        FROM tour_session_members
        WHERE left_at IS NOT NULL
        GROUP BY lang ORDER BY cnt DESC
    ");
    $langs->execute();
    $lang_stats = $langs->fetchAll();

    // Tour theo ngày (7 ngày gần nhất)
    $daily = db()->prepare("
        SELECT DATE(created_at) AS date,
               COUNT(*) AS tours,
               COALESCE(SUM(member_count),0) AS guests
        FROM tour_sessions
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
        GROUP BY DATE(created_at)
        ORDER BY date ASC
    ");
    $daily->execute();
    $daily_stats = $daily->fetchAll();

    json_ok([
        'total_guides'  => $total_guides,
        'tours_today'   => $tours_today,
        'guests_today'  => $guests_today,
        'pending_apps'  => $pending_apps,
        'top_guides'    => $top_guides,
        'lang_stats'    => $lang_stats,
        'daily_stats'   => $daily_stats,
    ]);
}
