<?php
// Set error log ke file sendiri
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/error.log');

/**
 * index.php - Router Utama Aplikasi
 * Menangani semua request dan routing
 * DIPERBAIKI - Routing untuk Claim Pengembalian Dana
 */

// ============================================
// START SESSION
// ============================================
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ============================================
// ERROR REPORTING (Hapus di production)
// ============================================
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../error.log');

// ============================================
// DEFINISI BASE_URL
// ============================================
define('BASE_URL', '/reservasi-kapal-wisata');
define('BASE_PATH', __DIR__ . '/..');

// ============================================
// KONEKSI DATABASE
// ============================================
require_once __DIR__ . '/../config/database.php';

// ============================================
// AUTO-LOAD CONTROLLER
// ============================================
spl_autoload_register(function($class) {
    $file = __DIR__ . '/../controllers/' . $class . '.php';
    if (file_exists($file)) {
        require_once $file;
    }
});

// ============================================
// AMBIL PARAMETER URL
// ============================================
$page = isset($_GET['page']) ? $_GET['page'] : 'home';
$action = isset($_GET['action']) ? $_GET['action'] : 'index';

// ================================================================
// 🔥 HANDLE AJAX REQUESTS TERLEBIH DAHULU
// ================================================================
$ajaxActions = [
    // Admin AJAX
    'confirmPesanan',
    'cancelPesanan',
    'getAdminNotifications',
    
    // 🔥 NOTIFIKASI AJAX - SEMUA ACTION NOTIFIKASI
    'getUnreadCount',
    'notificationCount',
    'getNotifications',
    'markAsRead',
    'bacaNotifikasi',
    'markAllAsRead',
    'bacaSemuaNotifikasi',
    'deleteNotification',
    'clearAllNotifications',
    'updateSessionFoto',
    'loadMoreNotifications',
    'getUserData',
    
    // Admin lainnya
    'getSupirDetail',
    'aktifkanSupir',
    'nonaktifkanSupir',
    'verifikasiKapal',
    'prosesRequestHapus',
    'prosesKonfirmasiPembayaran',
    'prosesPencairanDana',
    'prosesClaim',
    
    // Supir AJAX
    'updateStatusPesanan',
    'konfirmasiReschedule',
    
    // 🔥 SALDO AJAX
    'getSaldo',
    'getSaldoAjax',
];

if (in_array($action, $ajaxActions)) {
    // Tentukan controller yang sesuai
    $controller = null;
    
    // Admin Actions
    $adminActions = [
        'confirmPesanan', 
        'cancelPesanan', 
        'getAdminNotifications', 
        'verifikasiKapal', 
        'prosesRequestHapus', 
        'prosesKonfirmasiPembayaran',
        'prosesPencairanDana', 
        'prosesClaim', 
        'getSupirDetail', 
        'aktifkanSupir', 
        'nonaktifkanSupir'
    ];
    
    // Supir Actions (AJAX)
    $supirAjaxActions = [
        'updateStatusPesanan', 
        'konfirmasiReschedule',
        'markAsRead',
        'markAllAsRead',
        'deleteNotification',
        'getUnreadCount'
    ];
    
    // 🔥 WISATAWAN ACTIONS (Notifikasi AJAX)
    $wisatawanAjaxActions = [
        'getUnreadCount',
        'notificationCount',
        'getNotifications',
        'markAsRead',
        'bacaNotifikasi',
        'markAllAsRead',
        'bacaSemuaNotifikasi',
        'deleteNotification',
        'clearAllNotifications',
        'updateSessionFoto',
        'loadMoreNotifications',
        'getUserData',
        'getSaldo',
        'getSaldoAjax'
    ];
    
    // Admin AJAX
    if (in_array($action, $adminActions)) {
        require_once __DIR__ . '/../controllers/AdminController.php';
        $controller = new AdminController($pdo);
    } 
    // Supir AJAX
    elseif (in_array($action, $supirAjaxActions)) {
        require_once __DIR__ . '/../controllers/SupirController.php';
        $controller = new SupirController($pdo);
    } 
    // Wisatawan AJAX atau Notifikasi (Cek role)
    elseif (in_array($action, $wisatawanAjaxActions) || in_array($action, $ajaxActions)) {
        // Cek role user untuk notifikasi
        if (isset($_SESSION['role'])) {
            if ($_SESSION['role'] === 'admin') {
                require_once __DIR__ . '/../controllers/AdminController.php';
                $controller = new AdminController($pdo);
            } elseif ($_SESSION['role'] === 'pemilik_kapal' || $_SESSION['role'] === 'supir') {
                require_once __DIR__ . '/../controllers/SupirController.php';
                $controller = new SupirController($pdo);
            } else {
                require_once __DIR__ . '/../controllers/WisatawanController.php';
                $controller = new WisatawanController($pdo);
            }
        } else {
            // Default ke AuthController jika tidak login
            require_once __DIR__ . '/../controllers/AuthController.php';
            $controller = new AuthController($pdo);
        }
    } else {
        // Fallback ke AuthController
        require_once __DIR__ . '/../controllers/AuthController.php';
        $controller = new AuthController($pdo);
    }
    
    // Panggil method
    if ($controller && method_exists($controller, $action)) {
        $controller->$action();
    } else {
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false, 
            'message' => 'Method tidak ditemukan: ' . $action
        ]);
    }
    exit; // PENTING: Stop eksekusi setelah AJAX
}

