<?php
/**
 * AdminController - Mengelola semua fungsi untuk Admin
 * VERSI TERBARU - TANPA SHARED_TRIP_PARTICIPANTS
 * DITAMBAHKAN: Fitur Kelola Claim Pengembalian Dana
 * DIPERBAIKI: Proses Claim menggunakan status yang benar
 */
class AdminController {
    private $pdo;
    
    public function __construct($pdo) {
        $this->pdo = $pdo;
        if(!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
            header("Location: ?page=login");
            exit;
        }
    }
    
    /**
     * Helper: Ambil jumlah notifikasi belum dibaca
     */
    private function getUnreadCount($user_id) {
        try {
            $stmt = $this->pdo->prepare("SELECT COUNT(*) as total FROM notifications WHERE user_id = ? AND is_read = 0");
            $stmt->execute([$user_id]);
            return $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
        } catch (Exception $e) {
            return 0;
        }
    }
    
    /**
     * Helper: Kirim notifikasi WhatsApp
     */
    private function sendWhatsAppNotification($nomor, $template, $data = []) {
        $fonnte_file = __DIR__ . '/../config/fonnte.php';
        if (!file_exists($fonnte_file)) {
            error_log("❌ File fonnte.php tidak ditemukan");
            return false;
        }
        
        require_once $fonnte_file;
        
        if (!function_exists('sendWhatsApp')) {
            error_log("❌ Fungsi sendWhatsApp tidak ditemukan");
            return false;
        }
        
        $templates = [
            'request_hapus_disetujui_supir' => "
🗑️ *REQUEST HAPUS KAPAL DISETUJUI* 🗑️

Halo {nama_pemilik},
Request hapus kapal '{nama_kapal}' telah DISETUJUI oleh admin.

📌 Alasan: {alasan}

Kapal Anda sekarang telah dihapus dari sistem.
",
            'request_hapus_ditolak_supir' => "
❌ *REQUEST HAPUS KAPAL DITOLAK* ❌

Halo {nama_pemilik},
Request hapus kapal '{nama_kapal}' telah DITOLAK oleh admin.

📌 Alasan: {alasan}

Silakan hubungi admin untuk informasi lebih lanjut.
",
            'kapal_baru_admin' => "
⛵ *KAPAL BARU MENDAFTAR* ⛵

Pemilik: {nama_pemilik}
Kapal: {nama_kapal}
Jenis: {jenis}
Kapasitas: {kapasitas} orang
Pelabuhan: {pelabuhan}

🔗 Segera verifikasi kapal ini:
{link_verifikasi}
",
        ];
        
        $pesan = $templates[$template] ?? '';
        if (empty($pesan)) {
            error_log("❌ Template notifikasi tidak ditemukan: " . $template);
            return false;
        }
        
        foreach ($data as $key => $value) {
            $pesan = str_replace('{' . $key . '}', $value, $pesan);
        }
        
        return sendWhatsApp($nomor, $pesan);
    }
    
    /**
     * Dashboard Admin
     */
    public function dashboard() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCount($user_id);
        
        $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM kapal");
        $totalKapal = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM pesanan");
        $totalPesanan = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM users");
        $totalUsers = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        $stmt = $this->pdo->query("SELECT SUM(total_harga) as total FROM pesanan WHERE status_pesanan IN ('confirmed','completed')");
        $totalPendapatan = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
        
        $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM pesanan WHERE status_pesanan = 'pending'");
        $pendingCount = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM pesanan WHERE status_pesanan = 'completed'");
        $completedCount = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM users WHERE is_active = 1");
        $activeUsers = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        // Jumlah request hapus yang menunggu
        $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM kapal WHERE hapus_request = 'menunggu'");
        $pendingHapusCount = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
        
