<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/sites.php';
require_once __DIR__ . '/tours.php';
require_once __DIR__ . '/audio.php';
require_once __DIR__ . '/qr.php';
require_once __DIR__ . '/offline.php';
require_once __DIR__ . '/analytics.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/review.php';
require_once __DIR__ . '/users.php';
require_once __DIR__ . '/favorites.php';

require_once __DIR__ . '/ratings.php';
require_once __DIR__ . '/mailer.php';
require_once __DIR__ . '/tour.php';
require_once __DIR__ . '/languages.php';
require_once __DIR__ . '/guide.php';
require_once __DIR__ . '/partners.php';
require_once __DIR__ . '/partner_upload.php';
require_once __DIR__ . '/partner_booking.php';
require_once __DIR__ . '/app_settings.php';
require_once __DIR__ . '/audit.php';

cors();

$method   = $_SERVER['REQUEST_METHOD'];
$uri      = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri      = preg_replace('#^.*?/api#', '', $uri);
$segments = array_values(array_filter(explode('/', trim($uri, '/'))));

$r   = $segments[0] ?? '';
$id  = $segments[1] ?? null;
$sub = $segments[2] ?? null;
$sub2 = $segments[3] ?? null;
$sub3 = $segments[4] ?? null;

try {
    match(true) {
        $r==='heritage-sites' && $id==='nearby'                    && $method==='GET'    => sites_nearby(),
        $r==='heritage-sites' && $id && $sub==='reviews' && !$sub2 && $method==='GET'  => site_reviews_list($id),
        $r==='heritage-sites' && $id && $sub==='reviews' && !$sub2 && $method==='POST' => site_review_submit($id),
        $r==='heritage-sites' && $id===null                        && $method==='GET'    => sites_list(),
        $r==='heritage-sites' && $id===null                        && $method==='POST'   => (require_admin() ?: site_create()),
        $r==='heritage-sites' && $id && !$sub                      && $method==='GET'    => site_detail($id),
        $r==='heritage-sites' && $id && !$sub                      && $method==='PUT'    => (require_admin() ?: site_update($id)),
        $r==='heritage-sites' && $id && !$sub                      && $method==='DELETE' => (require_admin() ?: site_delete($id)),
        $r==='heritage-sites' && $id && $sub==='voice-tours'       && $method==='GET'    => site_tours($id),
        $r==='voice-tours' && $id===null                           && $method==='GET'    => tour_list(),
        $r==='voice-tours' && $id===null                           && $method==='POST'   => (require_admin() ?: tour_create()),
        $r==='voice-tours' && $id && !$sub                         && $method==='GET'    => tour_detail($id),
        $r==='voice-tours' && $id && !$sub                         && $method==='PUT'    => (require_admin() ?: tour_update($id)),
        $r==='voice-tours' && $id && $sub==='audio-points'         && $method==='GET'    => tour_audio_points($id),
        $r==='audio-points' && $id===null                          && $method==='GET'    => audio_list(),
        $r==='audio-points' && $id===null                          && $method==='POST'   => (require_admin() ?: audio_create()),
        $r==='audio-points' && $id                                 && $method==='GET'    => audio_detail($id),
        $r==='audio-points' && $id                                 && $method==='PUT'    => (require_admin() ?: audio_update($id)),
        $r==='audio-points' && $id                                 && $method==='DELETE' => (require_admin() ?: audio_delete($id)),
        $r==='offline-packs' && $id                                && $method==='GET'    => offline_pack($id),
        $r==='qr' && $id==='for' && $sub && $sub2           && $method==='GET'    => qr_for($sub,$sub2),
        $r==='qr' && $id==='seed'                                        && $method==='POST'   => qr_seed(),
        $r==='qr' && $id                                           && $method==='GET'    => qr_resolve($id),
        $r==='qr' && $id===null                                    && $method==='GET'    => qr_list(),
        $r==='qr' && $id===null                                    && $method==='POST'   => qr_create(),
        $r==='qr' && $id                                           && $method==='PUT'    => qr_update($id),
        $r==='qr' && $id                                           && $method==='DELETE' => qr_delete($id),
        $r==='review' && $id==='submit'                              && $method==='POST'   => review_submit(),
        $r==='review' && $id==='pending'                             && $method==='GET'    => review_pending(),
        $r==='review' && $id==='approve'                             && $method==='POST'   => review_approve(),
        $r==='review' && $id==='reject'                              && $method==='POST'   => review_reject(),
        $r==='review' && $id==='logs'                                && $method==='GET'    => review_logs(),
        $r==='analytics' && $sub==='listen-events'                 && $method==='POST'   => analytics_listen(),
        $r==='analytics' && $id && $sub==='listen-events'          && $method==='GET'    => (require_admin() ?: analytics_summary($id)),
        $r==='auth' && $id==='request-reset'                      && $method==='POST'   => auth_request_reset(),
        $r==='auth' && $id==='do-reset'                             && $method==='POST'   => auth_do_reset(),
        $r==='auth' && $id==='verify'                               && $method==='GET'    => auth_verify_email(),
        $r==='auth' && $id==='resend-verify'                        && $method==='POST'   => auth_resend_verify(),
        $r==='auth' && $id==='register'                            && $method==='POST'   => auth_register(),
        $r==='auth' && $id==='login'                               && $method==='POST'   => auth_login(),
        $r==='auth' && $id==='me'                                  && $method==='GET'    => auth_me(),
        $r==='auth' && $id==='me'                                  && $method==='PUT'    => auth_update_profile(),
        $r==='auth' && $id==='refresh'                             && $method==='POST'   => auth_refresh(),
        $r==='auth' && $id==='upload-avatar'                      && $method==='POST'   => auth_upload_avatar(),
        $r==='users' && $id==='export'                             && $method==='GET'    => users_export(),
        $r==='users' && $id===null                                 && $method==='GET'    => users_list(),
        $r==='users' && $id===null                                 && $method==='POST'   => user_create(),
        $r==='users' && $id && $sub==='password'                   && $method==='PUT'    => user_reset_password($id),
        $r==='users' && $id && $sub==='permissions'                && $method==='GET'    => user_get_permissions($id),
        $r==='users' && $id && $sub==='permissions'                && $method==='PUT'    => user_set_permissions($id),
        $r==='users' && $id && $sub==='permissions'                && $method==='DELETE' => user_delete_permission($id),
        $r==='users' && $id                                        && $method==='GET'    => user_detail($id),
        $r==='users' && $id                                        && $method==='PUT'    => user_update($id),
        $r==='tours' && $id===null                                && $method==='GET'    => tours_list(),
        $r==='tours' && $id===null                                && $method==='POST'   => tours_create(),
        $r==='tours' && $id && !$sub                             && $method==='GET'    => tours_get($id),
        $r==='tours' && $id && !$sub                             && $method==='PUT'    => tours_update($id),
        $r==='tours' && $id && !$sub                             && $method==='DELETE' => tours_delete($id),
        $r==='tours' && $id && $sub==='items' && !$sub2         && $method==='POST'   => tours_add_item($id),
        $r==='tours' && $id && $sub==='items' && $sub2          && $method==='PUT'    => tours_update_item($id,$sub2),
        $r==='tours' && $id && $sub==='items' && $sub2          && $method==='DELETE' => tours_delete_item($id,$sub2),
        $r==='tours' && $id && $sub==='reorder'                  && $method==='POST'   => tours_reorder($id),
        $r==='tours' && $id && $sub==='items' && $sub2 && $sub3==='booking' && $method==='POST' => tours_attach_booking($id,$sub2),
        $r==='favorites' && $id===null                             && $method==='GET'    => favorites_list(),
        $r==='favorites' && $id===null                             && $method==='POST'   => favorite_add(),
        $r==='favorites' && $id && $sub==='check'                  && $method==='GET'    => favorite_check($id),
        $r==='favorites' && $id                                    && $method==='DELETE' => favorite_remove($id),
        $r==='history' && $id===null                               && $method==='GET'    => history_list(),
        $r==='history' && $id===null                               && $method==='POST'   => history_add(),
        $r==='ratings' && $id===null                               && $method==='POST'   => rating_add(),
        $r==='ratings' && $id && $sub==='me'                       && $method==='GET'    => rating_me($id),
        $r==='ratings' && $id                                      && $method==='GET'    => rating_get($id),
        $r==='mailer'  && $id===null                               && $method==='POST'   => mailer_send(),
        $r==='guide' && $id==='my-permissions'                      && $method==='GET'    => guide_my_permissions(),
        $r==='guide' && $id==='apply'                               && $method==='POST'   => guide_apply(),
        $r==='guide' && $id==='my-application'                      && $method==='GET'    => guide_my_application(),
        $r==='guide' && $id==='applications'  && !$sub              && $method==='GET'    => guide_applications_list(),
        $r==='guide' && $id==='applications'  && $sub && $sub2==='approve' && $method==='POST' => guide_approve($sub),
        $r==='guide' && $id==='applications'  && $sub && $sub2==='reject'  && $method==='POST' => guide_reject($sub),
        $r==='guide' && $id==='analytics'                           && $method==='GET'    => guide_analytics(),
        $r==='audio-localizations' && $id===null                    && $method==='GET'    => i18n_audio_list(),
        $r==='audio-localizations' && $id===null                    && $method==='POST'   => i18n_audio_save(),
        $r==='audio-localizations' && $id                           && $method==='DELETE' => i18n_audio_delete($id),
        $r==='content-translations' && $id===null                   && $method==='GET'    => i18n_text_list(),
        $r==='content-translations' && $id===null                   && $method==='POST'   => i18n_text_save(),
        $r==='tour-guide' && $id==='my-session'                    && $method==='GET'    => tg_my_session(),
        $r==='tour-guide' && $id==='create'                          && $method==='POST'   => tg_create(),
        $r==='tour-guide' && $id==='join'                            && $method==='POST'   => tg_join(),
        $r==='tour-guide' && $id && $sub==='state'                   && $method==='GET'    => tg_state($id),
        $r==='tour-guide' && $id && $sub==='command'                 && $method==='POST'   => tg_command($id),
        $r==='tour-guide' && $id && $sub==='answer'                  && $method==='POST'   => tg_answer($id),
        $r==='tour-guide' && $id && $sub==='ping'                    && $method==='POST'   => tg_ping($id),
        $r==='tour-guide' && $id && $sub==='leave'                   && $method==='POST'   => tg_leave($id),
        $r==='tour-guide' && $id && $sub==='members'                 && $method==='GET'    => tg_members($id),
        $r==='ai'      && $id==='chat'                              && $method==='POST'   => (include __DIR__.'/ai.php'),
        
        $r==='audit-log'   && $id===null && $method==='GET'  => audit_log_list(),
        $r==='app-settings' && $id===null && $method==='GET'  => app_settings_get(),
        $r==='app-settings' && $id===null && $method==='PUT'  => app_settings_update(),
        $r==='partner-booking' && $id===null && $method==='POST' => partner_booking(),
        $r==='bookings' && $id==='proof-upload' && $method==='POST' => booking_upload_proof(),
        $r==='bookings' && $id==='proof' && $method==='POST' => booking_save_proof(),
        $r==='partner-reviews' && $id==='pending' && $method==='GET'  => partner_reviews_pending(),
        $r==='partner-reviews' && $id && $method==='PUT'  => partner_review_update($id),
        $r==='partner-upload' && $id===null         && $method==='POST' => partner_upload(),
        $r==='partners' && $id==='me'               && $method==='GET'  => partner_my_profile(),
        $r==='partners' && $id==='nearby'           && $method==='GET'  => partners_nearby(),
        $r==='partners' && $id==='reports'          && $method==='GET'  => partners_reports(),
        $r==='partners' && $id===null               && $method==='GET'  => partners_list(),
        $r==='partners' && $id===null               && $method==='POST' => partner_register(),
        $r==='partners' && $id && !$sub             && $method==='GET'  => partner_detail($id),
        $r==='partners' && $id && !$sub             && $method==='PUT'  => partner_update($id),
        $r==='partners' && $id && $sub==='status'   && $method==='PUT'  => partner_set_status($id),
        $r==='partners' && $id && $sub==='vouchers' && $sub2 && $sub3==='status' && $method==='PUT'  => partner_voucher_toggle($id, $sub2),
        $r==='partners' && $id && $sub==='vouchers' && $sub2==='validate' && $method==='POST' => partner_voucher_validate($id),
        $r==='partners' && $id && $sub==='vouchers' && $sub2                    && $method==='PUT'  => partner_voucher_update($id, $sub2),
        $r==='partners' && $id && $sub==='vouchers' && $method==='GET'  => partner_vouchers($id),
        $r==='partners' && $id && $sub==='vouchers' && $method==='POST' => partner_voucher_create($id),
        $r==='partners' && $id && $sub==='click'    && $method==='POST' => partner_click($id),
        $r==='partners' && $id && $sub==='review'   && $method==='POST' => partner_review_submit($id),
        $r==='partners' && $id && $sub==='reviews'  && $method==='GET'  => partner_reviews_list($id),
        $r==='partners' && $id && $sub==='reviews' && $sub3==='like'  && $method==='POST' => partner_review_like($id, $sub2),
        $r==='partners' && $id && $sub==='bookings' && !$sub2           && $method==='GET'  => partner_bookings_list($id),
        $r==='partners' && $id && $sub==='bookings' && $sub2 && $sub3==='paid'    && $method==='PUT'  => partner_booking_mark_paid($id, $sub2),
        $r==='partners' && $id && $sub==='bookings' && $sub2 && !$sub3 && $method==='PUT'  => partner_booking_update($id, $sub2),
        $r==='partners' && $id && $sub==='rooms'    && $method==='GET'  => partner_rooms_list($id),
        $r==='partners' && $id && $sub==='rooms'    && $method==='POST' => partner_rooms_save($id),
        $r==='partners' && $id && $sub==='menu'     && $method==='GET'  => partner_menu_list($id),
        $r==='partners' && $id && $sub==='menu'     && $method==='POST' => partner_menu_save($id),
        $r==='partners' && $id && $sub==='reviews' && $sub3==='reply' && $method==='POST' => partner_review_reply($id, $sub2),
        default => json_error('Endpoint not found', 404),
    };
} catch (PDOException $e) {
    error_log('[HV Route PDO] ' . $e->getMessage());
    error_log('[HV DB] ' . $e->getMessage());
    json_error('Database error', 500);
} catch (RuntimeException $e) {
    json_error($e->getMessage(), $e->getCode() ?: 500);
} catch (Throwable $e) {
    error_log('[HV Throwable] ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    json_error('Internal server error', 500);
}