// ================================================================
// ROUTING UTAMA
// ================================================================

switch($page) {
    
    // ==========================================
    // HALAMAN PUBLIK (Tanpa Login)
    // ==========================================
    case 'home':
        $controller = new HomeController($pdo);
        if(method_exists($controller, $action)) {
            $controller->$action();
        } else {
            $controller->index();
        }
        break;
        
    case 'tentang':
        $controller = new HomeController($pdo);
        if(method_exists($controller, $action)) {
            $controller->$action();
        } else {
            $controller->tentang();
        }
        break;
        
    case 'cara-booking':
        $controller = new HomeController($pdo);
        if(method_exists($controller, $action)) {
            $controller->$action();
        } else {
            $controller->caraBooking();
        }
        break;
        
    case 'kapal':
        $controller = new HomeController($pdo);
        if(method_exists($controller, $action)) {
            $controller->$action();
        } else {
            $controller->kapal();
        }
        break;
    
    // ==========================================
    // AUTHENTICATION (Login, Register, Logout)
    // ==========================================
    case 'login':
        $controller = new AuthController($pdo);
        if(method_exists($controller, $action)) {
            $controller->$action();
        } else {
            $controller->login();
        }
        break;
        
    case 'register':
        $controller = new AuthController($pdo);
        if(method_exists($controller, $action)) {
            $controller->$action();
        } else {
            $controller->register();
        }
        break;
        
    case 'logout':
        $controller = new AuthController($pdo);
        if(method_exists($controller, $action)) {
            $controller->$action();
        } else {
            $controller->logout();
        }
        break;
    
    // ==========================================
    // DASHBOARD ADMIN
    // ==========================================
    case 'admin':
        require_once __DIR__ . '/../controllers/AdminController.php';
        $controller = new AdminController($pdo);
        
        $adminActions = [
            'dashboard',
            'index',
            'profile',
            'profil',
            'editProfile',
            'updateProfile',
            'updateProfilePhoto',
            'updateSessionFoto',
            'kelolaKapal',
            'verifikasiKapal',
            'hapusKapal',
            'detailKapal',
            'requestHapusKapal',
            'prosesRequestHapus',
            'kelolaSupir',
            'getSupirDetail',
            'aktifkanSupir',
            'nonaktifkanSupir',
            'tambahSupir',
            'editSupir',
            'hapusSupir',
            'kelolaPesanan',
            'detailPesanan',
            'confirmPesanan',
            'cancelPesanan',
            'konfirmasiPembayaran',
            'prosesKonfirmasiPembayaran',
            'pencairanDana',
            'prosesPencairanDana',
            'claimPengembalian',
            'prosesClaim',
            'detailClaim',
            'laporan',
            'notifikasi',
            'notifications',
            'bacaNotifikasi',
            'bacaSemuaNotifikasi',
            'getUnreadCount',
            'markAsRead',
            'markAllAsRead',
            'deleteNotification',
            'clearAllNotifications',
            'getAdminNotifications',
        ];
        
        if (in_array($action, $adminActions) && method_exists($controller, $action)) {
            $controller->$action();
        } else {
            $_SESSION['flash_message'] = "Halaman tidak ditemukan.";
            $_SESSION['flash_type'] = 'warning';
            header("Location: ?page=admin&action=dashboard");
            exit;
        }
        break;
    
    // ==========================================
    // DASHBOARD SUPIR (PEMILIK KAPAL)
    // ==========================================
    case 'supir':
        require_once __DIR__ . '/../controllers/SupirController.php';
        $controller = new SupirController($pdo);
        
        $supirActions = [
            'dashboard',
            'index',
            'profile',
            'profil',
            'editProfile',
            'updateProfile',
            'updateProfilePhoto',
            'updateSessionFoto',
            'kelolaKapal',
            'tambahKapal',
            'editKapal',
            'hapusKapal',
            'detailKapal',
            'requestHapusKapal',
            'batalkanRequestHapus',
            'kelolaRute',
            'tambahRute',
            'editRute',
            'hapusRute',
            'updateRute',
            'kelolaRuteKapal',
            'kelolaJadwal',
            'tambahJadwal',
            'editJadwal',
            'hapusJadwal',
            'kelolaPesanan',
            'batalPesanan',
            'updateStatusPesanan',
            'detailPesanan',
            'konfirmasiReschedule',
            'pencairanDana',
            'sharedTrip',
            'notifikasi',
            'notifications',
            'bacaNotifikasi',
            'bacaSemuaNotifikasi',
            'getUnreadCount',
            'markAsRead',
            'markAllAsRead',
            'deleteNotification',
            'clearAllNotifications',
        ];
        
        if (in_array($action, $supirActions) && method_exists($controller, $action)) {
            $controller->$action();
        } else {
            $_SESSION['flash_message'] = "Halaman tidak ditemukan.";
            $_SESSION['flash_type'] = 'warning';
            header("Location: ?page=supir&action=dashboard");
            exit;
        }
        break;
    
    // ==========================================
// DASHBOARD WISATAWAN
// ==========================================
case 'wisatawan':
    require_once __DIR__ . '/../controllers/WisatawanController.php';
    $controller = new WisatawanController($pdo);
    
    $wisatawanActions = [
        'dashboard',
        'index',
        'saldo',
        'getSaldo',
        'getSaldoAjax',
        'tarikSaldo',              
        'prosesPembayaranSaldo',
        'profile',
        'profil',
        'editProfile',
        'updateProfile',
        'updateProfilePhoto',
        'updateSessionFoto',
        'cariKapal',
        'detailKapal',
        'booking',
        'prosesBooking',
        'pesananSaya',
        'riwayat',
        'riwayatPesanan',
        'status',
        'detailPesanan',
        'batalPesanan',
        'formBatalPesanan',
        'prosesBatalPesanan',
        'uploadPembayaran',
        'prosesUploadPembayaran',
        'prosesPembayaran',
        'pembayaran',
        'pembayaranSukses',
        'pembayaranPending',
        'ajukanClaim',
        'prosesClaim',  // <--- PASTIKAN INI ADA
        'claimPengembalian',
        'reschedule',
        'prosesReschedule',
        'selesaikanPerjalanan',
        'notifikasi',
        'notifications',
        'bacaNotifikasi',
        'bacaSemuaNotifikasi',
        'getUnreadCount',
        'markAsRead',
        'markAllAsRead',
        'deleteNotification',
        'clearAllNotifications',
        'notificationCount',
        'getNotifications',
        'loadMoreNotifications',
        'hapusNotifikasi',
    ];
    
    if (in_array($action, $wisatawanActions) && method_exists($controller, $action)) {
        $controller->$action();
    } else {
        // 🔥 JANGAN REDIRECT KE DASHBOARD, TAMPILKAN ERROR
        die("❌ Action tidak ditemukan: " . $action . "<br>File: index.php<br>Line: " . __LINE__);
    }
    break;
    
    // ==========================================
    // PAYMENT GATEWAY - MIDTRANS
    // ==========================================
    case 'payment':
        require_once __DIR__ . '/../controllers/PaymentController.php';
        $controller = new PaymentController($pdo);
        
        $paymentActions = [
            'notification',
            'finish',
            'unfinish',
            'error',
        ];
        
        if (in_array($action, $paymentActions) && method_exists($controller, $action)) {
            $controller->$action();
        } else {
            $_SESSION['flash_error'] = "Halaman pembayaran tidak valid.";
            header("Location: ?page=wisatawan&action=dashboard");
            exit;
        }
        break;
    
    // ==========================================
    // CRON JOB - NOTIFIKASI OTOMATIS
    // ==========================================
    case 'cron':
        if ($action == 'notifikasi_keberangkatan') {
            $token = $_GET['token'] ?? '';
            $validToken = 'your-secret-token-here-12345';
            
            if ($token !== $validToken) {
                http_response_code(403);
                die('Invalid token');
            }
            
            $cronFile = __DIR__ . '/../cron/notifikasi_keberangkatan.php';
            if (file_exists($cronFile)) {
                require_once $cronFile;
            } else {
                echo "❌ File cron tidak ditemukan: " . $cronFile;
            }
            exit;
        }
        break;
    
    // ==========================================
    // UPLOADS - SERVE FOTO
    // ==========================================
    case 'uploads':
        serveFile();
        break;
    
    // ==========================================
    // DEFAULT: 404 Not Found
    // ==========================================
    default:
        header("Location: ?page=home");
        exit;
}

