<?php
/**
 * SupirController - Mengelola semua fungsi untuk Supir (Pemilik Kapal)
 * VERSI LENGKAP - Dengan fitur CRUD Rute, Notifikasi Real-time, Reschedule, dan Detail Pesanan
 * DIPERBAIKI - Menambahkan method detailPesanan() dan Notifikasi lengkap
 * DIPERBAIKI - Query detailPesanan mengambil semua data termasuk waktu dan jenis pembayaran
 */
class SupirController {
    private $pdo;
    
    public function __construct($pdo) {
        $this->pdo = $pdo;
        if(!isset($_SESSION['user_id']) || $_SESSION['role'] != 'pemilik_kapal') {
            header("Location: ?page=login");
            exit;
        }
    }

    /**
     * Helper: Ambil jumlah notifikasi belum dibaca
     */
    private function getUnreadCountPrivate($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, $pesan) {
        $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;
        }
        
        return sendWhatsApp($nomor, $pesan);
    }
    
    /**
     * Helper: Get column names from a table
     */
    private function getTableColumns($table) {
        try {
            $stmt = $this->pdo->query("SHOW COLUMNS FROM $table");
            return $stmt->fetchAll(PDO::FETCH_COLUMN);
        } catch (Exception $e) {
            error_log("Error getTableColumns: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Helper: Cek apakah tabel ada
     */
    private function tableExists($tableName) {
        try {
            $stmt = $this->pdo->query("SHOW TABLES LIKE '$tableName'");
            return $stmt->rowCount() > 0;
        } catch (Exception $e) {
            return false;
        }
    }
   /**
 * BATALKAN PESANAN OLEH SUPIR - Dengan refund otomatis
 * URL: ?page=supir&action=batalPesanan&id=XXX
 * Method: POST
 */
public function batalPesanan() {
    // Cek login supir
    if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'pemilik_kapal') {
        $_SESSION['flash_error'] = 'Anda harus login sebagai supir.';
        header("Location: ?page=login");
        exit;
    }
    
    if ($_SERVER['REQUEST_METHOD'] != 'POST') {
        header("Location: ?page=supir&action=kelolaPesanan");
        exit;
    }
    
    $pesanan_id = (int) ($_POST['pesanan_id'] ?? 0);
    $supir_id = $_SESSION['user_id'];
    $alasan = trim($_POST['alasan'] ?? '');
    
    if ($pesanan_id <= 0) {
        $_SESSION['flash_error'] = "ID pesanan tidak valid.";
        header("Location: ?page=supir&action=kelolaPesanan");
        exit;
    }
    
    if (empty($alasan) || strlen($alasan) < 5) {
        $_SESSION['flash_error'] = "Alasan pembatalan minimal 5 karakter.";
        header("Location: ?page=supir&action=detailPesanan&id=" . $pesanan_id);
        exit;
    }
    
    try {
        // CEK PESANAN
        $stmt = $this->pdo->prepare("
            SELECT p.*, k.pemilik_id, k.nama_kapal, 
                   u.nama as wisatawan_nama, u.no_hp as wisatawan_hp, u.email as wisatawan_email
            FROM pesanan p
            JOIN kapal k ON p.kapal_id = k.id
            JOIN users u ON p.user_id = u.id
            WHERE p.id = ? AND k.pemilik_id = ?
        ");
        $stmt->execute([$pesanan_id, $supir_id]);
        $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$pesanan) {
            throw new Exception('Pesanan tidak ditemukan atau bukan milik Anda.');
        }
        
        // CEK STATUS
        if ($pesanan['status_pesanan'] == 'completed' || $pesanan['status_pesanan'] == 'selesai') {
            throw new Exception('Pesanan sudah selesai. Tidak dapat dibatalkan.');
        }
        
        if ($pesanan['status_pesanan'] == 'cancelled' || $pesanan['status_pesanan'] == 'dibatalkan') {
            throw new Exception('Pesanan sudah dibatalkan sebelumnya.');
        }
        
        // ================================================================
        // 🔥 BATALKAN PESANAN
        // ================================================================
        $this->pdo->beginTransaction();
        
        // 🔥 CEK KOLOM status_pembatalan - PAKAI NILAI YANG SESUAI
        // Cek dulu struktur kolom
        $stmtCheck = $this->pdo->query("SHOW COLUMNS FROM pesanan LIKE 'status_pembatalan'");
        $columnInfo = $stmtCheck->fetch(PDO::FETCH_ASSOC);
        
        // Jika kolom ada, gunakan nilai yang sesuai dengan ENUM
        if ($columnInfo) {
            // Ambil nilai ENUM yang tersedia
            $enumValues = [];
            if (preg_match("/^enum\((.*)\)$/", $columnInfo['Type'], $matches)) {
                $enumValues = str_getcsv($matches[1], ',', "'");
                $enumValues = array_map(function($v) { return trim($v, "'"); }, $enumValues);
            }
            
            // Pilih nilai yang sesuai
            $statusPembatalan = 'dibatalkan'; // default
            
            // Coba cari nilai yang cocok di ENUM
            $possibleValues = ['dibatalkan', 'dibatalkan_supir', 'cancelled', 'batal'];
            foreach ($possibleValues as $val) {
                if (in_array($val, $enumValues)) {
                    $statusPembatalan = $val;
                    break;
                }
            }
            
            // 1. Update status pesanan
            $stmt = $this->pdo->prepare("
                UPDATE pesanan 
                SET status_pesanan = 'cancelled',
                    status_pembatalan = ?,
                    tanggal_pembatalan = NOW(),
                    alasan_penolakan = ?
                WHERE id = ?
            ");
            $stmt->execute([$statusPembatalan, $alasan, $pesanan_id]);
        } else {
            // Jika kolom tidak ada, update tanpa status_pembatalan
            $stmt = $this->pdo->prepare("
                UPDATE pesanan 
                SET status_pesanan = 'cancelled',
                    tanggal_pembatalan = NOW(),
                    alasan_penolakan = ?
                WHERE id = ?
            ");
            $stmt->execute([$alasan, $pesanan_id]);
        }
        
        // 2. Jika sudah lunas, buat claim otomatis untuk refund
        if ($pesanan['status_pembayaran'] == 'lunas') {
            // Cek apakah sudah ada claim sebelumnya
            $stmt = $this->pdo->prepare("SELECT id FROM claim_pengembalian WHERE pesanan_id = ?");
            $stmt->execute([$pesanan_id]);
            
            if ($stmt->rowCount() == 0) {
                $stmt = $this->pdo->prepare("
                    INSERT INTO claim_pengembalian (pesanan_id, wisatawan_id, alasan_claim, status_claim, tanggal_claim) 
                    VALUES (?, ?, ?, 'pending', NOW())
                ");
                $stmt->execute([
                    $pesanan_id,
                    $pesanan['user_id'],
                    "Pesanan dibatalkan oleh supir. Alasan: " . $alasan
                ]);
                
                // Update status claim di pesanan
                $stmt = $this->pdo->prepare("
                    UPDATE pesanan 
                    SET status_claim = 'menunggu',
                        tanggal_claim = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$pesanan_id]);
            }
        }
        
        $this->pdo->commit();
        
        // ================================================================
        // KIRIM NOTIFIKASI
        // ================================================================
        require_once __DIR__ . '/../config/fonnte.php';
        
        $base_url = "http://" . $_SERVER['HTTP_HOST'] . "/reservasi-kapal-wisata";
        
        // Notifikasi ke wisatawan
        if (!empty($pesanan['wisatawan_hp'])) {
            $wa_msg = "
❌ *PESANAN DIBATALKAN OLEH SUPIR* ❌

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

Pesanan Anda dengan kode *{$pesanan['kode_pesanan']}* telah DIBATALKAN oleh supir.

📅 Tanggal: " . date('d/m/Y', strtotime($pesanan['tanggal_berangkat'])) . "
⛵ Kapal: {$pesanan['nama_kapal']}
📝 Alasan: {$alasan}

" . ($pesanan['status_pembayaran'] == 'lunas' ? "
💰 *Claim pengembalian dana telah diajukan secara otomatis!*
Silakan cek status claim Anda di aplikasi.
" : "") . "

Terima kasih. 🌊
";
            sendWhatsApp($pesanan['wisatawan_hp'], $wa_msg);
        }
        
        // Notifikasi di aplikasi
        $stmt = $this->pdo->prepare("
            INSERT INTO notifications (user_id, title, message, booking_id, is_read, created_at) 
            VALUES (?, ?, ?, ?, 0, NOW())
        ");
        
        // Ke wisatawan
        $title = "❌ Pesanan Dibatalkan oleh Supir";
        $msg = "Pesanan {$pesanan['kode_pesanan']} dibatalkan oleh supir. Alasan: {$alasan}";
        $stmt->execute([$pesanan['user_id'], $title, $msg, $pesanan_id]);
        
        // Ke admin
        $stmt->execute([
            1, 
            "⚠️ Pesanan Dibatalkan Supir", 
            "Pesanan {$pesanan['kode_pesanan']} dibatalkan oleh supir. Alasan: {$alasan}",
            $pesanan_id
        ]);
        
        $_SESSION['flash_success'] = "✅ Pesanan berhasil dibatalkan! " . 
            ($pesanan['status_pembayaran'] == 'lunas' ? "Claim refund otomatis diajukan." : "");
        
    } catch (Exception $e) {
        $this->pdo->rollBack();
        error_log("ERROR batalPesanan: " . $e->getMessage());
        $_SESSION['flash_error'] = "❌ Gagal membatalkan: " . $e->getMessage();
    }
    
    header("Location: ?page=supir&action=kelolaPesanan");
    exit;
}            
    /**
     * ================================================================
     * DASHBOARD
     * ================================================================
     */
    public function dashboard() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        // Ambil data supir
        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $supir = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Hitung jumlah kapal
        $stmt = $this->pdo->prepare("SELECT COUNT(*) as total FROM kapal WHERE pemilik_id = ?");
        $stmt->execute([$user_id]);
        $totalKapal = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        // Hitung pesanan masuk
        $stmt = $this->pdo->prepare("
            SELECT COUNT(*) as total FROM pesanan p 
            JOIN kapal k ON p.kapal_id = k.id 
            WHERE k.pemilik_id = ? AND p.status_pesanan = 'pending'
        ");
        $stmt->execute([$user_id]);
        $pesananMasuk = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        // Hitung pendapatan
        $stmt = $this->pdo->prepare("
            SELECT COALESCE(SUM(p.total_harga), 0) as total 
            FROM pesanan p 
            JOIN kapal k ON p.kapal_id = k.id 
            WHERE k.pemilik_id = ? AND p.status_pesanan IN ('confirmed', 'completed')
        ");
        $stmt->execute([$user_id]);
        $totalPendapatan = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
        
        require_once __DIR__ . '/../views/supir/dashboard.php';
    }
    
    /**
     * ================================================================
     * EDIT PROFIL - TAMPILAN FORM
     * ================================================================
     */
    public function editProfile() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        // Ambil data supir
        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $supir = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Hitung jumlah kapal
        $stmt = $this->pdo->prepare("SELECT COUNT(*) as total FROM kapal WHERE pemilik_id = ?");
        $stmt->execute([$user_id]);
        $totalKapal = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        // Hitung pesanan masuk
        $stmt = $this->pdo->prepare("
            SELECT COUNT(*) as total FROM pesanan p 
            JOIN kapal k ON p.kapal_id = k.id 
            WHERE k.pemilik_id = ? AND p.status_pesanan = 'pending'
        ");
        $stmt->execute([$user_id]);
        $pesananMasuk = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
        
        if (!$supir) {
            $_SESSION['flash_error'] = "Data tidak ditemukan.";
            header("Location: ?page=supir&action=dashboard");
            exit;
        }
        
        require_once __DIR__ . '/../views/supir/edit_profile.php';
    }
    
    /**
     * ================================================================
     * UPDATE PROFIL - PROSES UPDATE
     * ================================================================
     */
    public function updateProfile() {
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            header("Location: ?page=supir&action=editProfile");
            exit;
        }
        
        $user_id = $_SESSION['user_id'];
        $nama = trim($_POST['nama'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $no_hp = trim($_POST['no_hp'] ?? '');
        $password = $_POST['password'] ?? '';
        $password_confirm = $_POST['password_confirm'] ?? '';
        
        // Validasi
        $errors = [];
        
        if (empty($nama)) {
            $errors[] = "Nama lengkap harus diisi.";
        }
        
        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = "Email tidak valid.";
        }
        
        if (empty($no_hp)) {
            $errors[] = "Nomor HP harus diisi.";
        }
        
        // Cek email duplikat (kecuali email sendiri)
        $stmt = $this->pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
        $stmt->execute([$email, $user_id]);
        if ($stmt->fetch()) {
            $errors[] = "Email sudah digunakan oleh akun lain.";
        }
        
        // Cek password jika diisi
        if (!empty($password)) {
            if (strlen($password) < 6) {
                $errors[] = "Password minimal 6 karakter.";
            }
            if ($password !== $password_confirm) {
                $errors[] = "Konfirmasi password tidak cocok.";
            }
        }
        
        if (!empty($errors)) {
            $_SESSION['flash_error'] = implode("<br>", $errors);
            header("Location: ?page=supir&action=editProfile");
            exit;
        }
        
        try {
            // Update data
            if (!empty($password)) {
                // Update dengan password baru
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $this->pdo->prepare("
                    UPDATE users 
                    SET nama = ?, 
                        email = ?, 
                        no_hp = ?, 
                        password = ?,
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$nama, $email, $no_hp, $hashed_password, $user_id]);
            } else {
                // Update tanpa password
                $stmt = $this->pdo->prepare("
                    UPDATE users 
                    SET nama = ?, 
                        email = ?, 
                        no_hp = ?,
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$nama, $email, $no_hp, $user_id]);
            }
            
            // Update session
            $_SESSION['nama'] = $nama;
            $_SESSION['email'] = $email;
            $_SESSION['no_hp'] = $no_hp;
            
            $_SESSION['flash_success'] = "✅ Profil berhasil diperbarui!";
            
        } catch (Exception $e) {
            $_SESSION['flash_error'] = "Gagal memperbarui profil: " . $e->getMessage();
        }
        
        header("Location: ?page=supir&action=editProfile");
        exit;
    }
    
    /**
     * ================================================================
     * UPDATE FOTO PROFIL - VERSION FORM SUBMIT (TANPA AJAX)
     * ================================================================
     */
    public function updateProfilePhoto() {
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            $_SESSION['flash_error'] = "Method tidak diizinkan";
            header("Location: ?page=supir&action=editProfile");
            exit;
        }
        
        if (!isset($_SESSION['user_id'])) {
            $_SESSION['flash_error'] = "Session tidak valid";
            header("Location: ?page=supir&action=editProfile");
            exit;
        }
        
        $user_id = $_SESSION['user_id'];
        
        if (!isset($_FILES['foto']) || $_FILES['foto']['error'] !== 0) {
            $_SESSION['flash_error'] = "Gagal upload foto! Silakan pilih file yang valid.";
            header("Location: ?page=supir&action=editProfile");
            exit;
        }
        
        $file = $_FILES['foto'];
        $allowed = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp'];
        
        $fileType = mime_content_type($file['tmp_name']);
        if (!in_array($fileType, $allowed)) {
            $_SESSION['flash_error'] = "Format file tidak didukung! Gunakan JPG, PNG, atau WebP.";
            header("Location: ?page=supir&action=editProfile");
            exit;
        }
        
        if ($file['size'] > 2 * 1024 * 1024) {
            $_SESSION['flash_error'] = "Ukuran file terlalu besar! Maksimal 2MB.";
            header("Location: ?page=supir&action=editProfile");
            exit;
        }
        
        try {
            $stmt = $this->pdo->prepare("SELECT foto FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!empty($user['foto'])) {
                $oldPath = __DIR__ . '/../uploads/profile/' . $user['foto'];
                if (file_exists($oldPath)) {
                    @unlink($oldPath);
                }
            }
            
            $uploadDir = __DIR__ . '/../uploads/profile/';
            if (!is_dir($uploadDir)) {
                if (!mkdir($uploadDir, 0777, true)) {
                    $_SESSION['flash_error'] = "Gagal membuat direktori upload";
                    header("Location: ?page=supir&action=editProfile");
                    exit;
                }
            }
            
            $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
            $filename = time() . '_' . uniqid() . '.' . $extension;
            $fullPath = $uploadDir . $filename;
            
            if (!move_uploaded_file($file['tmp_name'], $fullPath)) {
                $_SESSION['flash_error'] = "Gagal menyimpan file!";
                header("Location: ?page=supir&action=editProfile");
                exit;
            }
            
            $stmt = $this->pdo->prepare("UPDATE users SET foto = ? WHERE id = ?");
            $result = $stmt->execute([$filename, $user_id]);
            
            if (!$result) {
                if (file_exists($fullPath)) {
                    @unlink($fullPath);
                }
                $_SESSION['flash_error'] = "Gagal update database";
                header("Location: ?page=supir&action=editProfile");
                exit;
            }
            
            $_SESSION['foto'] = $filename;
            $_SESSION['flash_success'] = "✅ Foto profil berhasil diperbarui!";
            
        } catch (Exception $e) {
            $_SESSION['flash_error'] = "Terjadi kesalahan: " . $e->getMessage();
        }
        
        header("Location: ?page=supir&action=editProfile");
        exit;
    }
    
    /**
     * ================================================================
     * KELOLA KAPAL
     * ================================================================
     */
    public function kelolaKapal() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        $stmt = $this->pdo->prepare("
            SELECT * FROM kapal 
            WHERE pemilik_id = ? 
            ORDER BY created_at DESC
        ");
        $stmt->execute([$user_id]);
        $kapalList = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        require_once __DIR__ . '/../views/supir/kelola_kapal.php';
    }
    
    /**
     * ================================================================
     * BATALKAN REQUEST HAPUS KAPAL
     * ================================================================
     */
    public function batalkanRequestHapus() {
        // Cek method POST
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            $_SESSION['flash_error'] = "Method tidak diizinkan.";
            header("Location: ?page=supir&action=kelolaKapal");
            exit;
        }
        
        $user_id = $_SESSION['user_id'];
        $request_id = isset($_POST['request_id']) ? (int)$_POST['request_id'] : 0;
        
        if ($request_id <= 0) {
            $_SESSION['flash_error'] = "❌ ID request tidak valid!";
            header("Location: ?page=supir&action=kelolaKapal");
            exit;
        }
        
        try {
            // Cek kepemilikan request
            $checkQuery = "SELECT id, kapal_id, nama_kapal FROM request_hapus_kapal 
                           WHERE id = ? AND pemilik_id = ? AND hapus_request = 'pending'";
            $checkStmt = $this->pdo->prepare($checkQuery);
            $checkStmt->execute([$request_id, $user_id]);
            $request = $checkStmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$request) {
                $_SESSION['flash_error'] = "❌ Request tidak ditemukan atau sudah diproses!";
                header("Location: ?page=supir&action=kelolaKapal");
                exit;
            }
            
            // Hapus request
            $deleteQuery = "DELETE FROM request_hapus_kapal WHERE id = ?";
            $deleteStmt = $this->pdo->prepare($deleteQuery);
            $deleteStmt->execute([$request_id]);
            
            $_SESSION['flash_success'] = '✅ Request hapus kapal "' . $request['nama_kapal'] . '" berhasil dibatalkan!';
            
        } catch (Exception $e) {
            $_SESSION['flash_error'] = "❌ Gagal membatalkan request: " . $e->getMessage();
        }
        
        header("Location: ?page=supir&action=kelolaKapal");
        exit;
    }
    
    /**
     * TAMBAH KAPAL
     */
    public function tambahKapal() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $nama_kapal = trim($_POST['nama_kapal'] ?? '');
            $jenis = trim($_POST['jenis'] ?? '');
            $kapasitas = (int)($_POST['kapasitas'] ?? 0);
            $deskripsi = trim($_POST['deskripsi'] ?? '');
            $harga_sewa = (int)($_POST['harga_sewa'] ?? 0);
            $pelabuhan = trim($_POST['pelabuhan'] ?? '');
            
            $errors = [];
            if (empty($nama_kapal)) $errors[] = "Nama kapal harus diisi.";
            if (empty($jenis)) $errors[] = "Jenis kapal harus diisi.";
            if ($kapasitas <= 0) $errors[] = "Kapasitas harus diisi dengan benar.";
            if ($harga_sewa <= 0) $errors[] = "Harga sewa harus diisi dengan benar.";
            if (empty($pelabuhan)) $errors[] = "Pelabuhan harus diisi.";
            
            if (!empty($errors)) {
                $_SESSION['flash_error'] = implode("<br>", $errors);
                header("Location: ?page=supir&action=tambahKapal");
                exit;
            }
            
            try {
                $stmt = $this->pdo->prepare("
                    INSERT INTO kapal (pemilik_id, nama_kapal, jenis, kapasitas, deskripsi, harga_sewa, pelabuhan, status_verifikasi, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
                ");
                $stmt->execute([$user_id, $nama_kapal, $jenis, $kapasitas, $deskripsi, $harga_sewa, $pelabuhan]);
                
                $_SESSION['flash_success'] = "✅ Kapal berhasil ditambahkan! Menunggu verifikasi admin.";
                header("Location: ?page=supir&action=kelolaKapal");
                exit;
                
            } catch (Exception $e) {
                $_SESSION['flash_error'] = "Gagal menambahkan kapal: " . $e->getMessage();
            }
        }
        
        require_once __DIR__ . '/../views/supir/tambah_kapal.php';
    }
    
    /**
     * EDIT KAPAL
     */
    public function editKapal() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        
        if (empty($id)) {
            $_SESSION['flash_error'] = "ID kapal tidak valid.";
            header("Location: ?page=supir&action=kelolaKapal");
            exit;
        }
        
        $stmt = $this->pdo->prepare("SELECT * FROM kapal WHERE id = ? AND pemilik_id = ?");
        $stmt->execute([$id, $user_id]);
        $kapal = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$kapal) {
            $_SESSION['flash_error'] = "Kapal tidak ditemukan.";
            header("Location: ?page=supir&action=kelolaKapal");
            exit;
        }
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $nama_kapal = trim($_POST['nama_kapal'] ?? '');
            $jenis = trim($_POST['jenis'] ?? '');
            $kapasitas = (int)($_POST['kapasitas'] ?? 0);
            $deskripsi = trim($_POST['deskripsi'] ?? '');
            $harga_sewa = (int)($_POST['harga_sewa'] ?? 0);
            $pelabuhan = trim($_POST['pelabuhan'] ?? '');
            
            $errors = [];
            if (empty($nama_kapal)) $errors[] = "Nama kapal harus diisi.";
            if (empty($jenis)) $errors[] = "Jenis kapal harus diisi.";
            if ($kapasitas <= 0) $errors[] = "Kapasitas harus diisi dengan benar.";
            if ($harga_sewa <= 0) $errors[] = "Harga sewa harus diisi dengan benar.";
            if (empty($pelabuhan)) $errors[] = "Pelabuhan harus diisi.";
            
            if (!empty($errors)) {
                $_SESSION['flash_error'] = implode("<br>", $errors);
                header("Location: ?page=supir&action=editKapal&id=" . $id);
                exit;
            }
            
            try {
                $stmt = $this->pdo->prepare("
                    UPDATE kapal 
                    SET nama_kapal = ?, 
                        jenis = ?, 
                        kapasitas = ?, 
                        deskripsi = ?, 
                        harga_sewa = ?, 
                        pelabuhan = ?,
                        updated_at = NOW()
                    WHERE id = ? AND pemilik_id = ?
                ");
                $stmt->execute([$nama_kapal, $jenis, $kapasitas, $deskripsi, $harga_sewa, $pelabuhan, $id, $user_id]);
                
                $_SESSION['flash_success'] = "✅ Kapal berhasil diperbarui!";
                header("Location: ?page=supir&action=kelolaKapal");
                exit;
                
            } catch (Exception $e) {
                $_SESSION['flash_error'] = "Gagal memperbarui kapal: " . $e->getMessage();
            }
        }
        
        require_once __DIR__ . '/../views/supir/edit_kapal.php';
    }
    
    /**
     * HAPUS KAPAL
     */
    public function hapusKapal() {
        $user_id = $_SESSION['user_id'];
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        
        if (empty($id)) {
            $_SESSION['flash_error'] = "ID kapal tidak valid.";
            header("Location: ?page=supir&action=kelolaKapal");
            exit;
        }
        
        $stmt = $this->pdo->prepare("SELECT nama_kapal FROM kapal WHERE id = ? AND pemilik_id = ?");
        $stmt->execute([$id, $user_id]);
        $kapal = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$kapal) {
            $_SESSION['flash_error'] = "Kapal tidak ditemukan atau bukan milik Anda.";
            header("Location: ?page=supir&action=kelolaKapal");
            exit;
        }
        
        try {
            $this->pdo->beginTransaction();
            
            // Hapus data terkait
            $relatedTables = ['shared_trip_participants', 'shared_trips', 'kapal_rute', 'schedules', 'pesanan'];
            foreach ($relatedTables as $table) {
                if ($this->tableExists($table)) {
                    try {
                        $stmt = $this->pdo->prepare("DELETE FROM $table WHERE kapal_id = ?");
                        $stmt->execute([$id]);
                    } catch (Exception $e) {
                        // Ignore
                    }
                }
            }
            
            // Hapus kapal
            $stmt = $this->pdo->prepare("DELETE FROM kapal WHERE id = ? AND pemilik_id = ?");
            $stmt->execute([$id, $user_id]);
            
            $this->pdo->commit();
            
            $_SESSION['flash_success'] = "✅ Kapal '{$kapal['nama_kapal']}' berhasil dihapus!";
            
        } catch (Exception $e) {
            $this->pdo->rollBack();
            $_SESSION['flash_error'] = "Gagal menghapus kapal: " . $e->getMessage();
        }
        
        header("Location: ?page=supir&action=kelolaKapal");
        exit;
    }
    
    /**
     * DETAIL KAPAL
     */
    public function detailKapal() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        
        if (empty($id)) {
            $_SESSION['flash_error'] = "ID kapal tidak valid.";
            header("Location: ?page=supir&action=kelolaKapal");
            exit;
        }
        
        $stmt = $this->pdo->prepare("
            SELECT k.*, 
                   (SELECT COUNT(*) FROM pesanan WHERE kapal_id = k.id) as total_pesanan,
                   (SELECT COUNT(*) FROM schedules WHERE kapal_id = k.id) as total_jadwal
            FROM kapal k 
            WHERE k.id = ? AND k.pemilik_id = ?
        ");
        $stmt->execute([$id, $user_id]);
        $kapal = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$kapal) {
            $_SESSION['flash_error'] = "Kapal tidak ditemukan.";
            header("Location: ?page=supir&action=kelolaKapal");
            exit;
        }
        
        require_once __DIR__ . '/../views/supir/detail_kapal.php';
    }
    
    /**
     * ================================================================
     * KELOLA RUTE
     * ================================================================
     */
    public function kelolaRute() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        $stmt = $this->pdo->prepare("
            SELECT id, nama_kapal FROM kapal 
            WHERE pemilik_id = ? AND status_verifikasi = 'verified'
            ORDER BY nama_kapal ASC
        ");
        $stmt->execute([$user_id]);
        $kapalList = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $stmt = $this->pdo->prepare("
            SELECT r.*, k.nama_kapal 
            FROM kapal_rute r 
            JOIN kapal k ON r.kapal_id = k.id 
            WHERE k.pemilik_id = ? 
            ORDER BY r.created_at DESC
        ");
        $stmt->execute([$user_id]);
        $ruteList = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        require_once __DIR__ . '/../views/supir/kelola_rute_kapal.php';
    }
    
    /**
     * KELOLA RUTE KAPAL - VIA MENU SIDEBAR
     */
    public function kelolaRuteKapal() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        $stmt = $this->pdo->prepare("
            SELECT id, nama_kapal FROM kapal 
            WHERE pemilik_id = ? AND status_verifikasi = 'verified'
            ORDER BY nama_kapal ASC
        ");
        $stmt->execute([$user_id]);
        $kapalList = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $stmt = $this->pdo->prepare("
            SELECT r.*, k.nama_kapal 
            FROM kapal_rute r 
            JOIN kapal k ON r.kapal_id = k.id 
            WHERE k.pemilik_id = ? 
            ORDER BY r.created_at DESC
        ");
        $stmt->execute([$user_id]);
        $kapalRute = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        require_once __DIR__ . '/../views/supir/kelola_rute_kapal.php';
    }
    
    /**
     * TAMBAH RUTE
     */
    public function tambahRute() {
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            header("Location: ?page=supir&action=kelolaRute");
            exit;
        }
        
        $user_id = $_SESSION['user_id'];
        
        $kapal_id = isset($_POST['kapal_id']) ? (int)$_POST['kapal_id'] : 0;
        $asal = trim($_POST['asal'] ?? '');
        $tujuan = trim($_POST['tujuan'] ?? '');
        $harga = isset($_POST['harga']) ? (int)$_POST['harga'] : 0;
        $deskripsi = trim($_POST['deskripsi'] ?? '');
        $destinasi = isset($_POST['destinasi']) ? $_POST['destinasi'] : [];
        
        $errors = [];
        if ($kapal_id <= 0) $errors[] = "Pilih kapal terlebih dahulu.";
        if (empty($asal)) $errors[] = "Lokasi asal harus diisi.";
        if (empty($tujuan)) $errors[] = "Tujuan harus diisi.";
        if ($harga <= 0) $errors[] = "Harga harus diisi dengan benar.";
        
        if (!empty($errors)) {
            $_SESSION['flash_error'] = implode("<br>", $errors);
            header("Location: ?page=supir&action=kelolaRute");
            exit;
        }
        
        $destinasi_clean = array_filter($destinasi, function($d) { return !empty(trim($d)); });
        
        try {
            $stmt = $this->pdo->prepare("SELECT id FROM kapal WHERE id = ? AND pemilik_id = ?");
            $stmt->execute([$kapal_id, $user_id]);
            if (!$stmt->fetch()) {
                $_SESSION['flash_error'] = "Kapal tidak ditemukan atau bukan milik Anda.";
                header("Location: ?page=supir&action=kelolaRute");
                exit;
            }
            
            $all_tujuan = array_merge([$tujuan], $destinasi_clean);
            $rute_string = $asal . ' → ' . implode(' → ', $all_tujuan);
            
            $stmt = $this->pdo->prepare("
                INSERT INTO kapal_rute (kapal_id, asal, tujuan, harga_jual, deskripsi, created_at) 
                VALUES (?, ?, ?, ?, ?, NOW())
            ");
            $stmt->execute([$kapal_id, $asal, $rute_string, $harga, $deskripsi]);
            
            $_SESSION['flash_success'] = "✅ Rute berhasil ditambahkan!";
            
        } catch (Exception $e) {
            $_SESSION['flash_error'] = "Gagal menambahkan rute: " . $e->getMessage();
        }
        
        header("Location: ?page=supir&action=kelolaRute");
        exit;
    }
    
    /**
     * EDIT RUTE - TAMPILAN FORM EDIT
     */
    public function editRute() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        
        if (empty($id)) {
            $_SESSION['flash_error'] = "ID rute tidak valid.";
            header("Location: ?page=supir&action=kelolaRute");
            exit;
        }
        
        $stmt = $this->pdo->prepare("
            SELECT r.*, k.nama_kapal 
            FROM kapal_rute r 
            JOIN kapal k ON r.kapal_id = k.id 
            WHERE r.id = ? AND k.pemilik_id = ?
        ");
        $stmt->execute([$id, $user_id]);
        $ruteData = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$ruteData) {
            $_SESSION['flash_error'] = "Rute tidak ditemukan atau bukan milik Anda.";
            header("Location: ?page=supir&action=kelolaRute");
            exit;
        }
        
        $stmt = $this->pdo->prepare("
            SELECT id, nama_kapal FROM kapal 
            WHERE pemilik_id = ? AND status_verifikasi = 'verified'
            ORDER BY nama_kapal ASC
        ");
        $stmt->execute([$user_id]);
        $kapalList = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $stmt = $this->pdo->prepare("
            SELECT r.*, k.nama_kapal 
            FROM kapal_rute r 
            JOIN kapal k ON r.kapal_id = k.id 
            WHERE k.pemilik_id = ? 
            ORDER BY r.created_at DESC
        ");
        $stmt->execute([$user_id]);
        $ruteList = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        require_once __DIR__ . '/../views/supir/kelola_rute_kapal.php';
    }
    
    /**
     * UPDATE RUTE
     */
    public function updateRute() {
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            header("Location: ?page=supir&action=kelolaRute");
            exit;
        }
        
        $user_id = $_SESSION['user_id'];
        
        $rute_id = isset($_POST['rute_id']) ? (int)$_POST['rute_id'] : 0;
        $kapal_id = isset($_POST['kapal_id']) ? (int)$_POST['kapal_id'] : 0;
        $asal = trim($_POST['asal'] ?? '');
        $tujuan = trim($_POST['tujuan'] ?? '');
        $harga = isset($_POST['harga']) ? (int)$_POST['harga'] : 0;
        $deskripsi = trim($_POST['deskripsi'] ?? '');
        $destinasi = isset($_POST['destinasi']) ? $_POST['destinasi'] : [];
        
        $errors = [];
        if ($rute_id <= 0) $errors[] = "ID rute tidak valid.";
        if ($kapal_id <= 0) $errors[] = "Pilih kapal terlebih dahulu.";
        if (empty($asal)) $errors[] = "Lokasi asal harus diisi.";
        if (empty($tujuan)) $errors[] = "Tujuan harus diisi.";
        if ($harga <= 0) $errors[] = "Harga harus diisi dengan benar.";
        
        if (!empty($errors)) {
            $_SESSION['flash_error'] = implode("<br>", $errors);
            header("Location: ?page=supir&action=kelolaRute");
            exit;
        }
        
        $destinasi_clean = array_filter($destinasi, function($d) { return !empty(trim($d)); });
        
        try {
            $stmt = $this->pdo->prepare("
                SELECT r.id FROM kapal_rute r 
                JOIN kapal k ON r.kapal_id = k.id 
                WHERE r.id = ? AND k.pemilik_id = ?
            ");
            $stmt->execute([$rute_id, $user_id]);
            if (!$stmt->fetch()) {
                $_SESSION['flash_error'] = "Rute tidak ditemukan atau bukan milik Anda.";
                header("Location: ?page=supir&action=kelolaRute");
                exit;
            }
            
            $all_tujuan = array_merge([$tujuan], $destinasi_clean);
            $rute_string = $asal . ' → ' . implode(' → ', $all_tujuan);
            
            $stmt = $this->pdo->prepare("
                UPDATE kapal_rute 
                SET kapal_id = ?, asal = ?, tujuan = ?, harga_jual = ?, deskripsi = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$kapal_id, $asal, $rute_string, $harga, $deskripsi, $rute_id]);
            
            $_SESSION['flash_success'] = "✅ Rute berhasil diperbarui!";
            
        } catch (Exception $e) {
            $_SESSION['flash_error'] = "Gagal memperbarui rute: " . $e->getMessage();
        }
        
        header("Location: ?page=supir&action=kelolaRute");
        exit;
    }
    
    /**
     * HAPUS RUTE
     */
    public function hapusRute() {
        $user_id = $_SESSION['user_id'];
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        
        if (empty($id)) {
            $_SESSION['flash_error'] = "ID rute tidak valid.";
            header("Location: ?page=supir&action=kelolaRute");
            exit;
        }
        
        try {
            $stmt = $this->pdo->prepare("
                DELETE r FROM kapal_rute r 
                JOIN kapal k ON r.kapal_id = k.id 
                WHERE r.id = ? AND k.pemilik_id = ?
            ");
            $stmt->execute([$id, $user_id]);
            
            if ($stmt->rowCount() > 0) {
                $_SESSION['flash_success'] = "✅ Rute berhasil dihapus!";
            } else {
                $_SESSION['flash_error'] = "Rute tidak ditemukan atau bukan milik Anda.";
            }
            
        } catch (Exception $e) {
            $_SESSION['flash_error'] = "Gagal menghapus rute: " . $e->getMessage();
        }
        
        header("Location: ?page=supir&action=kelolaRute");
        exit;
    }
    
    /**
     * ================================================================
     * KELOLA JADWAL
     * ================================================================
     */
    public function kelolaJadwal() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        $stmt = $this->pdo->prepare("
            SELECT s.*, k.nama_kapal 
            FROM schedules s 
            JOIN kapal k ON s.kapal_id = k.id 
            WHERE k.pemilik_id = ? 
            ORDER BY s.tanggal_berangkat DESC
        ");
        $stmt->execute([$user_id]);
        $jadwalList = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        require_once __DIR__ . '/../views/supir/kelola_jadwal.php';
    }
    
    /**
     * TAMBAH JADWAL
     */
    public function tambahJadwal() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        $stmt = $this->pdo->prepare("
            SELECT id, nama_kapal FROM kapal 
            WHERE pemilik_id = ? AND status_verifikasi = 'verified'
        ");
        $stmt->execute([$user_id]);
        $kapalList = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $stmt = $this->pdo->prepare("
            SELECT r.id, r.rute, k.nama_kapal 
            FROM kapal_rute r 
            JOIN kapal k ON r.kapal_id = k.id 
            WHERE k.pemilik_id = ?
        ");
        $stmt->execute([$user_id]);
        $ruteList = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $kapal_id = (int)($_POST['kapal_id'] ?? 0);
            $rute_id = (int)($_POST['rute_id'] ?? 0);
            $tanggal_berangkat = $_POST['tanggal_berangkat'] ?? '';
            $jam_berangkat = $_POST['jam_berangkat'] ?? '';
            $harga = (int)($_POST['harga'] ?? 0);
            $kuota = (int)($_POST['kuota'] ?? 0);
            
            $errors = [];
            if ($kapal_id <= 0) $errors[] = "Pilih kapal terlebih dahulu.";
            if ($rute_id <= 0) $errors[] = "Pilih rute terlebih dahulu.";
            if (empty($tanggal_berangkat)) $errors[] = "Tanggal berangkat harus diisi.";
            if (empty($jam_berangkat)) $errors[] = "Jam berangkat harus diisi.";
            if ($harga <= 0) $errors[] = "Harga harus diisi dengan benar.";
            if ($kuota <= 0) $errors[] = "Kuota harus diisi dengan benar.";
            
            if (!empty($errors)) {
                $_SESSION['flash_error'] = implode("<br>", $errors);
                header("Location: ?page=supir&action=tambahJadwal");
                exit;
            }
            
            try {
                $stmt = $this->pdo->prepare("
                    INSERT INTO schedules (kapal_id, rute_id, tanggal_berangkat, jam_berangkat, harga, kuota, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, NOW())
                ");
                $stmt->execute([$kapal_id, $rute_id, $tanggal_berangkat, $jam_berangkat, $harga, $kuota]);
                
                $_SESSION['flash_success'] = "✅ Jadwal berhasil ditambahkan!";
                header("Location: ?page=supir&action=kelolaJadwal");
                exit;
                
            } catch (Exception $e) {
                $_SESSION['flash_error'] = "Gagal menambahkan jadwal: " . $e->getMessage();
            }
        }
        
        require_once __DIR__ . '/../views/supir/tambah_jadwal.php';
    }
    
    /**
     * EDIT JADWAL
     */
    public function editJadwal() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        
        if (empty($id)) {
            $_SESSION['flash_error'] = "ID jadwal tidak valid.";
            header("Location: ?page=supir&action=kelolaJadwal");
            exit;
        }
        
        $stmt = $this->pdo->prepare("
            SELECT s.*, k.nama_kapal, k.pemilik_id 
            FROM schedules s 
            JOIN kapal k ON s.kapal_id = k.id 
            WHERE s.id = ? AND k.pemilik_id = ?
        ");
        $stmt->execute([$id, $user_id]);
        $jadwal = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$jadwal) {
            $_SESSION['flash_error'] = "Jadwal tidak ditemukan.";
            header("Location: ?page=supir&action=kelolaJadwal");
            exit;
        }
        
        $stmt = $this->pdo->prepare("
            SELECT id, nama_kapal FROM kapal 
            WHERE pemilik_id = ? AND status_verifikasi = 'verified'
        ");
        $stmt->execute([$user_id]);
        $kapalList = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $stmt = $this->pdo->prepare("
            SELECT r.id, r.rute, k.nama_kapal 
            FROM kapal_rute r 
            JOIN kapal k ON r.kapal_id = k.id 
            WHERE k.pemilik_id = ?
        ");
        $stmt->execute([$user_id]);
        $ruteList = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $kapal_id = (int)($_POST['kapal_id'] ?? 0);
            $rute_id = (int)($_POST['rute_id'] ?? 0);
            $tanggal_berangkat = $_POST['tanggal_berangkat'] ?? '';
            $jam_berangkat = $_POST['jam_berangkat'] ?? '';
            $harga = (int)($_POST['harga'] ?? 0);
            $kuota = (int)($_POST['kuota'] ?? 0);
            
            $errors = [];
            if ($kapal_id <= 0) $errors[] = "Pilih kapal terlebih dahulu.";
            if ($rute_id <= 0) $errors[] = "Pilih rute terlebih dahulu.";
            if (empty($tanggal_berangkat)) $errors[] = "Tanggal berangkat harus diisi.";
            if (empty($jam_berangkat)) $errors[] = "Jam berangkat harus diisi.";
            if ($harga <= 0) $errors[] = "Harga harus diisi dengan benar.";
            if ($kuota <= 0) $errors[] = "Kuota harus diisi dengan benar.";
            
            if (!empty($errors)) {
                $_SESSION['flash_error'] = implode("<br>", $errors);
                header("Location: ?page=supir&action=editJadwal&id=" . $id);
                exit;
            }
            
            try {
                $stmt = $this->pdo->prepare("
                    UPDATE schedules 
                    SET kapal_id = ?, 
                        rute_id = ?, 
                        tanggal_berangkat = ?, 
                        jam_berangkat = ?, 
                        harga = ?, 
                        kuota = ?,
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$kapal_id, $rute_id, $tanggal_berangkat, $jam_berangkat, $harga, $kuota, $id]);
                
                $_SESSION['flash_success'] = "✅ Jadwal berhasil diperbarui!";
                header("Location: ?page=supir&action=kelolaJadwal");
                exit;
                
            } catch (Exception $e) {
                $_SESSION['flash_error'] = "Gagal memperbarui jadwal: " . $e->getMessage();
            }
        }
        
        require_once __DIR__ . '/../views/supir/edit_jadwal.php';
    }
    
    /**
     * HAPUS JADWAL
     */
    public function hapusJadwal() {
        $user_id = $_SESSION['user_id'];
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        
        if (empty($id)) {
            $_SESSION['flash_error'] = "ID jadwal tidak valid.";
            header("Location: ?page=supir&action=kelolaJadwal");
            exit;
        }
        
        try {
            $stmt = $this->pdo->prepare("
                DELETE s FROM schedules s 
                JOIN kapal k ON s.kapal_id = k.id 
                WHERE s.id = ? AND k.pemilik_id = ?
            ");
            $stmt->execute([$id, $user_id]);
            
            $_SESSION['flash_success'] = "✅ Jadwal berhasil dihapus!";
            
        } catch (Exception $e) {
            $_SESSION['flash_error'] = "Gagal menghapus jadwal: " . $e->getMessage();
        }
        
        header("Location: ?page=supir&action=kelolaJadwal");
        exit;
    }
    
    /**
     * ================================================================
     * KELOLA PESANAN
     * ================================================================
     */
    public function kelolaPesanan() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        $status = isset($_GET['status']) ? $_GET['status'] : 'all';
        
        $sql = "
            SELECT p.*, k.nama_kapal, u.nama as wisatawan_nama, u.no_hp as wisatawan_hp
            FROM pesanan p 
            JOIN kapal k ON p.kapal_id = k.id 
            JOIN users u ON p.user_id = u.id 
            WHERE k.pemilik_id = ?
        ";
        
        if ($status != 'all') {
            $sql .= " AND p.status_pesanan = ?";
        }
        
        $sql .= " ORDER BY p.created_at DESC";
        
        $stmt = $this->pdo->prepare($sql);
        if ($status != 'all') {
            $stmt->execute([$user_id, $status]);
        } else {
            $stmt->execute([$user_id]);
        }
        $pesananList = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        require_once __DIR__ . '/../views/supir/kelola_pesanan.php';
    }
    
    /**
 * ================================================================
 * 🔥 DETAIL PESANAN - DIPERBAIKI DENGAN PENGECEKAN KOLOM
 * ================================================================
 */
public function detailPesanan() {
    // Cek login
    if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'pemilik_kapal') {
        $_SESSION['flash_error'] = 'Anda harus login sebagai supir.';
        header('Location: ?page=supir&action=login');
        exit;
    }
    
    $pesanan_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    $supir_id = (int)$_SESSION['user_id'];
    
    if ($pesanan_id <= 0) {
        $_SESSION['flash_error'] = 'ID pesanan tidak valid.';
        header('Location: ?page=supir&action=kelolaPesanan');
        exit;
    }
    
    $unreadCount = $this->getUnreadCountPrivate($supir_id);
    
    // Ambil data supir
    $stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$supir_id]);
    $supir = $stmt->fetch(PDO::FETCH_ASSOC);
    
    try {
        // ==============================================
        // 🔥 CEK KOLOM YANG ADA DI TABEL PESANAN
        // ==============================================
        $columns = $this->getTableColumns('pesanan');
        
        // ==============================================
        // 🔥 BUILD SELECT QUERY DINAMIS - BASE FIELDS
        // ==============================================
        $selectFields = "
            p.*,
            p.id as pesanan_id,
            p.kode_pesanan,
            p.tanggal_berangkat,
            p.created_at,
            p.durasi_jam,
            p.jumlah_tiket,
            p.total_harga,
            p.status_pesanan,
            p.status_pembayaran,
            p.status_pencairan,
            p.status_claim,
            p.status_pembatalan,
            p.jenis_booking,
            p.nama_lengkap,
            p.email,
            p.no_hp,
            p.nik_ktp,
            p.catatan,
            p.komisi_admin,
            p.nominal_diterima_supir,
            p.reschedule_status,
            p.reschedule_tanggal_baru,
            p.reschedule_alasan,
            p.alasan_penolakan,
            p.snap_token,
            p.snap_url,
            p.metode_pembayaran,
            p.tanggal_bayar,
            p.tanggal_konfirmasi_pembayaran,
            p.tanggal_pembatalan
        ";
        
        // ==============================================
        // 🔥 TAMBAHKAN FIELD BARU JIKA ADA (TANPA updated_at)
        // ==============================================
        $newFields = [
            'waktu_jemput_rencana',
            'waktu_selesai_rencana',
            'waktu_jemput_aktual',
            'waktu_selesai_aktual',
            'jenis_pembayaran',
            'jumlah_dibayar',
            'sisa_pembayaran',
            'status_keberangkatan',
            'reschedule_tanggal_ajuan',
            'reschedule_tanggal_respon',
            'reschedule_alasan_penolakan',
            'tanggal_selesai',
            'alasan_batal_otomatis'
        ];
        
        foreach ($newFields as $field) {
            if (in_array($field, $columns)) {
                $selectFields .= ", p.`$field`";
            }
        }
        
        // ==============================================
        // 🔥 QUERY LENGKAP
        // ==============================================
        $sql = "
            SELECT 
                $selectFields,
                
                -- Data kapal
                k.nama_kapal,
                k.pelabuhan_asal,
                k.pelabuhan_tujuan,
                k.fasilitas,
                k.foto,
                k.kapasitas,
                k.jenis,
                k.pemilik_id,
                k.status_verifikasi as kapal_status_verifikasi,
                
                -- Data rute
                kr.asal as route_asal,
                kr.tujuan as route_tujuan,
                kr.harga_jual as route_harga,
                kr.id as route_id,
                
                -- Data wisatawan
                u.nama as wisatawan_nama,
                u.email as wisatawan_email,
                u.no_hp as wisatawan_hp,
                u.foto as wisatawan_foto,
                
                -- Data pemilik/supir
                u2.nama as pemilik_nama,
                u2.no_hp as pemilik_hp
                
            FROM pesanan p
            LEFT JOIN kapal k ON p.kapal_id = k.id
            LEFT JOIN kapal_rute kr ON p.route_id = kr.id
            LEFT JOIN users u ON p.user_id = u.id
            LEFT JOIN users u2 ON k.pemilik_id = u2.id
            WHERE p.id = ? AND k.pemilik_id = ?
        ";
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$pesanan_id, $supir_id]);
        $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$pesanan) {
            $_SESSION['flash_error'] = 'Pesanan tidak ditemukan atau bukan milik Anda.';
            header('Location: ?page=supir&action=kelolaPesanan');
            exit;
        }
        
        // Hitung durasi hari
        $pesanan['durasi_hari'] = ceil(($pesanan['durasi_jam'] ?? 24) / 24);
        
        // ==============================================
        // 🔥 SET DEFAULT VALUE UNTUK FIELD YANG TIDAK ADA
        // ==============================================
        // Waktu
        if (!isset($pesanan['waktu_jemput_rencana']) || empty($pesanan['waktu_jemput_rencana'])) {
            $pesanan['waktu_jemput_rencana'] = null;
        }
        if (!isset($pesanan['waktu_selesai_rencana']) || empty($pesanan['waktu_selesai_rencana'])) {
            $pesanan['waktu_selesai_rencana'] = null;
        }
        if (!isset($pesanan['waktu_jemput_aktual']) || empty($pesanan['waktu_jemput_aktual'])) {
            $pesanan['waktu_jemput_aktual'] = null;
        }
        if (!isset($pesanan['waktu_selesai_aktual']) || empty($pesanan['waktu_selesai_aktual'])) {
            $pesanan['waktu_selesai_aktual'] = null;
        }
        
        // Jenis pembayaran
        if (!isset($pesanan['jenis_pembayaran']) || empty($pesanan['jenis_pembayaran'])) {
            $pesanan['jenis_pembayaran'] = 'full';
        }
        if (!isset($pesanan['jumlah_dibayar']) || empty($pesanan['jumlah_dibayar'])) {
            $pesanan['jumlah_dibayar'] = 0;
        }
        if (!isset($pesanan['sisa_pembayaran']) || empty($pesanan['sisa_pembayaran'])) {
            $pesanan['sisa_pembayaran'] = 0;
        }
        
        // Status keberangkatan
        if (!isset($pesanan['status_keberangkatan']) || empty($pesanan['status_keberangkatan'])) {
            $pesanan['status_keberangkatan'] = 'menunggu';
        }
        
        // Reschedule
        if (!isset($pesanan['reschedule_tanggal_ajuan']) || empty($pesanan['reschedule_tanggal_ajuan'])) {
            $pesanan['reschedule_tanggal_ajuan'] = null;
        }
        if (!isset($pesanan['reschedule_tanggal_respon']) || empty($pesanan['reschedule_tanggal_respon'])) {
            $pesanan['reschedule_tanggal_respon'] = null;
        }
        if (!isset($pesanan['reschedule_alasan_penolakan']) || empty($pesanan['reschedule_alasan_penolakan'])) {
            $pesanan['reschedule_alasan_penolakan'] = null;
        }
        if (!isset($pesanan['tanggal_selesai']) || empty($pesanan['tanggal_selesai'])) {
            $pesanan['tanggal_selesai'] = null;
        }
        if (!isset($pesanan['alasan_batal_otomatis']) || empty($pesanan['alasan_batal_otomatis'])) {
            $pesanan['alasan_batal_otomatis'] = null;
        }
        
        // Ambil riwayat notifikasi untuk pesanan ini
        $stmt = $this->pdo->prepare("
            SELECT * FROM notifications 
            WHERE booking_id = ? 
            ORDER BY created_at DESC 
            LIMIT 10
        ");
        $stmt->execute([$pesanan_id]);
        $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Hitung total pesanan untuk statistik
        $stmt = $this->pdo->prepare("
            SELECT COUNT(*) as total FROM pesanan p 
            JOIN kapal k ON p.kapal_id = k.id 
            WHERE k.pemilik_id = ?
        ");
        $stmt->execute([$supir_id]);
        $totalPesanan = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
        
        // Hitung pesanan masuk
        $stmt = $this->pdo->prepare("
            SELECT COUNT(*) as total FROM pesanan p 
            JOIN kapal k ON p.kapal_id = k.id 
            WHERE k.pemilik_id = ? AND p.status_pesanan = 'pending'
        ");
        $stmt->execute([$supir_id]);
        $pesananMasuk = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
        
        // Kirim ke view dengan semua数据
        require_once __DIR__ . '/../views/supir/detail_pesanan.php';
        
    } catch (Exception $e) {
        $_SESSION['flash_error'] = 'Error: ' . $e->getMessage();
        header('Location: ?page=supir&action=kelolaPesanan');
        exit;
    }
}
    
    /**
     * ================================================================
     * KONFIRMASI RESCHEDULE - Supir menyetujui/menolak reschedule
     * ================================================================
     */
    public function konfirmasiReschedule() {
        // Cek method
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            $_SESSION['flash_error'] = "Method tidak diizinkan. Gunakan POST.";
            header("Location: ?page=supir&action=kelolaPesanan");
            exit;
        }
        
        $user_id = $_SESSION['user_id'] ?? 0;
        $pesanan_id = (int) ($_POST['pesanan_id'] ?? 0);
        $keputusan = $_POST['keputusan'] ?? ''; // 'setuju' atau 'tolak'
        $alasan = trim($_POST['alasan'] ?? '');
        
        if (empty($pesanan_id) || empty($keputusan)) {
            $_SESSION['flash_error'] = "Data tidak lengkap.";
            header("Location: ?page=supir&action=kelolaPesanan");
            exit;
        }
        
        try {
            // Cek kepemilikan
            $stmt = $this->pdo->prepare("
                SELECT p.*, k.pemilik_id, u.nama as wisatawan_nama, u.no_hp as wisatawan_hp
                FROM pesanan p 
                JOIN kapal k ON p.kapal_id = k.id 
                JOIN users u ON p.user_id = u.id
                WHERE p.id = ? AND k.pemilik_id = ?
            ");
            $stmt->execute([$pesanan_id, $user_id]);
            $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$pesanan) {
                $_SESSION['flash_error'] = "Pesanan tidak ditemukan atau bukan milik Anda.";
                header("Location: ?page=supir&action=kelolaPesanan");
                exit;
            }
            
            // Cek apakah status reschedule masih 'menunggu'
            if ($pesanan['reschedule_status'] != 'menunggu') {
                $_SESSION['flash_error'] = "Permintaan reschedule sudah diproses sebelumnya.";
                header("Location: ?page=supir&action=kelolaPesanan");
                exit;
            }
            
            $this->pdo->beginTransaction();
            
            require_once __DIR__ . '/../config/fonnte.php';
            
            // Cek kolom yang ada
            $columns = $this->getTableColumns('pesanan');
            
            if ($keputusan == 'setuju') {
                // ==============================================
                // RESCHEDULE DISETUJUI
                // ==============================================
                $sql = "UPDATE pesanan SET ";
                $params = [];
                
                if (in_array('tanggal_berangkat', $columns)) {
                    $sql .= "tanggal_berangkat = ?";
                    $params[] = $pesanan['reschedule_tanggal_baru'];
                }
                
                if (in_array('pelabuhan_tujuan', $columns) && !empty($pesanan['reschedule_rute_baru'])) {
                    $sql .= ", pelabuhan_tujuan = ?";
                    $params[] = $pesanan['reschedule_rute_baru'];
                }
                
                if (in_array('reschedule_status', $columns)) {
                    $sql .= ", reschedule_status = 'disetujui'";
                }
                
                if (in_array('reschedule_tanggal_respon', $columns)) {
                    $sql .= ", reschedule_tanggal_respon = NOW()";
                }
                
                $sql .= " WHERE id = ?";
                $params[] = $pesanan_id;
                
                $stmt = $this->pdo->prepare($sql);
                $stmt->execute($params);
                
                // ================================================================
                // KIRIM NOTIFIKASI KE WISATAWAN
                // ================================================================
                if (!empty($pesanan['wisatawan_hp'])) {
                    $wa_msg = "
✅ *PERUBAHAN JADWAL DISETUJUI* ✅

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

Perubahan jadwal untuk pesanan dengan kode *{$pesanan['kode_pesanan']}* telah DISETUJUI oleh pemilik kapal.

📅 Tanggal Baru: " . date('d/m/Y', strtotime($pesanan['reschedule_tanggal_baru'])) . "
🗺️ Destinasi Baru: {$pesanan['reschedule_rute_baru']}

Silakan cek aplikasi untuk detail lengkap.

Selamat berlibur! 🌊⛵
";
                    sendWhatsApp($pesanan['wisatawan_hp'], $wa_msg);
                }
                
                // Notifikasi aplikasi
                try {
                    $stmt = $this->pdo->prepare("
                        INSERT INTO notifications (user_id, title, message, booking_id, is_read, created_at) 
                        VALUES (?, ?, ?, ?, 0, NOW())
                    ");
                    $title = "✅ Perubahan Jadwal Disetujui";
                    $msg = "Perubahan jadwal untuk pesanan {$pesanan['kode_pesanan']} telah disetujui oleh pemilik kapal.";
                    $stmt->execute([$pesanan['user_id'], $title, $msg, $pesanan_id]);
                } catch (Exception $e) {
                    // Ignore
                }
                
                $_SESSION['flash_success'] = "✅ Perubahan jadwal disetujui!";
                
            } elseif ($keputusan == 'tolak') {
                // ==============================================
                // RESCHEDULE DITOLAK
                // ==============================================
                $sql = "UPDATE pesanan SET ";
                $params = [];
                
                if (in_array('reschedule_status', $columns)) {
                    $sql .= "reschedule_status = 'ditolak'";
                }
                
                if (in_array('reschedule_alasan_penolakan', $columns) && !empty($alasan)) {
                    $sql .= ", reschedule_alasan_penolakan = ?";
                    $params[] = $alasan;
                }
                
                if (in_array('reschedule_tanggal_respon', $columns)) {
                    $sql .= ", reschedule_tanggal_respon = NOW()";
                }
                
                $sql .= " WHERE id = ?";
                $params[] = $pesanan_id;
                
                $stmt = $this->pdo->prepare($sql);
                $stmt->execute($params);
                
                // ================================================================
                // KIRIM NOTIFIKASI KE WISATAWAN
                // ================================================================
                if (!empty($pesanan['wisatawan_hp'])) {
                    $wa_msg = "
❌ *PERUBAHAN JADWAL DITOLAK* ❌

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

Perubahan jadwal untuk pesanan dengan kode *{$pesanan['kode_pesanan']}* telah DITOLAK oleh pemilik kapal.

📝 Alasan: {$alasan}

Silakan hubungi pemilik kapal untuk informasi lebih lanjut.

Terima kasih. 🌊
";
                    sendWhatsApp($pesanan['wisatawan_hp'], $wa_msg);
                }
                
                // Notifikasi aplikasi
                try {
                    $stmt = $this->pdo->prepare("
                        INSERT INTO notifications (user_id, title, message, booking_id, is_read, created_at) 
                        VALUES (?, ?, ?, ?, 0, NOW())
                    ");
                    $title = "❌ Perubahan Jadwal Ditolak";
                    $msg = "Perubahan jadwal untuk pesanan {$pesanan['kode_pesanan']} ditolak oleh pemilik kapal.";
                    $stmt->execute([$pesanan['user_id'], $title, $msg, $pesanan_id]);
                } catch (Exception $e) {
                    // Ignore
                }
                
                $_SESSION['flash_success'] = "✅ Perubahan jadwal ditolak.";
            }
            
            $this->pdo->commit();
            
        } catch (Exception $e) {
            $this->pdo->rollBack();
            error_log("Error konfirmasiReschedule: " . $e->getMessage());
            $_SESSION['flash_error'] = "Gagal memproses: " . $e->getMessage();
        }
        
        header("Location: ?page=supir&action=kelolaPesanan");
        exit;
    }
    
    /**
     * ================================================================
     * UPDATE STATUS PESANAN - DIPERBAIKI SESUAI STRUKTUR TABEL
     * ================================================================
     */
    public function updateStatusPesanan() {
        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
            header("Location: ?page=supir&action=kelolaPesanan");
            exit;
        }
        
        $user_id = $_SESSION['user_id'];
        $pesanan_id = (int)($_POST['pesanan_id'] ?? 0);
        $status = $_POST['status'] ?? '';
        $alasan = trim($_POST['alasan'] ?? '');
        
        if (empty($pesanan_id) || empty($status)) {
            $_SESSION['flash_error'] = "Data tidak lengkap.";
            header("Location: ?page=supir&action=kelolaPesanan");
            exit;
        }
        
        $validStatus = ['pending', 'confirmed', 'completed', 'cancelled'];
        if (!in_array($status, $validStatus)) {
            $_SESSION['flash_error'] = "Status tidak valid.";
            header("Location: ?page=supir&action=kelolaPesanan");
            exit;
        }
        
        try {
            $stmt = $this->pdo->prepare("
                SELECT p.*, k.pemilik_id, u.nama as wisatawan_nama, u.no_hp as wisatawan_hp
                FROM pesanan p 
                JOIN kapal k ON p.kapal_id = k.id 
                JOIN users u ON p.user_id = u.id
                WHERE p.id = ? AND k.pemilik_id = ?
            ");
            $stmt->execute([$pesanan_id, $user_id]);
            $pesanan = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$pesanan) {
                $_SESSION['flash_error'] = "Pesanan tidak ditemukan atau bukan milik Anda.";
                header("Location: ?page=supir&action=kelolaPesanan");
                exit;
            }
            
            // ==============================================
            // CEK STRUKTUR TABEL PESANAN
            // ==============================================
            $columns = $this->getTableColumns('pesanan');
            
            // ==============================================
            // BUILD UPDATE QUERY DINAMIS
            // ==============================================
            $sql = "UPDATE pesanan SET status_pesanan = ?";
            $params = [$status];
            
            // Tambahkan kolom updated_at jika ada
            if (in_array('updated_at', $columns)) {
                $sql .= ", updated_at = NOW()";
            }
            
            // Jika status = confirmed, update tanggal_konfirmasi_pembayaran
            if ($status == 'confirmed') {
                if (in_array('tanggal_konfirmasi_pembayaran', $columns)) {
                    $sql .= ", tanggal_konfirmasi_pembayaran = NOW()";
                }
                // Update status pembayaran menjadi menunggu_konfirmasi jika masih belum_bayar
                if ($pesanan['status_pembayaran'] == 'belum_bayar') {
                    if (in_array('status_pembayaran', $columns)) {
                        $sql .= ", status_pembayaran = 'menunggu_konfirmasi'";
                    }
                }
            }
            
            // Jika status = completed, update tanggal_selesai
            if ($status == 'completed') {
                if (in_array('tanggal_selesai', $columns)) {
                    $sql .= ", tanggal_selesai = NOW()";
                }
            }
            
            // Jika status = cancelled, update tanggal_pembatalan
            if ($status == 'cancelled') {
                if (in_array('tanggal_pembatalan', $columns)) {
                    $sql .= ", tanggal_pembatalan = NOW()";
                }
                if (in_array('status_pembatalan', $columns)) {
                    $sql .= ", status_pembatalan = 'dibatalkan'";
                }
            }
            
            // Tambahkan alasan jika ada (untuk penolakan/pembatalan)
            if (!empty($alasan) && ($status == 'cancelled')) {
                if (in_array('alasan_penolakan', $columns)) {
                    $sql .= ", alasan_penolakan = ?";
                    $params[] = $alasan;
                } elseif (in_array('alasan', $columns)) {
                    $sql .= ", alasan = ?";
                    $params[] = $alasan;
                }
            }
            
            $sql .= " WHERE id = ?";
            $params[] = $pesanan_id;
            
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($params);
            
            // ================================================================
            // KIRIM NOTIFIKASI KE WISATAWAN
            // ================================================================
            $statusText = [
                'pending' => 'Menunggu',
                'confirmed' => 'Dikonfirmasi',
                'completed' => 'Selesai',
                'cancelled' => 'Dibatalkan'
            ];
            
            $statusDisplay = $statusText[$status] ?? ucfirst($status);
            
            try {
                $stmt = $this->pdo->prepare("
                    INSERT INTO notifications (user_id, title, message, booking_id, is_read, created_at) 
                    VALUES (?, ?, ?, ?, 0, NOW())
                ");
                $title = "📋 Status Pesanan Diperbarui";
                $msg = "Pesanan {$pesanan['kode_pesanan']} telah berubah status menjadi {$statusDisplay}.";
                if (!empty($alasan)) {
                    $msg .= " Alasan: {$alasan}";
                }
                $stmt->execute([$pesanan['user_id'], $title, $msg, $pesanan_id]);
            } catch (Exception $e) {
                // Ignore
            }
            
            if (!empty($pesanan['wisatawan_hp'])) {
                $wa_msg = "
🛳️ *STATUS PESANAN DIPERBARUI* 🛳️

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

Status pesanan Anda untuk kapal *{$pesanan['nama_kapal']}* telah diperbarui.

📌 Kode Pesanan: *{$pesanan['kode_pesanan']}*
📌 Status: *{$statusDisplay}*
" . (!empty($alasan) ? "📌 Alasan: {$alasan}" : "") . "

Silakan cek aplikasi untuk informasi lebih lanjut.

Terima kasih. 🌊
";
                $this->sendWhatsAppNotification($pesanan['wisatawan_hp'], $wa_msg);
            }
            
            $_SESSION['flash_success'] = "✅ Status pesanan berhasil diperbarui menjadi {$statusDisplay}!";
            
        } catch (Exception $e) {
            error_log("Update Status Error: " . $e->getMessage());
            $_SESSION['flash_error'] = "❌ Gagal memperbarui status: " . $e->getMessage();
        }
        
        header("Location: ?page=supir&action=kelolaPesanan");
        exit;
    }
    
    /**
     * ================================================================
     * PENCAIRAN DANA (Riwayat Pencairan)
     * ================================================================
     */
    public function pencairanDana() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        $stmt = $this->pdo->prepare("
            SELECT p.*, k.nama_kapal 
            FROM pesanan p 
            JOIN kapal k ON p.kapal_id = k.id 
            WHERE k.pemilik_id = ? 
            AND p.status_pembayaran = 'lunas'
            AND p.status_pencairan = 'cair'
            ORDER BY p.tanggal_pencairan DESC
        ");
        $stmt->execute([$user_id]);
        $riwayat = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $totalDicairkan = array_sum(array_column($riwayat, 'nominal_diterima_supir'));
        
        require_once __DIR__ . '/../views/supir/riwayat_pencairan.php';
    }
    
    /**
     * ================================================================
     * NOTIFIKASI
     * ================================================================
     */
    public function notifikasi() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        $stmt = $this->pdo->prepare("
            SELECT * FROM notifications 
            WHERE user_id = ? 
            ORDER BY created_at DESC
        ");
        $stmt->execute([$user_id]);
        $notifikasi = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        require_once __DIR__ . '/../views/supir/notifikasi.php';
    }
    
    /**
     * ================================================================
     * BACA NOTIFIKASI - Tandai satu notifikasi sebagai dibaca (GET)
     * ================================================================
     */
    public function bacaNotifikasi() {
        $id = (int) ($_GET['id'] ?? 0);
        $user_id = $_SESSION['user_id'];
        
        if ($id > 0) {
            try {
                $stmt = $this->pdo->prepare("
                    UPDATE notifications 
                    SET is_read = 1 
                    WHERE id = ? AND user_id = ?
                ");
                $stmt->execute([$id, $user_id]);
                $_SESSION['flash_success'] = "✅ Notifikasi ditandai sebagai dibaca.";
            } catch (Exception $e) {
                $_SESSION['flash_error'] = "❌ Gagal menandai notifikasi.";
            }
        }
        
        header("Location: ?page=supir&action=notifikasi");
        exit;
    }
    
    /**
     * ================================================================
     * BACA SEMUA NOTIFIKASI - Tandai semua sebagai dibaca (GET)
     * ================================================================
     */
    public function bacaSemuaNotifikasi() {
        $user_id = $_SESSION['user_id'];
        
        try {
            $stmt = $this->pdo->prepare("
                UPDATE notifications 
                SET is_read = 1 
                WHERE user_id = ? AND is_read = 0
            ");
            $stmt->execute([$user_id]);
            $_SESSION['unreadCount'] = 0;
            $_SESSION['flash_success'] = "✅ Semua notifikasi telah ditandai sebagai dibaca.";
        } catch (Exception $e) {
            $_SESSION['flash_error'] = "❌ Gagal menandai notifikasi: " . $e->getMessage();
        }
        
        header("Location: ?page=supir&action=notifikasi");
        exit;
    }
    
    /**
     * ================================================================
     * HAPUS NOTIFIKASI - Hapus notifikasi (GET)
     * ================================================================
     */
    public function hapusNotifikasi() {
        $id = (int) ($_GET['id'] ?? 0);
        $user_id = $_SESSION['user_id'];
        
        if ($id > 0) {
            try {
                $stmt = $this->pdo->prepare("
                    DELETE FROM notifications 
                    WHERE id = ? AND user_id = ?
                ");
                $stmt->execute([$id, $user_id]);
                $_SESSION['flash_success'] = "🗑️ Notifikasi dihapus.";
            } catch (Exception $e) {
                $_SESSION['flash_error'] = "❌ Gagal menghapus notifikasi.";
            }
        }
        
        header("Location: ?page=supir&action=notifikasi");
        exit;
    }
    
    /**
     * ================================================================
     * GET UNREAD COUNT - UNTUK AJAX REAL-TIME NOTIFIKASI
     * ================================================================
     */
    public function getUnreadCount() {
        header('Content-Type: application/json');
        header('Cache-Control: no-cache, must-revalidate');
        
        $user_id = $_SESSION['user_id'] ?? 0;
        $count = 0;
        
        if ($user_id > 0) {
            try {
                $stmt = $this->pdo->prepare("SELECT COUNT(*) as total FROM notifications WHERE user_id = ? AND is_read = 0");
                $stmt->execute([$user_id]);
                $result = $stmt->fetch(PDO::FETCH_ASSOC);
                $count = (int)($result['total'] ?? 0);
                
                $_SESSION['unreadCount'] = $count;
                
            } catch (Exception $e) {
                $count = 0;
            }
        }
        
        echo json_encode(['count' => $count]);
        exit;
    }
    
    /**
     * MARK AS READ - Tandai satu notifikasi sebagai dibaca (AJAX)
     */
    public function markAsRead() {
        // 🔥 TAMBAHKAN DEBUG
        error_log('=== markAsRead called ===');
        error_log('POST: ' . print_r($_POST, true));
        error_log('GET: ' . print_r($_GET, true));
        error_log('SESSION: ' . print_r($_SESSION, true));
        
        header('Content-Type: application/json');
        header('Cache-Control: no-cache, must-revalidate');
        
        // Cek login
        if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'pemilik_kapal') {
            echo json_encode([
                'success' => false, 
                'message' => 'Unauthorized - Silakan login sebagai supir'
            ]);
            exit;
        }
        
        // 🔥 AMBIL ID DARI POST ATAU GET
        $id = isset($_POST['id']) ? (int)$_POST['id'] : (isset($_GET['id']) ? (int)$_GET['id'] : 0);
        $user_id = $_SESSION['user_id'];
        
        if ($id <= 0) {
            echo json_encode([
                'success' => false, 
                'message' => 'ID notifikasi tidak valid'
            ]);
            exit;
        }
        
        try {
            $stmt = $this->pdo->prepare("
                UPDATE notifications 
                SET is_read = 1 
                WHERE id = ? AND user_id = ?
            ");
            $stmt->execute([$id, $user_id]);
            
            // Update unread count di session
            $_SESSION['unreadCount'] = $this->getUnreadCountPrivate($user_id);
            
            echo json_encode([
                'success' => true, 
                'message' => 'Notifikasi ditandai sebagai dibaca'
            ]);
        } catch (Exception $e) {
            error_log('Error markAsRead: ' . $e->getMessage());
            echo json_encode([
                'success' => false, 
                'message' => 'Error: ' . $e->getMessage()
            ]);
        }
        exit;
    }
    
    /**
     * MARK ALL AS READ - Tandai semua notifikasi sebagai dibaca (AJAX)
     * URL: ?page=ajax&action=markAllAsRead
     * Method: POST
     */
    public function markAllAsRead() {
        header('Content-Type: application/json');
        header('Cache-Control: no-cache, must-revalidate');
        
        // Cek login
        if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'pemilik_kapal') {
            echo json_encode([
                'success' => false, 
                'message' => 'Unauthorized - Silakan login sebagai supir'
            ]);
            exit;
        }
        
        $user_id = $_SESSION['user_id'];
        
        try {
            $stmt = $this->pdo->prepare("
                UPDATE notifications 
                SET is_read = 1 
                WHERE user_id = ? AND is_read = 0
            ");
            $stmt->execute([$user_id]);
            
            // Update unread count di session
            $_SESSION['unreadCount'] = 0;
            
            echo json_encode([
                'success' => true, 
                'message' => 'Semua notifikasi ditandai sebagai dibaca'
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false, 
                'message' => 'Error: ' . $e->getMessage()
            ]);
        }
        exit;
    }
    
    /**
     * DELETE NOTIFICATION - Hapus notifikasi (AJAX)
     * URL: ?page=ajax&action=deleteNotification
     * Method: POST
     */
    public function deleteNotification() {
        header('Content-Type: application/json');
        header('Cache-Control: no-cache, must-revalidate');
        
        // Cek login
        if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'pemilik_kapal') {
            echo json_encode([
                'success' => false, 
                'message' => 'Unauthorized - Silakan login sebagai supir'
            ]);
            exit;
        }
        
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $user_id = $_SESSION['user_id'];
        
        if ($id <= 0) {
            echo json_encode([
                'success' => false, 
                'message' => 'ID notifikasi tidak valid'
            ]);
            exit;
        }
        
        try {
            $stmt = $this->pdo->prepare("
                DELETE FROM notifications 
                WHERE id = ? AND user_id = ?
            ");
            $stmt->execute([$id, $user_id]);
            
            // Update unread count di session
            $_SESSION['unreadCount'] = $this->getUnreadCountPrivate($user_id);
            
            echo json_encode([
                'success' => true, 
                'message' => 'Notifikasi dihapus'
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false, 
                'message' => 'Error: ' . $e->getMessage()
            ]);
        }
        exit;
    }
    
    /**
     * ================================================================
     * SHARED TRIP
     * ================================================================
     */
    public function sharedTrip() {
        $user_id = $_SESSION['user_id'];
        $unreadCount = $this->getUnreadCountPrivate($user_id);
        
        $stmt = $this->pdo->prepare("
            SELECT st.*, k.nama_kapal, 
                   (SELECT COUNT(*) FROM shared_trip_participants WHERE trip_id = st.id) as peserta
            FROM shared_trips st 
            JOIN kapal k ON st.kapal_id = k.id 
            WHERE k.pemilik_id = ? 
            ORDER BY st.created_at DESC
        ");
        $stmt->execute([$user_id]);
        $sharedTrips = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        require_once __DIR__ . '/../views/supir/shared_trip.php';
    }
}
?>