        require_once __DIR__ . '/../views/admin/dashboard.php';
    }
    
    /**
     * Kelola Kapal - Menampilkan semua kapal untuk admin
     */
    public function kelolaKapal() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCount($user_id);
        
        $stmt = $this->pdo->query("
            SELECT k.*, u.nama as pemilik_nama, u.no_hp as pemilik_no_hp
            FROM kapal k 
            LEFT JOIN users u ON k.pemilik_id = u.id 
            ORDER BY FIELD(k.status_verifikasi, 'pending') DESC, k.created_at DESC
        ");
        $kapalList = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        require_once __DIR__ . '/../views/admin/kelola_kapal.php';
    }
    
    /**
     * Verifikasi Kapal - Menerima atau menolak kapal
     */
    public function verifikasiKapal() {
        if(!isset($_GET['id']) || !isset($_GET['act'])) {
            $_SESSION['flash_message'] = "Parameter tidak lengkap.";
            $_SESSION['flash_type'] = 'danger';
            header("Location: ?page=admin&action=kelolaKapal");
            exit;
        }
        
        $id = (int)$_GET['id'];
        $act = $_GET['act'];
        
        if(!in_array($act, ['verify', 'reject'])) {
            $_SESSION['flash_message'] = "Aksi tidak valid.";
            $_SESSION['flash_type'] = 'danger';
            header("Location: ?page=admin&action=kelolaKapal");
            exit;
        }
        
        $stmt = $this->pdo->prepare("
            SELECT k.*, u.id as pemilik_user_id, u.nama as pemilik_nama, u.no_hp as pemilik_no_hp
            FROM kapal k 
            JOIN users u ON k.pemilik_id = u.id 
            WHERE k.id = ?
        ");
        $stmt->execute([$id]);
        $kapal = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if(!$kapal) {
            $_SESSION['flash_message'] = "Kapal tidak ditemukan.";
            $_SESSION['flash_type'] = 'danger';
            header("Location: ?page=admin&action=kelolaKapal");
            exit;
        }
        
        if($kapal['status_verifikasi'] != 'pending') {
            $_SESSION['flash_message'] = "Kapal '{$kapal['nama_kapal']}' sudah diproses sebelumnya.";
            $_SESSION['flash_type'] = 'warning';
            header("Location: ?page=admin&action=kelolaKapal");
            exit;
        }
        
        if($act == 'verify') {
            $stmt = $this->pdo->prepare("
                UPDATE kapal 
                SET status_verifikasi = 'verified', 
                    verified_at = NOW() 
                WHERE id = ?
            ");
            $stmt->execute([$id]);
            
            $statusText = "diverifikasi";
            $title = "✅ Kapal Diverifikasi";
            $msg = "Kapal '{$kapal['nama_kapal']}' Anda telah diverifikasi oleh admin dan sekarang dapat disewa oleh wisatawan.";
            $notifType = 'success';
            
        } else {
            $alasan = isset($_POST['alasan']) ? trim($_POST['alasan']) : 'Tidak memenuhi syarat';
            if(empty($alasan)) $alasan = 'Tidak memenuhi syarat';
            
            $stmt = $this->pdo->prepare("
                UPDATE kapal 
                SET status_verifikasi = 'rejected', 
                    rejected_at = NOW(), 
                    alasan_penolakan = ? 
                WHERE id = ?
            ");
            $stmt->execute([$alasan, $id]);
            
            $statusText = "ditolak";
            $title = "❌ Kapal Ditolak";
            $msg = "Kapal '{$kapal['nama_kapal']}' Anda ditolak oleh admin. Alasan: $alasan.";
            $notifType = 'danger';
        }
        
        if(isset($kapal['pemilik_user_id'])) {
            $stmt = $this->pdo->prepare("
                INSERT INTO notifications (user_id, title, message, is_read, created_at) 
                VALUES (?, ?, ?, 0, NOW())
            ");
            $stmt->execute([$kapal['pemilik_user_id'], $title, $msg]);
        }
        
        $_SESSION['flash_message'] = "Kapal '{$kapal['nama_kapal']}' berhasil {$statusText}.";
        $_SESSION['flash_type'] = $notifType;
        
        header("Location: ?page=admin&action=kelolaKapal");
        exit;
    }
    
    /**
     * DAFTAR REQUEST HAPUS KAPAL
     */
    public function requestHapusKapal() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCount($user_id);
        
        // Ambil semua request yang menunggu
        $stmt = $this->pdo->prepare("
            SELECT k.*, u.nama as pemilik_nama, u.no_hp as pemilik_no_hp, u.email as pemilik_email
            FROM kapal k 
            JOIN users u ON k.pemilik_id = u.id 
            WHERE k.hapus_request = 'menunggu'
            ORDER BY k.hapus_request_at ASC
        ");
        $stmt->execute();
        $requests = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Ambil riwayat request yang sudah diproses
        $stmt = $this->pdo->prepare("
            SELECT k.*, u.nama as pemilik_nama
            FROM kapal k 
            JOIN users u ON k.pemilik_id = u.id 
            WHERE k.hapus_request IN ('disetujui', 'ditolak')
            ORDER BY k.hapus_request_at DESC
            LIMIT 20
        ");
        $stmt->execute();
        $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        require_once __DIR__ . '/../views/admin/request_hapus_kapal.php';
    }
    
    /**
     * PROSES REQUEST HAPUS KAPAL - TANPA SHARED_TRIP
     */
    public function prosesRequestHapus() {
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            header("Location: ?page=admin&action=requestHapusKapal");
            exit;
        }
        
        $id = (int) ($_POST['kapal_id'] ?? 0);
        $action = $_POST['action'] ?? '';
        $alasan = trim($_POST['alasan'] ?? '');
        $admin_id = $_SESSION['user_id'];
        
        if (empty($id) || empty($action)) {
            $_SESSION['flash_error'] = "Data tidak lengkap.";
            header("Location: ?page=admin&action=requestHapusKapal");
            exit;
        }
        
        if (!in_array($action, ['terima', 'tolak'])) {
            $_SESSION['flash_error'] = "Aksi tidak valid.";
            header("Location: ?page=admin&action=requestHapusKapal");
            exit;
        }
        
        // Ambil data kapal
        $stmt = $this->pdo->prepare("
            SELECT k.*, u.id as pemilik_user_id, u.nama as pemilik_nama, u.no_hp as pemilik_no_hp
            FROM kapal k 
            JOIN users u ON k.pemilik_id = u.id 
            WHERE k.id = ? AND k.hapus_request = 'menunggu'
        ");
        $stmt->execute([$id]);
        $kapal = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$kapal) {
            $_SESSION['flash_error'] = "Request tidak ditemukan atau sudah diproses.";
            header("Location: ?page=admin&action=requestHapusKapal");
            exit;
        }
        
        try {
            if ($action == 'terima') {
                // ============================================================
                // SETUJUI - HAPUS KAPAL PERMANEN
                // ============================================================
                $this->pdo->beginTransaction();
                
                // 1. Hapus kapal_rute
                $stmt = $this->pdo->prepare("DELETE FROM kapal_rute WHERE kapal_id = ?");
                $stmt->execute([$id]);
                
                // 2. Hapus schedules (jika ada)
                try {
                    $stmt = $this->pdo->prepare("DELETE FROM schedules WHERE kapal_id = ?");
                    $stmt->execute([$id]);
                } catch (Exception $e) {
                    // Tabel tidak ada, lanjutkan
                }
                
                // 3. Hapus rute_kapal
                $stmt = $this->pdo->prepare("DELETE FROM rute_kapal WHERE kapal_id = ?");
                $stmt->execute([$id]);
                
                // 4. Hapus claim_pengembalian (jika ada)
                try {
                    $stmt = $this->pdo->prepare("
                        DELETE cp FROM claim_pengembalian cp 
                        INNER JOIN pesanan p ON cp.pesanan_id = p.id 
                        WHERE p.kapal_id = ?
                    ");
                    $stmt->execute([$id]);
                } catch (Exception $e) {
                    // Tabel tidak ada, lanjutkan
                }
                
                // 5. Hapus pesanan
                $stmt = $this->pdo->prepare("DELETE FROM pesanan WHERE kapal_id = ?");
                $stmt->execute([$id]);
                
                // 6. HAPUS KAPAL - PERMANEN
                $stmt = $this->pdo->prepare("DELETE FROM kapal WHERE id = ?");
                $stmt->execute([$id]);
                
                $this->pdo->commit();
                
                $title = "🗑️ Kapal Dihapus Permanen";
                $msg = "Request hapus kapal '{$kapal['nama_kapal']}' telah DISETUJUI oleh admin. Kapal telah dihapus permanen dari sistem.";
                $notif_template = 'request_hapus_disetujui_supir';
                $wa_data = [
                    'nama_pemilik' => $kapal['pemilik_nama'],
                    'nama_kapal' => $kapal['nama_kapal'],
                    'alasan' => $alasan ?: 'Tidak ada alasan'
                ];
                
                $_SESSION['flash_success'] = "✅ Request hapus '{$kapal['nama_kapal']}' disetujui. Kapal berhasil dihapus permanen.";
                
            } elseif ($action == 'tolak') {
                // ============================================================
                // TOLAK - BATALKAN REQUEST
                // ============================================================
                if (empty($alasan)) {
                    $_SESSION['flash_error'] = "Alasan penolakan harus diisi.";
                    header("Location: ?page=admin&action=requestHapusKapal");
                    exit;
                }
                
                $stmt = $this->pdo->prepare("
                    UPDATE kapal 
                    SET hapus_request = 'ditolak',
                        alasan_hapus = ?,
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$alasan, $id]);
                
                $title = "❌ Request Hapus Kapal Ditolak";
                $msg = "Request hapus kapal '{$kapal['nama_kapal']}' telah DITOLAK oleh admin. Alasan: " . ($alasan ?: 'Tidak ada alasan');
                $notif_template = 'request_hapus_ditolak_supir';
                $wa_data = [
                    'nama_pemilik' => $kapal['pemilik_nama'],
                    'nama_kapal' => $kapal['nama_kapal'],
                    'alasan' => $alasan ?: 'Tidak ada alasan'
                ];
                
                $_SESSION['flash_success'] = "❌ Request hapus '{$kapal['nama_kapal']}' ditolak.";
            }
            
            // ============================================================
            // KIRIM NOTIFIKASI KE SUPIR
            // ============================================================
            // Notifikasi di aplikasi
            $stmt = $this->pdo->prepare("
                INSERT INTO notifications (user_id, title, message, is_read, created_at) 
                VALUES (?, ?, ?, 0, NOW())
            ");
            $stmt->execute([$kapal['pemilik_user_id'], $title, $msg]);
            
            // Notifikasi WhatsApp ke supir
            if (!empty($kapal['pemilik_no_hp'])) {
                $this->sendWhatsAppNotification($kapal['pemilik_no_hp'], $notif_template, $wa_data);
            }
            
        } catch (Exception $e) {
            if (isset($this->pdo) && $this->pdo->inTransaction()) {
                $this->pdo->rollBack();
            }
            error_log("Error prosesRequestHapus: " . $e->getMessage());
            $_SESSION['flash_error'] = "Gagal memproses: " . $e->getMessage();
        }
        
        header("Location: ?page=admin&action=requestHapusKapal");
        exit;
    }
    
    /**
     * Hapus Kapal - Admin langsung menghapus kapal (tanpa request)
     * 🔥 TANPA SHARED_TRIP_PARTICIPANTS
     */
    public function hapusKapal() {
        if(!isset($_GET['id'])) {
            $_SESSION['flash_message'] = "ID kapal tidak ditemukan.";
            $_SESSION['flash_type'] = 'danger';
            header("Location: ?page=admin&action=kelolaKapal");
            exit;
        }
        
        $id = (int)$_GET['id'];
        
        $stmt = $this->pdo->prepare("SELECT nama_kapal, pemilik_id FROM kapal WHERE id = ?");
        $stmt->execute([$id]);
        $kapal = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if(!$kapal) {
            $_SESSION['flash_message'] = "Kapal tidak ditemukan.";
            $_SESSION['flash_type'] = 'danger';
            header("Location: ?page=admin&action=kelolaKapal");
            exit;
        }
        
        try {
            $this->pdo->beginTransaction();
            
            // 1. Hapus kapal_rute
            $stmt = $this->pdo->prepare("DELETE FROM kapal_rute WHERE kapal_id = ?");
            $stmt->execute([$id]);
            
            // 2. Hapus schedules (jika ada)
            try {
                $stmt = $this->pdo->prepare("DELETE FROM schedules WHERE kapal_id = ?");
                $stmt->execute([$id]);
            } catch (Exception $e) {
                // Tabel tidak ada, lanjutkan
            }
            
            // 3. Hapus rute_kapal
            $stmt = $this->pdo->prepare("DELETE FROM rute_kapal WHERE kapal_id = ?");
            $stmt->execute([$id]);
            
            // 4. Hapus claim_pengembalian (jika ada)
            try {
                $stmt = $this->pdo->prepare("
                    DELETE cp FROM claim_pengembalian cp 
                    INNER JOIN pesanan p ON cp.pesanan_id = p.id 
                    WHERE p.kapal_id = ?
                ");
                $stmt->execute([$id]);
            } catch (Exception $e) {
                // Tabel tidak ada, lanjutkan
            }
            
            // 5. Hapus pesanan
            $stmt = $this->pdo->prepare("DELETE FROM pesanan WHERE kapal_id = ?");
            $stmt->execute([$id]);
            
            // 6. HAPUS KAPAL
            $stmt = $this->pdo->prepare("DELETE FROM kapal WHERE id = ?");
            $stmt->execute([$id]);
            
            // Notifikasi ke pemilik
            if(isset($kapal['pemilik_id'])) {
                $title = "🗑️ Kapal Dihapus";
                $msg = "Kapal '{$kapal['nama_kapal']}' telah dihapus oleh admin dari sistem.";
                $stmt = $this->pdo->prepare("
                    INSERT INTO notifications (user_id, title, message, is_read, created_at) 
                    VALUES (?, ?, ?, 0, NOW())
                ");
                $stmt->execute([$kapal['pemilik_id'], $title, $msg]);
            }
            
            $this->pdo->commit();
            
            $_SESSION['flash_message'] = "Kapal '{$kapal['nama_kapal']}' berhasil dihapus.";
            $_SESSION['flash_type'] = 'success';
            
        } catch (Exception $e) {
            if (isset($this->pdo) && $this->pdo->inTransaction()) {
                $this->pdo->rollBack();
            }
            $_SESSION['flash_message'] = "Gagal menghapus kapal: " . $e->getMessage();
            $_SESSION['flash_type'] = 'danger';
        }
        
        header("Location: ?page=admin&action=kelolaKapal");
        exit;
    }
    
    /**
     * ================================================================
     * 🔥 KELOLA PESANAN - DENGAN PARAMETER ID
     * ================================================================
     */
    public function kelolaPesanan() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCount($user_id);
        
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        
        if ($id > 0) {
            // ==============================================
            // TAMPILKAN DETAIL SATU PESANAN
            // ==============================================
            $stmt = $this->pdo->prepare("
                SELECT p.*, k.nama_kapal, k.pelabuhan_asal, k.pelabuhan_tujuan,
                       u.nama as wisatawan_nama, u.no_hp as wisatawan_hp, u.email as wisatawan_email,
                       u2.nama as pemilik_nama, u2.no_hp as pemilik_hp,
                       kr.asal as route_asal, kr.tujuan as route_tujuan, kr.harga_jual as route_harga
                FROM pesanan p 
                LEFT JOIN kapal k ON p.kapal_id = k.id 
                LEFT JOIN users u ON p.user_id = u.id 
                LEFT JOIN users u2 ON k.pemilik_id = u2.id
                LEFT JOIN kapal_rute kr ON p.route_id = kr.id
                WHERE p.id = ?
            ");
            $stmt->execute([$id]);
            $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$pesanan) {
                $_SESSION['flash_error'] = "Pesanan tidak ditemukan.";
                header("Location: ?page=admin&action=kelolaPesanan");
                exit;
            }
            
            require_once __DIR__ . '/../views/admin/detail_pesanan.php';
            
        } else {
            // ==============================================
            // TAMPILKAN SEMUA PESANAN (FILTER PENDING)
            // ==============================================
            $stmt = $this->pdo->prepare("
                SELECT 
                    p.*,
                    k.nama_kapal,
                    u.nama as wisatawan,
                    u.no_hp as wisatawan_hp,
                    u.email as wisatawan_email
                FROM pesanan p 
                LEFT JOIN kapal k ON p.kapal_id = k.id 
                LEFT JOIN users u ON p.user_id = u.id 
                WHERE p.status_pesanan = 'pending'
                ORDER BY p.created_at DESC
            ");
            $stmt->execute();
            $pesananList = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Hitung notifikasi untuk sidebar
            $notificationCounts = $this->getAdminNotificationCounts();
            
            require_once __DIR__ . '/../views/admin/kelola_pesanan.php';
        }
    }
    
    public function confirmPesanan() {
        // Hapus output buffer
        while (ob_get_level()) {
            ob_end_clean();
        }
        
        header('Content-Type: application/json');
        header('Cache-Control: no-cache, must-revalidate');
        
        // Cek login
        if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
            echo json_encode([
                'success' => false, 
                'message' => 'Unauthorized - Silakan login sebagai admin'
            ]);
            exit;
        }
        
        $id = isset($_POST['id']) ? (int)$_POST['id'] : (isset($_GET['id']) ? (int)$_GET['id'] : 0);
        
        if ($id <= 0) {
            echo json_encode([
                'success' => false, 
                'message' => 'ID pesanan tidak valid'
            ]);
            exit;
        }
        
        try {
            // Cek pesanan
            $stmt = $this->pdo->prepare("SELECT * FROM pesanan WHERE id = ?");
            $stmt->execute([$id]);
            $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$pesanan) {
                echo json_encode([
                    'success' => false, 
                    'message' => 'Pesanan tidak ditemukan'
                ]);
                exit;
            }
            
            // Cek status (status_pesanan: 'pending' atau 'tertunda')
            $status = $pesanan['status_pesanan'];
            if ($status !== 'pending' && $status !== 'tertunda') {
                echo json_encode([
                    'success' => false, 
                    'message' => 'Pesanan tidak dapat dikonfirmasi. Status saat ini: ' . $status
                ]);
                exit;
            }
            
            // Update status pesanan
            $stmt = $this->pdo->prepare("
                UPDATE pesanan 
                SET status_pesanan = 'confirmed',
                    tanggal_konfirmasi_pembayaran = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$id]);
            
            echo json_encode([
                'success' => true, 
                'message' => 'Pesanan berhasil dikonfirmasi'
            ]);
            
        } catch (Exception $e) {
            echo json_encode([
                'success' => false, 
                'message' => 'Error: ' . $e->getMessage()
            ]);
        }
        exit;
    }
    
    public function cancelPesanan() {
        // Hapus output buffer
        while (ob_get_level()) {
            ob_end_clean();
        }
        
        header('Content-Type: application/json');
        header('Cache-Control: no-cache, must-revalidate');
        
        // Cek login
        if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
            echo json_encode([
                'success' => false, 
                'message' => 'Unauthorized - Silakan login sebagai admin'
            ]);
            exit;
        }
        
        $id = isset($_POST['id']) ? (int)$_POST['id'] : (isset($_GET['id']) ? (int)$_GET['id'] : 0);
        $reason = isset($_POST['reason']) ? trim($_POST['reason']) : '';
        
        if ($id <= 0) {
            echo json_encode([
                'success' => false, 
                'message' => 'ID pesanan tidak valid'
            ]);
            exit;
        }
        
        try {
            // Cek pesanan
            $stmt = $this->pdo->prepare("SELECT * FROM pesanan WHERE id = ?");
            $stmt->execute([$id]);
            $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$pesanan) {
                echo json_encode([
                    'success' => false, 
                    'message' => 'Pesanan tidak ditemukan'
                ]);
                exit;
            }
            
            // Cek status (status_pesanan: 'pending' atau 'tertunda')
            $status = $pesanan['status_pesanan'];
            if ($status !== 'pending' && $status !== 'tertunda') {
                echo json_encode([
                    'success' => false, 
                    'message' => 'Pesanan tidak dapat dibatalkan. Status saat ini: ' . $status
                ]);
                exit;
            }
            
            // Update status pesanan
            $stmt = $this->pdo->prepare("
                UPDATE pesanan 
                SET status_pesanan = 'cancelled',
                    status_pembatalan = 'dibatalkan',
                    tanggal_pembatalan = NOW(),
                    alasan_penolakan = ? 
                WHERE id = ?
            ");
            $stmt->execute([$reason, $id]);
            
            echo json_encode([
                'success' => true, 
                'message' => 'Pesanan berhasil dibatalkan' . ($reason ? ' (Alasan: ' . $reason . ')' : '')
            ]);
            
        } catch (Exception $e) {
            echo json_encode([
                'success' => false, 
                'message' => 'Error: ' . $e->getMessage()
            ]);
        }
        exit;
    }
    
    /**
     * Get notification counts
     */
    private function getAdminNotificationCounts() {
        $counts = [
            'kapal_pending' => 0,
            'pesanan_pending' => 0,
            'request_hapus' => 0,
            'pembayaran_pending' => 0,
            'claim_pending' => 0,
            'pencairan_pending' => 0,
            'total' => 0
        ];
        
        try {
            // Pesanan pending
            $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM pesanan WHERE status_pesanan = 'pending'");
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            $counts['pesanan_pending'] = (int)($result['total'] ?? 0);
            
            // Kapal pending
            $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM kapal WHERE status_verifikasi = 'pending'");
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            $counts['kapal_pending'] = (int)($result['total'] ?? 0);
            
            // Pembayaran pending
            $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM pesanan WHERE status_pembayaran = 'menunggu_konfirmasi'");
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            $counts['pembayaran_pending'] = (int)($result['total'] ?? 0);
            
            // Claim pending
            try {
                $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM claim_pengembalian WHERE status_claim = 'pending'");
                $result = $stmt->fetch(PDO::FETCH_ASSOC);
                $counts['claim_pending'] = (int)($result['total'] ?? 0);
            } catch (Exception $e) {
                // Tabel mungkin belum ada
            }
            
            $counts['total'] = array_sum($counts);
            
        } catch (Exception $e) {
            // Silent fail
        }
        
        return $counts;
    }
    
    /**
     * Send notification to user (opsional)
     */
    private function sendNotification($user_id, $title, $message) {
        try {
            // Cek tabel notifications
            $stmt = $this->pdo->prepare("
                INSERT INTO notifications (user_id, title, message, is_read, created_at) 
                VALUES (?, ?, ?, 0, NOW())
            ");
            $stmt->execute([$user_id, $title, $message]);
        } catch (Exception $e) {
            error_log('Error sending notification: ' . $e->getMessage());
        }
    }
    
    /**
     * Kelola Supir (Pemilik Kapal)
     */
    public function kelolaSupir() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCount($user_id);
        
        $stmt = $this->pdo->query("
            SELECT * FROM users 
            WHERE role = 'pemilik_kapal' 
            ORDER BY created_at DESC
        ");
        $supir = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        require_once __DIR__ . '/../views/admin/kelola_supir.php';
    }
    
    /**
     * ================================================================
     * GET SUPIR DETAIL - UNTUK MODAL AJAX
     * ================================================================
     */
    public function getSupirDetail() {
        // Set header untuk JSON response
        header('Content-Type: application/json');
        
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        
        if (empty($id)) {
            echo json_encode([
                'success' => false,
                'message' => 'ID supir tidak valid'
            ]);
            exit;
        }
        
        try {
            $stmt = $this->pdo->prepare("
                SELECT 
                    id, 
                    nama, 
                    email, 
                    no_hp, 
                    is_active,
                    created_at,
                    (SELECT COUNT(*) FROM kapal WHERE pemilik_id = users.id) as total_kapal
                FROM users 
                WHERE id = ? AND role = 'pemilik_kapal'
            ");
            $stmt->execute([$id]);
            $data = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($data) {
                echo json_encode([
                    'success' => true,
                    'data' => $data
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Supir tidak ditemukan'
                ]);
            }
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => 'Terjadi kesalahan: ' . $e->getMessage()
            ]);
        }
        exit;
    }
    
    /**
     * ================================================================
     * TOGGLE STATUS SUPIR (AKTIFKAN / NONAKTIFKAN)
     * ================================================================
     */
    public function toggleSupirStatus() {
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        $action = isset($_GET['action']) ? $_GET['action'] : '';
        
        if (empty($id) || !in_array($action, ['aktifkanSupir', 'nonaktifkanSupir'])) {
            $_SESSION['flash_message'] = "Parameter tidak valid.";
            $_SESSION['flash_type'] = 'danger';
            header("Location: ?page=admin&action=kelolaSupir");
            exit;
        }
        
        // Ambil data supir
        $stmt = $this->pdo->prepare("
            SELECT id, nama, email, is_active FROM users 
            WHERE id = ? AND role = 'pemilik_kapal'
        ");
        $stmt->execute([$id]);
        $supir = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$supir) {
            $_SESSION['flash_message'] = "Supir tidak ditemukan.";
            $_SESSION['flash_type'] = 'danger';
            header("Location: ?page=admin&action=kelolaSupir");
            exit;
        }
        
        $newStatus = ($action == 'aktifkanSupir') ? 1 : 0;
        $statusText = ($newStatus == 1) ? 'diaktifkan' : 'dinonaktifkan';
        
        try {
            $stmt = $this->pdo->prepare("
                UPDATE users 
                SET is_active = ?, 
                    updated_at = NOW() 
                WHERE id = ?
            ");
            $stmt->execute([$newStatus, $id]);
            
            // Kirim notifikasi ke supir
            $title = ($newStatus == 1) ? "✅ Akun Diaktifkan" : "⛔ Akun Dinonaktifkan";
            $msg = ($newStatus == 1) 
                ? "Akun Anda telah diaktifkan kembali oleh admin. Anda dapat mengakses sistem kembali."
                : "Akun Anda telah dinonaktifkan oleh admin. Silakan hubungi admin untuk informasi lebih lanjut.";
            
            $stmt = $this->pdo->prepare("
                INSERT INTO notifications (user_id, title, message, is_read, created_at) 
                VALUES (?, ?, ?, 0, NOW())
            ");
            $stmt->execute([$id, $title, $msg]);
            
            $_SESSION['flash_message'] = "Supir '{$supir['nama']}' berhasil {$statusText}.";
            $_SESSION['flash_type'] = 'success';
            
        } catch (Exception $e) {
            $_SESSION['flash_message'] = "Gagal mengubah status: " . $e->getMessage();
            $_SESSION['flash_type'] = 'danger';
        }
        
        header("Location: ?page=admin&action=kelolaSupir");
        exit;
    }
    
    /**
     * Laporan Pendapatan
     */
    public function laporan() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCount($user_id);

        // 🔥 AMBIL FILTER TANGGAL (jika ada)
        $tanggal_awal = $_GET['tanggal_awal'] ?? '';
        $tanggal_akhir = $_GET['tanggal_akhir'] ?? '';
        
        // 🔥 Jika filter kosong, TIDAK PAKAI FILTER TANGGAL!
        $useDateFilter = !empty($tanggal_awal) && !empty($tanggal_akhir);
        
        if ($useDateFilter) {
            $dateCondition = "AND tanggal_konfirmasi_pembayaran BETWEEN ? AND ?";
            $dateParams = [$tanggal_awal . ' 00:00:00', $tanggal_akhir . ' 23:59:59'];
        } else {
            $dateCondition = "";
            $dateParams = [];
        }

        // ============================================
        // 1. TOTAL PESANAN & PENDAPATAN
        // ============================================
        $sql = "
            SELECT 
                COUNT(*) as total_pesanan,
                COALESCE(SUM(total_harga), 0) as total_pendapatan,
                COALESCE(SUM(komisi_admin), 0) as total_komisi,
                COALESCE(SUM(nominal_diterima_supir), 0) as total_diterima_supir
            FROM pesanan
            WHERE status_pesanan IN ('confirmed', 'completed')
            $dateCondition
        ";
        $stmt = $this->pdo->prepare($sql);
        if ($useDateFilter) {
            $stmt->execute($dateParams);
        } else {
            $stmt->execute();
        }
        $summary = $stmt->fetch(PDO::FETCH_ASSOC);

        // ============================================
        // 2. LAPORAN PER KAPAL
        // ============================================
        $sql = "
            SELECT 
                k.id as kapal_id,
                k.nama_kapal,
                COUNT(p.id) as total_pesanan,
                COALESCE(SUM(p.total_harga), 0) as total_pendapatan,
                COALESCE(SUM(p.komisi_admin), 0) as total_komisi,
                COALESCE(SUM(p.nominal_diterima_supir), 0) as total_diterima_supir
            FROM kapal k
            LEFT JOIN pesanan p ON k.id = p.kapal_id 
                AND p.status_pesanan IN ('confirmed', 'completed')
                $dateCondition
            WHERE k.status_verifikasi = 'verified'
            GROUP BY k.id, k.nama_kapal
            ORDER BY total_pendapatan DESC
        ";
        $stmt = $this->pdo->prepare($sql);
        if ($useDateFilter) {
            $stmt->execute($dateParams);
        } else {
            $stmt->execute();
        }
        $laporanKapal = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // ============================================
        // 3. DANA SUDAH DICAIRKAN KE SUPIR
        // ============================================
        $sql = "
            SELECT 
                u.id as supir_id,
                u.nama as supir_nama,
                u.no_hp as supir_hp,
                k.nama_kapal,
                COUNT(p.id) as total_pesanan,
                COALESCE(SUM(p.nominal_diterima_supir), 0) as total_dicairkan,
                MAX(p.tanggal_pencairan) as tanggal_pencairan_terakhir
            FROM users u
            JOIN kapal k ON u.id = k.pemilik_id
            JOIN pesanan p ON k.id = p.kapal_id
            WHERE p.status_pencairan = 'cair'
            $dateCondition
            GROUP BY u.id, u.nama, u.no_hp, k.nama_kapal
            ORDER BY total_dicairkan DESC
        ";
        $stmt = $this->pdo->prepare($sql);
        if ($useDateFilter) {
            $stmt->execute($dateParams);
        } else {
            $stmt->execute();
        }
        $laporanPencairan = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // ============================================
        // 4. DANA CLAIM WISATAWAN
        // ============================================
        $sql = "
            SELECT 
                u.id as wisatawan_id,
                u.nama as wisatawan_nama,
                u.no_hp as wisatawan_hp,
                p.kode_pesanan,
                p.nama_kapal,
                p.total_harga as jumlah_claim,
                c.status_claim,
                c.tanggal_claim,
                c.alasan_claim
            FROM claim_pengembalian c
            JOIN pesanan p ON c.pesanan_id = p.id
            JOIN users u ON c.wisatawan_id = u.id
            WHERE c.status_claim = 'diterima'
            $dateCondition
            ORDER BY c.tanggal_claim DESC
        ";
        $stmt = $this->pdo->prepare($sql);
        if ($useDateFilter) {
            $stmt->execute($dateParams);
        } else {
            $stmt->execute();
        }
        $laporanClaim = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // ============================================
        // 5. STATISTIK WISATAWAN
        // ============================================
        $sql = "
            SELECT 
                COUNT(DISTINCT user_id) as total_wisatawan,
                COUNT(*) as total_pesanan_wisatawan,
                COALESCE(SUM(total_harga), 0) as total_nilai_pesanan
            FROM pesanan
            WHERE status_pesanan IN ('confirmed', 'completed')
            $dateCondition
        ";
        $stmt = $this->pdo->prepare($sql);
        if ($useDateFilter) {
            $stmt->execute($dateParams);
        } else {
            $stmt->execute();
        }
        $statistikWisatawan = $stmt->fetch(PDO::FETCH_ASSOC);

        // ============================================
        // 6. TOTAL KAPAL YANG DIPESAN
        // ============================================
        $sql = "
            SELECT COUNT(DISTINCT kapal_id) as total_kapal_dipesan
            FROM pesanan
            WHERE status_pesanan IN ('confirmed', 'completed')
            $dateCondition
        ";
        $stmt = $this->pdo->prepare($sql);
        if ($useDateFilter) {
            $stmt->execute($dateParams);
        } else {
            $stmt->execute();
        }
        $totalKapalDipesan = $stmt->fetch(PDO::FETCH_ASSOC)['total_kapal_dipesan'] ?? 0;

        // ============================================
        // HITUNG TOTAL
        // ============================================
        $totalDicairkan = array_sum(array_column($laporanPencairan, 'total_dicairkan'));
        $totalClaim = array_sum(array_column($laporanClaim, 'jumlah_claim'));

        // ============================================
        // 🔥 KIRIM VARIABEL KE VIEW
        // ============================================
        $data = [
            'laporanKapal' => $laporanKapal,
            'laporanPencairan' => $laporanPencairan,
            'laporanClaim' => $laporanClaim,
            'summary' => $summary,
            'statistikWisatawan' => $statistikWisatawan,
            'totalKapalDipesan' => $totalKapalDipesan,
            'totalDicairkan' => $totalDicairkan,
            'totalClaim' => $totalClaim,
            'tanggal_awal' => $tanggal_awal ?: date('Y-m-01'),
            'tanggal_akhir' => $tanggal_akhir ?: date('Y-m-d'),
            'useDateFilter' => $useDateFilter,
        ];
        extract($data);
        require_once __DIR__ . '/../views/admin/laporan.php';
    }
    
    /**
     * KONFIRMASI PEMBAYARAN - Menampilkan daftar pembayaran
     */
    public function konfirmasiPembayaran() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCount($user_id);
        
        // Ambil semua pesanan yang menunggu konfirmasi pembayaran
        $stmt = $this->pdo->prepare("
            SELECT p.*, k.nama_kapal, k.pemilik_id, k.persen_komisi,
                   u.nama as wisatawan_nama, u.no_hp as wisatawan_hp,
                   u2.nama as pemilik_nama, u2.no_hp as pemilik_hp
            FROM pesanan p 
            JOIN kapal k ON p.kapal_id = k.id 
            JOIN users u ON p.user_id = u.id 
            JOIN users u2 ON k.pemilik_id = u2.id
            WHERE p.status_pembayaran = 'menunggu_konfirmasi'
              AND p.status_pesanan = 'confirmed'
            ORDER BY p.created_at DESC
        ");
        $stmt->execute();
        $pendingPayments = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Ambil riwayat konfirmasi
        $stmt = $this->pdo->prepare("
            SELECT p.*, k.nama_kapal, u.nama as wisatawan_nama,
                   u2.nama as pemilik_nama
            FROM pesanan p 
            JOIN kapal k ON p.kapal_id = k.id 
            JOIN users u ON p.user_id = u.id 
            JOIN users u2 ON k.pemilik_id = u2.id
            WHERE p.status_pembayaran_admin IN ('dikonfirmasi', 'ditolak')
            ORDER BY p.tanggal_konfirmasi_pembayaran DESC
            LIMIT 20
        ");
        $stmt->execute();
        $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        require_once __DIR__ . '/../views/admin/konfirmasi_pembayaran.php';
    }
    
    /**
     * PROSES KONFIRMASI PEMBAYARAN
     */
    public function prosesKonfirmasiPembayaran() {
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            header("Location: ?page=admin&action=konfirmasiPembayaran");
            exit;
        }
        
        $id = (int) ($_POST['pesanan_id'] ?? 0);
        $action = $_POST['action'] ?? '';
        $alasan = trim($_POST['alasan'] ?? '');
        $admin_id = $_SESSION['user_id'];
        
        if (empty($id) || empty($action)) {
            $_SESSION['flash_error'] = "Data tidak lengkap.";
            header("Location: ?page=admin&action=konfirmasiPembayaran");
            exit;
        }
        
        if (!in_array($action, ['terima', 'tolak'])) {
            $_SESSION['flash_error'] = "Aksi tidak valid.";
            header("Location: ?page=admin&action=konfirmasiPembayaran");
            exit;
        }
        
        // Ambil data pesanan
        $stmt = $this->pdo->prepare("
            SELECT p.*, k.nama_kapal, k.pemilik_id, k.persen_komisi,
                   u.nama as wisatawan_nama, u.no_hp as wisatawan_hp,
                   u2.nama as pemilik_nama, u2.no_hp as pemilik_hp
            FROM pesanan p 
            JOIN kapal k ON p.kapal_id = k.id 
            JOIN users u ON p.user_id = u.id 
            JOIN users u2 ON k.pemilik_id = u2.id
            WHERE p.id = ? AND p.status_pembayaran = 'menunggu_konfirmasi'
        ");
        $stmt->execute([$id]);
        $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$pesanan) {
            $_SESSION['flash_error'] = "Pesanan tidak ditemukan atau sudah diproses.";
            header("Location: ?page=admin&action=konfirmasiPembayaran");
            exit;
        }
        
        require_once __DIR__ . '/../config/fonnte.php';
        $base_url = "http://" . $_SERVER['HTTP_HOST'] . "/reservasi-kapal-wisata";
        
        try {
            if ($action == 'terima') {
                // ============================================================
                // TERIMA PEMBAYARAN
                // ============================================================
                $komisi = $pesanan['persen_komisi'] ?? 10;
                $total_harga = $pesanan['total_harga'];
                $nominal_komisi = ($komisi / 100) * $total_harga;
                $nominal_diterima_supir = $total_harga - $nominal_komisi;
                
                $this->pdo->beginTransaction();
                
                // Update status pembayaran
                $stmt = $this->pdo->prepare("
                    UPDATE pesanan 
                    SET status_pembayaran = 'lunas',
                        status_pembayaran_admin = 'dikonfirmasi',
                        komisi_admin = ?,
                        nominal_diterima_supir = ?,
                        tanggal_konfirmasi_pembayaran = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$nominal_komisi, $nominal_diterima_supir, $id]);
                
                $this->pdo->commit();
                
                // Notifikasi ke WISATAWAN
                if (!empty($pesanan['wisatawan_hp'])) {
                    $wa_msg = "
✅ *PEMBAYARAN DIKONFIRMASI* ✅

Halo *{$pesanan['wisatawan_nama']}*,

Pembayaran Anda untuk pesanan *{$pesanan['kode_pesanan']}* telah DIKONFIRMASI!

📅 Tanggal: " . date('d/m/Y', strtotime($pesanan['tanggal_berangkat'])) . "
⛵ Kapal: {$pesanan['nama_kapal']}
💰 Total: Rp " . number_format($total_harga, 0, ',', '.') . "

🎉 *PESANAN ANDA SIAP!*
Selamat menikmati perjalanan Anda. 🌊⛵

Terima kasih telah menggunakan layanan kami.
";
                    sendWhatsApp($pesanan['wisatawan_hp'], $wa_msg);
                }
                
                // Notifikasi ke SUPIR (uang sudah masuk sistem)
                if (!empty($pesanan['pemilik_hp'])) {
                    $wa_msg = "
💰 *PEMBAYARAN TELAH DIKONFIRMASI ADMIN* 💰

Halo *{$pesanan['pemilik_nama']}*,

Pembayaran untuk pesanan *{$pesanan['kode_pesanan']}* telah dikonfirmasi oleh admin.

📅 Tanggal: " . date('d/m/Y', strtotime($pesanan['tanggal_berangkat'])) . "
⛵ Kapal: {$pesanan['nama_kapal']}
👤 Wisatawan: {$pesanan['wisatawan_nama']}
💰 Total: Rp " . number_format($total_harga, 0, ',', '.') . "
💸 Komisi Admin ({$komisi}%): Rp " . number_format($nominal_komisi, 0, ',', '.') . "
📤 Diterima Supir: Rp " . number_format($nominal_diterima_supir, 0, ',', '.') . "

💳 *Dana akan dicairkan ke rekening Anda setelah perjalanan selesai.*
";
                    sendWhatsApp($pesanan['pemilik_hp'], $wa_msg);
                }
                
                $_SESSION['flash_success'] = "✅ Pembayaran berhasil dikonfirmasi!";
                
            } elseif ($action == 'tolak') {
                // ============================================================
                // TOLAK PEMBAYARAN
                // ============================================================
                if (empty($alasan)) {
                    $_SESSION['flash_error'] = "Alasan penolakan harus diisi.";
                    header("Location: ?page=admin&action=konfirmasiPembayaran");
                    exit;
                }
                
                $stmt = $this->pdo->prepare("
                    UPDATE pesanan 
                    SET status_pembayaran = 'gagal',
                        status_pembayaran_admin = 'ditolak',
                        alasan_penolakan_pembayaran = ?,
                        tanggal_konfirmasi_pembayaran = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$alasan, $id]);
                
                // Notifikasi ke WISATAWAN
                if (!empty($pesanan['wisatawan_hp'])) {
                    $wa_msg = "
❌ *PEMBAYARAN DITOLAK* ❌

Halo *{$pesanan['wisatawan_nama']}*,

Pembayaran Anda untuk pesanan *{$pesanan['kode_pesanan']}* telah DITOLAK oleh admin.

📌 Alasan: {$alasan}

Silakan upload ulang bukti pembayaran yang valid.

Terima kasih. 🌊
";
                    sendWhatsApp($pesanan['wisatawan_hp'], $wa_msg);
                }
                
                $_SESSION['flash_success'] = "❌ Pembayaran ditolak.";
            }
            
        } catch (Exception $e) {
            if (isset($this->pdo) && $this->pdo->inTransaction()) {
                $this->pdo->rollBack();
            }
            $_SESSION['flash_error'] = "Gagal memproses: " . $e->getMessage();
        }
        
        header("Location: ?page=admin&action=konfirmasiPembayaran");
        exit;
    }
    
    /**
     * PENCAIRAN DANA KE SUPIR
     */
    public function pencairanDana() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCount($user_id);
        
        // Cek apakah kolom tanggal_pencairan ada
        try {
            $stmt = $this->pdo->query("SHOW COLUMNS FROM pesanan LIKE 'tanggal_pencairan'");
            $hasColumn = $stmt->rowCount() > 0;
        } catch (Exception $e) {
            $hasColumn = false;
        }
        
        // ================================================================
        // AMBIL PESANAN YANG SUDAH LUNAS DAN BELUM DICAIRKAN
        // ================================================================
        $stmt = $this->pdo->prepare("
            SELECT 
                p.*, 
                k.nama_kapal, 
                k.persen_komisi,
                u.nama as pemilik_nama, 
                u.no_hp as pemilik_hp
            FROM pesanan p 
            JOIN kapal k ON p.kapal_id = k.id 
            JOIN users u ON k.pemilik_id = u.id
            WHERE p.status_pembayaran = 'lunas'
              AND p.status_pencairan = 'belum'
              AND p.status_pesanan IN ('confirmed', 'completed')
            ORDER BY p.tanggal_konfirmasi_pembayaran ASC
        ");
        $stmt->execute();
        $pendingCair = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // ================================================================
        // HITUNG ULANG NOMINAL UNTUK SETIAP PESANAN
        // ================================================================
        foreach ($pendingCair as &$p) {
            if (!isset($p['komisi_admin']) || $p['komisi_admin'] == 0) {
                $komisi = $p['persen_komisi'] ?? 10;
                $total_harga = $p['total_harga'];
                $p['komisi_admin'] = ($komisi / 100) * $total_harga;
                $p['nominal_diterima_supir'] = $total_harga - $p['komisi_admin'];
            }
            $p['durasi_hari'] = ceil($p['durasi_jam'] / 24);
        }
        
        // ================================================================
        // AMBIL RIWAYAT PENCAIRAN
        // ================================================================
        if ($hasColumn) {
            $orderBy = "p.tanggal_pencairan DESC";
        } else {
            $orderBy = "p.updated_at DESC";
        }
        
        $stmt = $this->pdo->prepare("
            SELECT p.*, k.nama_kapal, u.nama as pemilik_nama
            FROM pesanan p 
            JOIN kapal k ON p.kapal_id = k.id 
            JOIN users u ON k.pemilik_id = u.id
            WHERE p.status_pencairan = 'cair'
            ORDER BY {$orderBy}
            LIMIT 20
        ");
        $stmt->execute();
        $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // ================================================================
        // HITUNG TOTAL DANA
        // ================================================================
        $totalTertahan = array_sum(array_column($pendingCair, 'nominal_diterima_supir'));
        $totalDicairkan = array_sum(array_column($history, 'nominal_diterima_supir'));
        $totalKomisi = array_sum(array_column($pendingCair, 'komisi_admin'));
        
        require_once __DIR__ . '/../views/admin/pencairan_dana.php';
    }
    
    /**
     * PROSES PENCAIRAN DANA KE SUPIR
     */
    public function prosesPencairanDana() {
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            header("Location: ?page=admin&action=pencairanDana");
            exit;
        }
        
        $id = (int) ($_POST['pesanan_id'] ?? 0);
        $admin_id = $_SESSION['user_id'];
        
        if (empty($id)) {
            $_SESSION['flash_error'] = "Data tidak lengkap.";
            header("Location: ?page=admin&action=pencairanDana");
            exit;
        }
        
        $stmt = $this->pdo->prepare("
            SELECT p.*, k.nama_kapal, k.persen_komisi, u.nama as pemilik_nama, u.no_hp as pemilik_hp
            FROM pesanan p 
            JOIN kapal k ON p.kapal_id = k.id 
            JOIN users u ON k.pemilik_id = u.id
            WHERE p.id = ? AND p.status_pencairan = 'belum'
        ");
        $stmt->execute([$id]);
        $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$pesanan) {
            $_SESSION['flash_error'] = "Pesanan tidak ditemukan atau sudah dicairkan.";
            header("Location: ?page=admin&action=pencairanDana");
            exit;
        }
        
        try {
            $this->pdo->beginTransaction();
            
            $total_harga = $pesanan['total_harga'];
            $persen_komisi = $pesanan['persen_komisi'] ?? 10;
            $komisi_admin = round($total_harga * $persen_komisi / 100);
            $nominal_diterima_supir = $total_harga - $komisi_admin;
            
            $stmt = $this->pdo->prepare("
                UPDATE pesanan 
                SET 
                    status_pencairan = 'cair',
                    tanggal_pencairan = NOW(),
                    komisi_admin = ?,
                    nominal_diterima_supir = ?
                WHERE id = ?
            ");
            $stmt->execute([$komisi_admin, $nominal_diterima_supir, $id]);
            
            $this->pdo->commit();
            
            require_once __DIR__ . '/../config/fonnte.php';
            
            if (!empty($pesanan['pemilik_hp']) && function_exists('sendWhatsApp')) {
                $wa_msg = "
💰 *DANA TELAH DICAIRKAN* 💰

Halo *{$pesanan['pemilik_nama']}*,

Dana untuk pesanan *{$pesanan['kode_pesanan']}* telah dicairkan.

📅 Tanggal: " . date('d/m/Y', strtotime($pesanan['tanggal_berangkat'])) . "
⛵ Kapal: {$pesanan['nama_kapal']}
💰 Total: Rp " . number_format($total_harga, 0, ',', '.') . "
💸 Komisi: Rp " . number_format($komisi_admin, 0, ',', '.') . "
💳 Diterima: Rp " . number_format($nominal_diterima_supir, 0, ',', '.') . "

Terima kasih telah bekerja sama dengan kami. 🌊
";
                sendWhatsApp($pesanan['pemilik_hp'], $wa_msg);
            }
            
            $stmtNotif = $this->pdo->prepare("
                INSERT INTO notifications (user_id, title, message, booking_id, is_read) 
                VALUES (?, '💰 Dana Dicairkan ke Supir', 
                        CONCAT('Dana untuk pesanan ', ?, ' telah dicairkan ke supir sebesar Rp ', 
                               FORMAT(?, 0, 'id_ID'), '. Perjalanan selesai.'),
                        ?, 0)
            ");
            $stmtNotif->execute([
                $pesanan['user_id'],
                $pesanan['kode_pesanan'],
                $nominal_diterima_supir,
                $pesanan['id']
            ]);
            
            $_SESSION['flash_success'] = "✅ Dana berhasil dicairkan ke supir! (Rp " . number_format($nominal_diterima_supir, 0, ',', '.') . ")";
            
        } catch (Exception $e) {
            if ($this->pdo->inTransaction()) {
                $this->pdo->rollBack();
            }
            $_SESSION['flash_error'] = "Gagal memproses: " . $e->getMessage();
        }
        
        header("Location: ?page=admin&action=pencairanDana");
        exit;
    }
    
    // ================================================================
    // 🔥 FITUR KELOLA CLAIM PENGEMBALIAN DANA - DIPERBAIKI
    // ================================================================
    
    /**
     * CLAIM PENGEMBALIAN - Daftar semua claim
     * URL: ?page=admin&action=claimPengembalian
     */
   /**
 * CLAIM PENGEMBALIAN - Daftar semua claim
 * URL: ?page=admin&action=claimPengembalian
 */
/**
 * CLAIM PENGEMBALIAN - Daftar semua claim
 * URL: ?page=admin&action=claimPengembalian
 * DIPERBAIKI - Dengan error handling dan debug
 */
public function claimPengembalian() {
    $user_id = $_SESSION['user_id'];
    $unreadCount = $this->getUnreadCount($user_id);
    
    // ================================================================
    // 🔥 DEBUG - Cek apakah ada data di tabel
    // ================================================================
    try {
        $stmtCheck = $this->pdo->query("SELECT COUNT(*) as total FROM claim_pengembalian");
        $totalRows = $stmtCheck->fetch(PDO::FETCH_ASSOC);
        error_log("Total rows in claim_pengembalian: " . ($totalRows['total'] ?? 0));
    } catch (Exception $e) {
        error_log("Error checking claim_pengembalian: " . $e->getMessage());
    }
    
    // ================================================================
    // AMBIL SEMUA CLAIM DENGAN DETAIL
    // ================================================================
    try {
        $stmt = $this->pdo->prepare("
            SELECT 
                c.*,
                p.kode_pesanan,
                p.tanggal_berangkat,
                p.total_harga,
                p.status_pembayaran,
                p.nama_lengkap as wisatawan_nama,
                p.no_hp as wisatawan_hp,
                p.email as wisatawan_email,
                k.nama_kapal,
                u.nama as pemilik_kapal,
                u.no_hp as pemilik_hp
            FROM claim_pengembalian c
            LEFT JOIN pesanan p ON c.pesanan_id = p.id
            LEFT JOIN kapal k ON p.kapal_id = k.id
            LEFT JOIN users u ON k.pemilik_id = u.id
            ORDER BY 
                CASE 
                    WHEN c.status_claim = 'pending' THEN 1
                    WHEN c.status_claim = 'diterima' THEN 2
                    WHEN c.status_claim = 'ditolak' THEN 3
                    ELSE 4
                END,
                c.tanggal_claim DESC
        ");
        $stmt->execute();
        $claims = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        error_log("Total claims found: " . count($claims));
        
    } catch (Exception $e) {
        error_log("Error get claims: " . $e->getMessage());
        $claims = [];
        $_SESSION['flash_error'] = "Error mengambil data: " . $e->getMessage();
    }
    
    // ================================================================
    // HITUNG STATISTIK
    // ================================================================
    $totalClaim = count($claims);
    $pendingClaim = 0;
    $diterimaClaim = 0;
    $ditolakClaim = 0;
    $totalRefund = 0;
    
    foreach ($claims as $c) {
        $status = $c['status_claim'] ?? '';
        
        if ($status == 'pending') {
            $pendingClaim++;
        } elseif ($status == 'diterima') {
            $diterimaClaim++;
            $totalRefund += (int) ($c['total_harga'] ?? 0);
        } elseif ($status == 'ditolak') {
            $ditolakClaim++;
        }
    }
    
    error_log("Stats - Total: $totalClaim, Pending: $pendingClaim, Diterima: $diterimaClaim, Ditolak: $ditolakClaim");
    
    // ================================================================
    // 🔥 KIRIM KE VIEW
    // ================================================================
    require_once __DIR__ . '/../views/admin/claim_pengembalian.php';
}

/**
 * DETAIL CLAIM - Lihat detail claim
 * URL: ?page=admin&action=detailClaim&id=XXX
 */
public function detailClaim() {
    $claim_id = (int) ($_GET['id'] ?? 0);
    $user_id = $_SESSION['user_id'];
    $unreadCount = $this->getUnreadCount($user_id);
    
    if ($claim_id <= 0) {
        $_SESSION['flash_error'] = "ID claim tidak valid.";
        header("Location: ?page=admin&action=claimPengembalian");
        exit;
    }
    
    try {
        $stmt = $this->pdo->prepare("
            SELECT 
                c.*,
                p.kode_pesanan,
                p.tanggal_berangkat,
                p.tanggal_pesan,
                p.total_harga,
                p.status_pembayaran,
                p.nama_lengkap as wisatawan_nama,
                p.no_hp as wisatawan_hp,
                p.email as wisatawan_email,
                p.nik_ktp as wisatawan_nik,
                p.catatan as pesanan_catatan,
                p.status_pembatalan,
                p.alasan_penolakan,
                p.status_pesanan as pesanan_status,
                k.nama_kapal,
                k.pelabuhan_asal,
                k.pelabuhan_tujuan,
                u.nama as pemilik_kapal,
                u.no_hp as pemilik_hp,
                u.email as pemilik_email,
                -- 🔥 Ambil data supir (pemilik kapal)
                u.id as supir_id,
                u.nama as supir_nama
            FROM claim_pengembalian c
            JOIN pesanan p ON c.pesanan_id = p.id
            JOIN kapal k ON p.kapal_id = k.id
            JOIN users u ON k.pemilik_id = u.id
            WHERE c.id = ?
        ");
        $stmt->execute([$claim_id]);
        $claim = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$claim) {
            $_SESSION['flash_error'] = "Claim tidak ditemukan.";
            header("Location: ?page=admin&action=claimPengembalian");
            exit;
        }
        
        // ==============================================
        // 🔥 TENTUKAN ALASAN PENGAJUAN CLAIM - DIPERBAIKI
        // ==============================================
        $claimReason = '';
        $claimReasonBadge = '';
        $claimReasonIcon = '';
        $claimReasonDetail = '';
        
        // Cek status pembatalan pesanan
        $statusPembatalan = $claim['status_pembatalan'] ?? '';
        $alasanPenolakan = $claim['alasan_penolakan'] ?? '';
        $pesananStatus = $claim['pesanan_status'] ?? '';
        $alasanClaim = $claim['alasan_claim'] ?? '';
        $supirNama = $claim['supir_nama'] ?? 'Supir';
        $wisatawanNama = $claim['wisatawan_nama'] ?? 'Wisatawan';
        
        // ==============================================
        // 🔥 LOGIKA DETEKSI YANG LEBIH AKURAT
        // ==============================================
        
        // 1. CEK: Dibatalkan oleh SUPIR (status_pembatalan = 'dibatalkan_supir')
        if ($statusPembatalan == 'dibatalkan_supir') {
            $claimReason = 'Pesanan dibatalkan oleh SUPIR KAPAL';
            $claimReasonBadge = 'badge-danger';
            $claimReasonIcon = 'fa-user-times';
            $claimReasonDetail = "Supir kapal ({$supirNama}) membatalkan pesanan ini. " . (!empty($alasanPenolakan) ? "Alasan: {$alasanPenolakan}" : 'Tidak ada alasan.');
        }
        // 2. CEK: Dibatalkan oleh SUPIR (dari alasan penolakan)
        elseif (stripos($alasanPenolakan, 'supir') !== false || stripos($alasanPenolakan, 'pemilik kapal') !== false) {
            $claimReason = 'Pesanan dibatalkan oleh SUPIR KAPAL';
            $claimReasonBadge = 'badge-danger';
            $claimReasonIcon = 'fa-user-times';
            $claimReasonDetail = "Supir kapal ({$supirNama}) membatalkan pesanan ini. Alasan: {$alasanPenolakan}";
        }
        // 3. CEK: Dibatalkan oleh WISATAWAN (status_pembatalan = 'dibatalkan_otomatis' karena telat)
        elseif ($statusPembatalan == 'dibatalkan_otomatis') {
            $claimReason = 'Pesanan dibatalkan oleh WISATAWAN (Supir Telat > 2 Jam)';
            $claimReasonBadge = 'badge-warning';
            $claimReasonIcon = 'fa-user-clock';
            $claimReasonDetail = "Wisatawan ({$wisatawanNama}) membatalkan pesanan secara otomatis karena supir tidak menjemput sesuai jadwal (terlambat > 2 jam). " . (!empty($alasanPenolakan) ? "Alasan: {$alasanPenolakan}" : '');
        }
        // 4. CEK: Dibatalkan oleh WISATAWAN (manual)
        elseif ($statusPembatalan == 'dibatalkan' || $statusPembatalan == 'dibatalkan_wisatawan') {
            $claimReason = 'Pesanan dibatalkan oleh WISATAWAN (Manual)';
            $claimReasonBadge = 'badge-warning';
            $claimReasonIcon = 'fa-user';
            $claimReasonDetail = "Wisatawan ({$wisatawanNama}) membatalkan pesanan secara manual. " . (!empty($alasanPenolakan) ? "Alasan: {$alasanPenolakan}" : 'Tidak ada alasan.');
        }
        // 5. CEK: Dari alasan claim (jika mengandung kata "supir" atau "telat")
        elseif (stripos($alasanClaim, 'supir') !== false || stripos($alasanClaim, 'telat') !== false || stripos($alasanClaim, 'terlambat') !== false) {
            $claimReason = 'Claim diajukan oleh WISATAWAN (Supir Telat / Tidak Datang)';
            $claimReasonBadge = 'badge-info';
            $claimReasonIcon = 'fa-hand-holding-usd';
            $claimReasonDetail = "Wisatawan ({$wisatawanNama}) mengajukan claim karena supir tidak menjemput atau terlambat. Alasan: {$alasanClaim}";
        }
        // 6. DEFAULT: Claim langsung dari wisatawan
        else {
            $claimReason = 'Claim diajukan oleh WISATAWAN';
            $claimReasonBadge = 'badge-info';
            $claimReasonIcon = 'fa-hand-holding-usd';
            $claimReasonDetail = "Wisatawan ({$wisatawanNama}) mengajukan claim pengembalian dana. " . (!empty($alasanClaim) ? "Alasan: {$alasanClaim}" : '');
        }
        
        // ==============================================
        // 🔥 TAMBAHKAN INFORMASI SUPIR DI DETAIL
        // ==============================================
        if (!empty($claim['supir_nama'])) {
            // Sudah ada di claimReasonDetail
        }
        
    } catch (Exception $e) {
        $_SESSION['flash_error'] = "Error: " . $e->getMessage();
        header("Location: ?page=admin&action=claimPengembalian");
        exit;
    }
    
    require_once __DIR__ . '/../views/admin/detail_claim.php';
}
/**
 * PROSES CLAIM - Admin menerima atau menolak claim
 * URL: ?page=admin&action=prosesClaim
 * Method: POST
 */
public function prosesClaim() {
    // Cek login admin
    if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
        header("Location: ?page=login");
        exit;
    }
    
    if ($_SERVER['REQUEST_METHOD'] != 'POST') {
        header("Location: ?page=admin&action=claimPengembalian");
        exit;
    }
    
    // AMBIL DATA
    $claim_id = (int) ($_POST['claim_id'] ?? 0);
    $keputusan = $_POST['keputusan'] ?? '';
    $alasan_admin = trim($_POST['alasan_admin'] ?? '');
    
    // VALIDASI
    if ($claim_id <= 0) {
        $_SESSION['flash_error'] = "ID claim tidak valid.";
        header("Location: ?page=admin&action=claimPengembalian");
        exit;
    }
    
    if (empty($keputusan)) {
        $_SESSION['flash_error'] = "Silakan pilih keputusan (Terima/Tolak).";
        header("Location: ?page=admin&action=detailClaim&id=" . $claim_id);
        exit;
    }
    
    if (!in_array($keputusan, ['diterima', 'ditolak'])) {
        $_SESSION['flash_error'] = "Keputusan tidak valid.";
        header("Location: ?page=admin&action=detailClaim&id=" . $claim_id);
        exit;
    }
    
    if (empty($alasan_admin) || strlen($alasan_admin) < 5) {
        $_SESSION['flash_error'] = "Alasan/admin note minimal 5 karakter.";
        header("Location: ?page=admin&action=detailClaim&id=" . $claim_id);
        exit;
    }
    
    try {
        $this->pdo->beginTransaction();
        
        // AMBIL DATA CLAIM
        $stmt = $this->pdo->prepare("
            SELECT c.*, p.kode_pesanan, p.total_harga, p.user_id as wisatawan_id,
                   u.nama as wisatawan_nama, u.no_hp as wisatawan_hp,
                   k.pemilik_id as supir_id, u2.nama as supir_nama, u2.no_hp as supir_hp
            FROM claim_pengembalian c
            LEFT JOIN pesanan p ON c.pesanan_id = p.id
            LEFT JOIN users u ON c.wisatawan_id = u.id
            LEFT JOIN kapal k ON p.kapal_id = k.id
            LEFT JOIN users u2 ON k.pemilik_id = u2.id
            WHERE c.id = ?
        ");
        $stmt->execute([$claim_id]);
        $claim = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$claim) {
            throw new Exception('Claim tidak ditemukan.');
        }
        
        if ($claim['status_claim'] != 'pending') {
            throw new Exception('Claim sudah diproses sebelumnya.');
        }
        
        // ================================================================
        // 🔥 UPDATE CLAIM - HANYA FIELD YANG ADA DI TABEL
        // ================================================================
        $stmt = $this->pdo->prepare("
            UPDATE claim_pengembalian 
            SET status_claim = ?,
                alasan_admin = ?
            WHERE id = ?
        ");
        $stmt->execute([$keputusan, $alasan_admin, $claim_id]);
        
        // UPDATE STATUS PESANAN
        if ($keputusan == 'diterima') {
            $stmt = $this->pdo->prepare("
                UPDATE pesanan 
                SET status_claim = 'diterima',
                    status_pencairan = 'proses'
                WHERE id = ?
            ");
            $stmt->execute([$claim['pesanan_id']]);
            
            // TAMBAHKAN SALDO KE WISATAWAN
            $jumlah_refund = (int) $claim['total_harga'];
            $wisatawan_id = (int) $claim['wisatawan_id'];
            $keterangan = "Refund claim pesanan {$claim['kode_pesanan']}";
            
            // Cek saldo existing
            $stmt = $this->pdo->prepare("SELECT saldo FROM saldo_wisatawan WHERE user_id = ?");
            $stmt->execute([$wisatawan_id]);
            $saldoExist = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($saldoExist) {
                $saldoBaru = $saldoExist['saldo'] + $jumlah_refund;
                $stmt = $this->pdo->prepare("UPDATE saldo_wisatawan SET saldo = ? WHERE user_id = ?");
                $stmt->execute([$saldoBaru, $wisatawan_id]);
            } else {
                $saldoBaru = $jumlah_refund;
                $stmt = $this->pdo->prepare("INSERT INTO saldo_wisatawan (user_id, saldo) VALUES (?, ?)");
                $stmt->execute([$wisatawan_id, $saldoBaru]);
            }
            
            // Simpan riwayat saldo
            try {
                $stmt = $this->pdo->prepare("
                    INSERT INTO riwayat_saldo (user_id, jenis, jumlah, saldo_sebelum, saldo_sesudah, keterangan, referensi_id) 
                    VALUES (?, 'masuk', ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $wisatawan_id,
                    $jumlah_refund,
                    $saldoExist ? $saldoExist['saldo'] : 0,
                    $saldoBaru,
                    $keterangan,
                    $claim_id
                ]);
            } catch (Exception $e) {
                error_log("Error saving saldo history: " . $e->getMessage());
            }
            
            $_SESSION['flash_success'] = "✅ Claim diterima dan saldo wisatawan bertambah Rp " . number_format($jumlah_refund, 0, ',', '.');
            
        } else {
            // Claim ditolak
            $stmt = $this->pdo->prepare("
                UPDATE pesanan 
                SET status_claim = 'ditolak'
                WHERE id = ?
            ");
            $stmt->execute([$claim['pesanan_id']]);
            
            $_SESSION['flash_success'] = "❌ Claim ditolak.";
        }
        
        $this->pdo->commit();
        
    } catch (Exception $e) {
        $this->pdo->rollBack();
        error_log("ERROR prosesClaim: " . $e->getMessage());
        $_SESSION['flash_error'] = "❌ Gagal memproses claim: " . $e->getMessage();
    }
    
    header("Location: ?page=admin&action=claimPengembalian");
    exit;
}
    
    /**
     * ================================================================
     * GET ADMIN NOTIFICATIONS - UNTUK AJAX REAL-TIME BADGE
     * ================================================================
     */
    public function getAdminNotifications() {
        header('Content-Type: application/json');
        header('Cache-Control: no-cache, must-revalidate');
        
        $response = [
            'kapal_pending' => 0,
            'pesanan_pending' => 0,
            'request_hapus' => 0,
            'pembayaran_pending' => 0,
            'pencairan_pending' => 0,
            'claim_pending' => 0,
        ];
        
        try {
            // 1. Kapal menunggu verifikasi
            $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM kapal WHERE status_verifikasi = 'pending'");
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            $response['kapal_pending'] = (int)($result['total'] ?? 0);
            
            // 2. Pesanan pending
            $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM pesanan WHERE status_pesanan = 'pending'");
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            $response['pesanan_pending'] = (int)($result['total'] ?? 0);
            
            // 3. Request hapus pending
            $checkTable = $this->pdo->query("SHOW TABLES LIKE 'request_hapus_kapal'");
            if ($checkTable && $checkTable->rowCount() > 0) {
                $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM request_hapus_kapal WHERE hapus_request = 'pending'");
                $result = $stmt->fetch(PDO::FETCH_ASSOC);
                $response['request_hapus'] = (int)($result['total'] ?? 0);
            }
            
            // 4. Pembayaran menunggu konfirmasi
            $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM pesanan WHERE status_pembayaran = 'menunggu_konfirmasi'");
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            $response['pembayaran_pending'] = (int)($result['total'] ?? 0);
            
            // 5. Pencairan dana tertahan
            $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM pesanan WHERE status_pencairan = 'belum' AND status_pembayaran = 'lunas'");
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            $response['pencairan_pending'] = (int)($result['total'] ?? 0);
            
            // 6. Claim pending
            $checkClaim = $this->pdo->query("SHOW TABLES LIKE 'claim_pengembalian'");
            if ($checkClaim && $checkClaim->rowCount() > 0) {
                $stmt = $this->pdo->query("SELECT COUNT(*) as total FROM claim_pengembalian WHERE status_claim = 'pending'");
                $result = $stmt->fetch(PDO::FETCH_ASSOC);
                $response['claim_pending'] = (int)($result['total'] ?? 0);
            }
            
        } catch (Exception $e) {
            error_log("Error getAdminNotifications: " . $e->getMessage());
        }
        
        echo json_encode($response);
        exit;
    }
}
?>