// ================================================================
// FUNGSI SERVE FILE (FOTO)
// ================================================================
function serveFile() {
    $folder = isset($_GET['folder']) ? $_GET['folder'] : 'profile';
    $file = isset($_GET['file']) ? $_GET['file'] : '';
    
    $allowedFolders = ['profile', 'kapal', 'wisatawan', 'profil', 'bukti', 'notifikasi', 'supir', 'admin'];
    if (!in_array($folder, $allowedFolders)) {
        http_response_code(403);
        echo 'Folder tidak diizinkan';
        exit;
    }
    
    if (empty($file)) {
        http_response_code(404);
        echo 'File tidak ditemukan';
        exit;
    }
    
    $file = preg_replace('/[^a-zA-Z0-9._-]/', '', $file);
    if (empty($file)) {
        http_response_code(404);
        echo 'File tidak valid';
        exit;
    }
    
    $filePath = __DIR__ . '/../uploads/' . $folder . '/' . $file;
    
    if (!file_exists($filePath)) {
        http_response_code(404);
        echo 'File tidak ditemukan';
        exit;
    }
    
    if (!is_readable($filePath)) {
        http_response_code(403);
        echo 'File tidak dapat diakses';
        exit;
    }
    
    $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
    $mimeTypes = [
        'jpg' => 'image/jpeg',
        'jpeg' => 'image/jpeg',
        'png' => 'image/png',
        'gif' => 'image/gif',
        'webp' => 'image/webp',
        'svg' => 'image/svg+xml',
        'bmp' => 'image/bmp',
        'ico' => 'image/x-icon',
    ];
    
    $contentType = $mimeTypes[$extension] ?? 'application/octet-stream';
    
    header('Content-Type: ' . $contentType);
    header('Content-Length: ' . filesize($filePath));
    header('Cache-Control: public, max-age=2592000');
    header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2592000) . ' GMT');
    
    readfile($filePath);
    exit;
}
?>