<?php
/**
 * booking.php - Halaman Booking Kapal untuk Wisatawan
 * DIPERBAIKI - Rute otomatis terpilih sesuai pencarian, tanpa dropdown
 * DITAMBAHKAN - Filter Pelabuhan Asal
 * DITAMBAHKAN - Waktu Jemput dan Waktu Selesai untuk deteksi keterlambatan
 * DITAMBAHKAN - Pilihan Pembayaran DP, Full, atau Bayar di Tempat
 */
$activeMenu = 'booking';
$pageTitle = 'Booking Kapal - Wisatawan';
include __DIR__ . '/../layouts/header.php';

// ============================================
// FUNGSI AUTO-GENERATE RUTE
// ============================================
function autoGenerateRoutes($kapalId, $pdo) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM kapal_rute WHERE kapal_id = ?");
    $stmt->execute([$kapalId]);
    $count = $stmt->fetchColumn();
    
    if ($count > 0) {
        return true;
    }
    
    $defaultRoutes = [
        ['asal' => 'Parapat', 'tujuan' => 'Tomok', 'harga' => 2500000],
        ['asal' => 'Parapat', 'tujuan' => 'Tuktuk Siadong', 'harga' => 2000000],
        ['asal' => 'Parapat', 'tujuan' => 'Situmurun', 'harga' => 3000000],
        ['asal' => 'Parapat', 'tujuan' => 'Balige', 'harga' => 3500000],
        ['asal' => 'Parapat', 'tujuan' => 'Pangururan', 'harga' => 4000000],
        ['asal' => 'Parapat', 'tujuan' => 'Ambarita', 'harga' => 2800000],
        ['asal' => 'Parapat', 'tujuan' => 'Simanindo', 'harga' => 3200000],
    ];
    
    try {
        $pdo->beginTransaction();
        
        foreach ($defaultRoutes as $route) {
            $stmt = $pdo->prepare("
                INSERT INTO kapal_rute (kapal_id, asal, tujuan, harga_jual) 
                VALUES (?, ?, ?, ?)
            ");
            $stmt->execute([
                $kapalId, 
                $route['asal'], 
                $route['tujuan'], 
                $route['harga']
            ]);
        }
        
        $pdo->commit();
        return true;
    } catch (Exception $e) {
        $pdo->rollBack();
        return false;
    }
}

// ============================================
// AMBIL DATA KAPAL DENGAN RUTE
// ============================================
$userName = $_SESSION['nama'] ?? 'Pengguna';
$userEmail = $_SESSION['email'] ?? '';
$userNoHp = $_SESSION['no_hp'] ?? '';

$tanggalFilter = isset($_GET['tanggal']) ? $_GET['tanggal'] : date('Y-m-d', strtotime('+1 day'));
$searchTerm = isset($_GET['search']) ? trim($_GET['search']) : '';
$pelabuhanFilter = isset($_GET['pelabuhan']) ? trim($_GET['pelabuhan']) : '';
$tomorrow = date('Y-m-d', strtotime('+1 day'));
$maxDate = date('Y-m-d', strtotime('+30 days'));

// ============================================
// AMBIL DAFTAR PELABUHAN UNTUK FILTER
// ============================================
$pelabuhanList = [];
try {
    $stmt = $this->pdo->prepare("
        SELECT DISTINCT kr.asal 
        FROM kapal_rute kr
        JOIN kapal k ON kr.kapal_id = k.id
        WHERE k.status_verifikasi = 'verified' AND k.status_aktif = 1
        ORDER BY kr.asal ASC
    ");
    $stmt->execute();
    $pelabuhanList = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (Exception $e) {
    $pelabuhanList = [];
}

// Jika tidak ada pelabuhan dari database, gunakan default
if (empty($pelabuhanList)) {
    $pelabuhanList = ['Parapat', 'Onanrunggu', 'Ambarita', 'Tomok', 'Tuktuk'];
}

// ============================================
// AUTO-INSERT RUTE UNTUK SEMUA KAPAL YANG BELUM PUNYA RUTE
// ============================================
$totalAutoInsert = 0;
try {
    $stmt = $this->pdo->prepare("
        SELECT k.id, k.nama_kapal 
        FROM kapal k 
        WHERE k.status_verifikasi = 'verified' 
        AND k.status_aktif = 1
        AND NOT EXISTS (
            SELECT 1 FROM kapal_rute kr WHERE kr.kapal_id = k.id
        )
    ");
    $stmt->execute();
    $kapalTanpaRute = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($kapalTanpaRute as $kapal) {
        if (autoGenerateRoutes($kapal['id'], $this->pdo)) {
            $totalAutoInsert++;
        }
    }
    
    if ($totalAutoInsert > 0) {
        $_SESSION['flash_success'] = "✅ Berhasil membuat rute otomatis untuk $totalAutoInsert kapal!";
    }
} catch (Exception $e) {
    // Ignore error
}

// ============================================
// QUERY AMBIL KAPAL DENGAN RUTE
// ============================================
$sql = "
    SELECT 
        k.*,
        (SELECT COUNT(*) FROM kapal_rute WHERE kapal_id = k.id) as total_rute,
        (SELECT MIN(harga_jual) FROM kapal_rute WHERE kapal_id = k.id) as harga_termurah,
        (SELECT MAX(harga_jual) FROM kapal_rute WHERE kapal_id = k.id) as harga_termahal,
        (SELECT GROUP_CONCAT(DISTINCT CONCAT(asal, ' → ', tujuan) SEPARATOR ' | ') FROM kapal_rute WHERE kapal_id = k.id) as daftar_rute,
        (SELECT GROUP_CONCAT(DISTINCT tujuan SEPARATOR ' | ') FROM kapal_rute WHERE kapal_id = k.id) as daftar_tujuan,
        (SELECT GROUP_CONCAT(DISTINCT asal SEPARATOR ' | ') FROM kapal_rute WHERE kapal_id = k.id) as daftar_asal
    FROM kapal k 
    WHERE k.status_verifikasi = 'verified' AND k.status_aktif = 1
";

// Filter pencarian berdasarkan tujuan wisata
$conditions = [];
$params = [];

if (!empty($searchTerm)) {
    $conditions[] = "(
        k.nama_kapal LIKE ? OR 
        k.pelabuhan_asal LIKE ? OR 
        k.jenis LIKE ? OR
        k.fasilitas LIKE ? OR
        k.deskripsi LIKE ? OR
        EXISTS (
            SELECT 1 FROM kapal_rute kr 
            WHERE kr.kapal_id = k.id 
            AND (kr.tujuan LIKE ? OR kr.asal LIKE ?)
        )
    )";
    $searchPattern = '%' . $searchTerm . '%';
    $params = array_fill(0, 7, $searchPattern);
}

// 🔥 FILTER PELABUHAN ASAL
if (!empty($pelabuhanFilter)) {
    $conditions[] = "EXISTS (
        SELECT 1 FROM kapal_rute kr 
        WHERE kr.kapal_id = k.id 
        AND kr.asal LIKE ?
    )";
    $params[] = '%' . $pelabuhanFilter . '%';
}

if (!empty($conditions)) {
    $sql .= " AND " . implode(" AND ", $conditions);
}

$sql .= " GROUP BY k.id ORDER BY k.created_at DESC";

$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);

$kapalList = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ============================================
// AMBIL RUTE PER KAPAL
// ============================================
$rutePerKapal = [];
foreach ($kapalList as $kapal) {
    try {
        $stmt = $this->pdo->prepare("
            SELECT id, asal, tujuan, harga_jual, created_at 
            FROM kapal_rute 
            WHERE kapal_id = ? 
            ORDER BY harga_jual ASC
        ");
        $stmt->execute([$kapal['id']]);
        $rutePerKapal[$kapal['id']] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        $rutePerKapal[$kapal['id']] = [];
    }
}

// ============================================
// TENTUKAN RUTE YANG DIPILIH BERDASARKAN PENCARIAN
// ============================================
$selectedRouteId = null;
$selectedRouteTujuan = '';
$selectedRouteData = null;
$selectedRouteAsal = '';

if (!empty($searchTerm)) {
    foreach ($rutePerKapal as $kapalId => $routes) {
        foreach ($routes as $route) {
            if (stripos($route['tujuan'], $searchTerm) !== false) {
                $selectedRouteId = $route['id'];
                $selectedRouteTujuan = $route['tujuan'];
                $selectedRouteData = $route;
                $selectedRouteAsal = $route['asal'];
                break 2;
            }
        }
    }
}

// ============================================
// AMBIL SHARED TRIPS
// ============================================
$sharedTrips = [];
try {
    $stmt = $this->pdo->prepare("
        SELECT st.*, k.nama_kapal, k.pelabuhan_asal, 
               (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 st.tanggal_berangkat >= ? 
        AND st.kuota > (SELECT COUNT(*) FROM shared_trip_participants WHERE trip_id = st.id)
        ORDER BY st.tanggal_berangkat ASC
        LIMIT 10
    ");
    $stmt->execute([date('Y-m-d')]);
    $sharedTrips = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $sharedTrips = [];
}

$totalCount = count($kapalList);
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">

<script>
function autoGenerateRute(kapalId, btnElement) {
    if (!confirm('Kapal ini belum memiliki rute. Buatkan rute otomatis sekarang?\n\nRute yang akan dibuat:\n• Parapat → Tomok (Rp 2.500.000)\n• Parapat → Tuktuk Siadong (Rp 2.000.000)\n• Parapat → Situmurun (Rp 3.000.000)\n• Parapat → Balige (Rp 3.500.000)\n• Parapat → Pangururan (Rp 4.000.000)\n• Parapat → Ambarita (Rp 2.800.000)\n• Parapat → Simanindo (Rp 3.200.000)')) {
        return;
    }
    
    btnElement.disabled = true;
    btnElement.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Membuat...';
    
    const formData = new FormData();
    formData.append('kapal_id', kapalId);
    formData.append('action', 'auto_generate_rute');
    
    fetch('<?= $_SERVER['PHP_SELF'] ?>?page=wisatawan&action=booking', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(html => {
        alert('✅ Rute berhasil dibuat! Halaman akan di-refresh.');
        location.reload();
    })
    .catch(error => {
        alert('❌ Terjadi kesalahan: ' + error);
        btnElement.disabled = false;
        btnElement.innerHTML = '<i class="fas fa-plus"></i> Buat Rute Otomatis';
    });
}

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'auto_generate_rute') {
    $kapalId = isset($_POST['kapal_id']) ? intval($_POST['kapal_id']) : 0;
    if ($kapalId > 0) {
        if (autoGenerateRoutes($kapalId, $this->pdo)) {
            echo "// Auto-generate berhasil untuk kapal ID: $kapalId";
        }
    }
    exit;
}
?>
</script>

<div class="booking-wrapper">
    <?php include __DIR__ . '/../layouts/sidebar_wisatawan.php'; ?>

    <main class="main-content">
        <div class="content-header">
            <div>
                <h1>🛥️ Booking Kapal</h1>
                <p>Cari dan pesan kapal wisata sesuai kebutuhan Anda.</p>
                <?php if(!empty($searchTerm) && !empty($selectedRouteTujuan)): ?>
                    <div class="search-indicator">
                        <i class="fas fa-flag-checkered" style="color:#2b6cb0;"></i>
                        <strong>Destinasi yang dicari:</strong> <?= htmlspecialchars($searchTerm) ?>
                        <span style="color:#2b6cb0; margin-left:0.5rem;">
                            <i class="fas fa-arrow-right"></i> Rute otomatis menuju <strong><?= htmlspecialchars($selectedRouteTujuan) ?></strong>
                        </span>
                        <?php if(!empty($selectedRouteAsal)): ?>
                            <span style="color:#065f46; margin-left:0.5rem; background:#d1fae5; padding:0.2rem 0.8rem; border-radius:12px;">
                                <i class="fas fa-anchor"></i> Berangkat dari <strong><?= htmlspecialchars($selectedRouteAsal) ?></strong>
                            </span>
                        <?php endif; ?>
                        <?php if(!empty($pelabuhanFilter)): ?>
                            <span style="color:#1e40af; margin-left:0.5rem; background:#dbeafe; padding:0.2rem 0.8rem; border-radius:12px;">
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <?php if(isset($_SESSION['flash_success'])): ?>
            <div class="alert alert-success">
                <span class="alert-icon">✅</span>
                <?= $_SESSION['flash_success'] ?>
                <button class="alert-close" onclick="this.parentElement.remove()">✕</button>
            </div>
            <?php unset($_SESSION['flash_success']); ?>
        <?php endif; ?>
        <?php if(isset($_SESSION['flash_error'])): ?>
            <div class="alert alert-danger">
                <span class="alert-icon">❌</span>
                <?= $_SESSION['flash_error'] ?>
                <button class="alert-close" onclick="this.parentElement.remove()">✕</button>
            </div>
            <?php unset($_SESSION['flash_error']); ?>
        <?php endif; ?>

        <!-- Filter & Pencarian -->
        <div class="filter-section">
            <form method="GET" action="" class="filter-form" id="filterForm">
                <input type="hidden" name="page" value="wisatawan">
                <input type="hidden" name="action" value="booking">
                
                <div class="filter-row">
                    <div class="filter-group">
                        <label> 📅 Tanggal Keberangkatan</label>
                        <input type="date" name="tanggal" class="filter-input" 
                               id="filterTanggal"
                               min="<?= $tomorrow ?>" max="<?= $maxDate ?>"
                               value="<?= htmlspecialchars($tanggalFilter) ?>">
                    </div>
                    <div class="filter-group" style="flex:2;">
                        <label> 🔍 Cari Destinasi Wisata</label>
                        <input type="text" name="search" class="filter-input"  
                               value="<?= htmlspecialchars($searchTerm) ?>"
                               id="searchInput" placeholder="Cari destinasi...">
                    </div>
                    <!-- ========================================== -->
                    <!-- 🔥 FILTER PELABUHAN ASAL -->
                    <!-- ========================================== -->
                    <div class="filter-group" style="flex:1.5;">
                        <label> ⚓ Pelabuhan Asal</label>
                        <select name="pelabuhan" class="filter-input" id="pelabuhanFilter">
                            <option value="">Semua Pelabuhan</option>
                            <?php foreach($pelabuhanList as $pelabuhan): ?>
                                <option value="<?= htmlspecialchars($pelabuhan) ?>" 
                                    <?= ($pelabuhanFilter == $pelabuhan) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($pelabuhan) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="filter-group" style="flex:0.5;">
                        <label>&nbsp;</label>
                        <div style="display:flex; gap:0.5rem; flex-wrap:wrap;">
                            <button type="submit" class="btn btn-primary" id="btnCari">
                                <i class="fas fa-search"></i> Cari
                            </button>
                            <?php if(!empty($searchTerm) || isset($_GET['tanggal']) || !empty($pelabuhanFilter)): ?>
                                <a href="?page=wisatawan&action=booking" class="btn btn-secondary">
                                    <i class="fas fa-undo"></i> Reset
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div class="filter-result-info">
                    <i class="fas fa-info-circle"></i> 
                    Menampilkan <strong><?= $totalCount ?></strong> kapal 
                    <?php if(!empty($searchTerm)): ?>
                        dengan destinasi wisata "<strong><?= htmlspecialchars($searchTerm) ?></strong>"
                    <?php endif; ?>
                    <?php if(!empty($pelabuhanFilter)): ?>
                        dari pelabuhan "<strong><?= htmlspecialchars($pelabuhanFilter) ?></strong>"
                    <?php endif; ?>
                    untuk tanggal <strong><?= date('d/m/Y', strtotime($tanggalFilter)) ?></strong>
                    
                    <?php if(isset($totalAutoInsert) && $totalAutoInsert > 0): ?>
                        <span style="color: #065f46; background: #d1fae5; padding: 0.2rem 0.8rem; border-radius: 12px; margin-left: 0.5rem;">
                             +<?= $totalAutoInsert ?> rute baru dibuat otomatis
                        </span>
                    <?php endif; ?>
                    
                    <?php if(!empty($searchTerm) && !empty($selectedRouteTujuan)): ?>
                        <span style="color: #1e40af; background: #dbeafe; padding: 0.2rem 0.8rem; border-radius: 12px; margin-left: 0.5rem;">
                             Rute otomatis: <strong><?= htmlspecialchars($selectedRouteTujuan) ?></strong>
                        </span>
                    <?php endif; ?>
                    
                    <?php if(!empty($selectedRouteAsal)): ?>
                        <span style="color: #065f46; background: #d1fae5; padding: 0.2rem 0.8rem; border-radius: 12px;">
                            <i class="fas fa-anchor"></i> Pelabuhan: <strong><?= htmlspecialchars($selectedRouteAsal) ?></strong>
                        </span>
                    <?php endif; ?>
                </div>
            </form>
        </div>

        <!-- Shared Trip Section -->
        <?php if(!empty($sharedTrips)): ?>
        <div class="shared-trip-section">
            <h3> 🤝 Shared Trip (Berbagi Kapal)</h3>
            <p>Gabung dengan wisatawan lain untuk harga lebih hemat!</p>
            <div class="shared-trip-grid">
                <?php foreach($sharedTrips as $trip): ?>
                    <div class="shared-trip-card">
                        <div class="trip-header">
                            <span class="trip-badge">SHARED</span>
                            <span class="trip-price">Rp <?= number_format($trip['harga_per_orang'] ?? 0, 0, ',', '.') ?>/org</span>
                        </div>
                        <div class="trip-body">
                            <h4> ⛵ <?= htmlspecialchars($trip['nama_kapal']) ?></h4>
                            <p>📍 <?= htmlspecialchars($trip['pelabuhan_asal'] ?? 'Parapat') ?></p>
                            <p>📅 <?= date('d/m/Y', strtotime($trip['tanggal_berangkat'])) ?></p>
                            <p> Kuota tersisa: <strong><?= ($trip['kuota'] ?? 0) - ($trip['peserta'] ?? 0) ?></strong> orang</p>
                        </div>
                        <div class="trip-footer">
                            <button class="btn btn-success btn-sm btn-shared" 
                                    data-trip-id="<?= $trip['id'] ?>"
                                    data-kapal-id="<?= $trip['kapal_id'] ?>"
                                    data-harga="<?= $trip['harga_per_orang'] ?? 0 ?>"
                                    data-tanggal="<?= $trip['tanggal_berangkat'] ?>"
                                    data-kapal="<?= htmlspecialchars($trip['nama_kapal']) ?>">
                                 🤝 Gabung Trip
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Daftar Kapal -->
        <div class="kapal-section">
            <div class="section-header">
                <h3> ⛵ Kapal Tersedia</h3>
                <span class="kapal-count"><?= $totalCount ?> kapal</span>
                <?php if(!empty($pelabuhanFilter)): ?>
                    <span style="font-size:0.8rem; color:#2b6cb0; background:#dbeafe; padding:0.2rem 0.8rem; border-radius:12px;">
                        <i class="fas fa-filter"></i> Pelabuhan: <?= htmlspecialchars($pelabuhanFilter) ?>
                    </span>
                <?php endif; ?>
            </div>

            <?php if(empty($kapalList)): ?>
                <div class="empty-state">
                    <div class="empty-icon">🚫</div>
                    <p> Belum ada kapal yang tersedia.</p>
                    <?php if(!empty($searchTerm)): ?>
                        <p>Tidak ditemukan kapal dengan destinasi "<strong><?= htmlspecialchars($searchTerm) ?></strong>"</p>
                    <?php endif; ?>
                    <?php if(!empty($pelabuhanFilter)): ?>
                        <p>di pelabuhan "<strong><?= htmlspecialchars($pelabuhanFilter) ?></strong>"</p>
                    <?php endif; ?>
                    <p>Silakan coba lagi nanti atau hubungi admin.</p>
                </div>
            <?php else: ?>
                <div class="kapal-grid">
                    <?php foreach($kapalList as $kapal): 
                        $routes = $rutePerKapal[$kapal['id']] ?? [];
                        $hargaTermurah = $kapal['harga_termurah'] ?? 0;
                        $totalRute = $kapal['total_rute'] ?? 0;
                        $daftarTujuan = $kapal['daftar_tujuan'] ?? '';
                        $daftarAsal = $kapal['daftar_asal'] ?? '';
                        
                        $hasMatchingRoute = false;
                        $matchingRouteId = null;
                        $matchingRouteData = null;
                        $matchingRouteAsal = '';
                        if (!empty($searchTerm)) {
                            foreach ($routes as $route) {
                                if (stripos($route['tujuan'], $searchTerm) !== false) {
                                    $hasMatchingRoute = true;
                                    $matchingRouteId = $route['id'];
                                    $matchingRouteData = $route;
                                    $matchingRouteAsal = $route['asal'];
                                    break;
                                }
                            }
                        }
                    ?>
                        <div class="kapal-card <?= $hasMatchingRoute ? 'has-matching-route' : '' ?>" id="kapal-<?= $kapal['id'] ?>">
                            <?php if($hasMatchingRoute): ?>
                                <div class="matching-badge">
                                    <i class="fas fa-check-circle"></i> Cocok dengan "<?= htmlspecialchars($searchTerm) ?>"
                                </div>
                            <?php endif; ?>
                            
                            <div class="kapal-image">
                                <?php if(!empty($kapal['foto'])): ?>
                                    <img src="/reservasi-kapal-wisata/uploads/kapal/<?= $kapal['foto'] ?>" 
                                         alt="<?= htmlspecialchars($kapal['nama_kapal']) ?>"
                                         onerror="this.src='https://via.placeholder.com/300x200?text=Kapal'">
                                <?php else: ?>
                                    <div class="kapal-image-placeholder">
                                        <span>⛵</span>
                                    </div>
                                <?php endif; ?>
                                <span class="kapal-type"><?= ucfirst($kapal['jenis'] ?? 'Kapal') ?></span>
                                <span class="status-available"> ✅ TERSEDIA</span>
                            </div>
                            <div class="kapal-body">
                                <h4><?= htmlspecialchars($kapal['nama_kapal']) ?></h4>
                                <div class="kapal-meta">
                                    <span class="meta-item">
                                        <i class="fas fa-users"></i> <?= $kapal['kapasitas'] ?? 0 ?> orang
                                    </span>
                                    <span class="meta-item">
                                        <i class="fas fa-map-marker-alt"></i> <?= htmlspecialchars($kapal['pelabuhan_asal'] ?? 'Parapat') ?>
                                    </span>
                                    <span class="meta-item">
                                        <i class="fas fa-tag"></i> <?= ucfirst($kapal['jenis'] ?? '-') ?>
                                    </span>
                                </div>
                                
                                <?php if(!empty($kapal['fasilitas'])): ?>
                                    <div class="kapal-fasilitas">
                                        <i class="fas fa-concierge-bell"></i> <?= htmlspecialchars($kapal['fasilitas']) ?>
                                    </div>
                                <?php endif; ?>

                                <?php if(!empty($daftarTujuan)): ?>
                                    <div class="kapal-tujuan">
                                        <span class="tujuan-label"><i class="fas fa-flag-checkered"></i> Destinasi Wisata:</span>
                                        <?php 
                                        $tujuanArray = explode(' | ', $daftarTujuan);
                                        foreach($tujuanArray as $tujuan): 
                                            $isMatch = !empty($searchTerm) && stripos($tujuan, $searchTerm) !== false;
                                        ?>
                                            <span class="tujuan-tag <?= $isMatch ? 'tujuan-match' : '' ?>">
                                                <?= htmlspecialchars($tujuan) ?>
                                                <?php if($isMatch): ?>
                                                    <i class="fas fa-check-circle" style="color:#22c55e; font-size:0.6rem;"></i>
                                                <?php endif; ?>
                                            </span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>

                                <?php if(!empty($daftarAsal)): ?>
                                    <div class="kapal-pelabuhan">
                                        <span class="pelabuhan-label"><i class="fas fa-anchor"></i> Pelabuhan Asal:</span>
                                        <?php 
                                        $asalArray = explode(' | ', $daftarAsal);
                                        $asalArray = array_unique($asalArray);
                                        foreach($asalArray as $asal): 
                                            $isMatch = !empty($pelabuhanFilter) && stripos($asal, $pelabuhanFilter) !== false;
                                        ?>
                                            <span class="pelabuhan-tag <?= $isMatch ? 'pelabuhan-match' : '' ?>">
                                                <?= htmlspecialchars($asal) ?>
                                                <?php if($isMatch): ?>
                                                    <i class="fas fa-check-circle" style="color:#22c55e; font-size:0.6rem;"></i>
                                                <?php endif; ?>
                                            </span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>

                                <?php if($totalRute > 0): ?>
                                    <div class="kapal-rute-info">
                                        <span class="rute-count"><i class="fas fa-route"></i> <?= $totalRute ?> rute tersedia</span>
                                        <?php if($hargaTermurah > 0): ?>
                                            <span class="rute-price">Mulai Rp <?= number_format($hargaTermurah, 0, ',', '.') ?></span>
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="kapal-rute-info" style="background: #fef3c7; color: #92400e; flex-wrap: wrap; gap: 0.5rem; align-items: center;">
                                        <span><i class="fas fa-exclamation-triangle"></i> Belum ada rute</span>
                                        <button onclick="autoGenerateRute(<?= $kapal['id'] ?>, this)" 
                                                class="btn btn-sm" 
                                                style="background: #f59e0b; color: #fff; padding: 0.2rem 0.8rem; border: none; border-radius: 4px; font-size: 0.7rem; cursor: pointer;">
                                            <i class="fas fa-plus"></i> Buat Rute Otomatis
                                        </button>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="kapal-footer">
                                <div class="price-tag">
                                    <?php if($totalRute > 0 && $hargaTermurah > 0): ?>
                                        Rp <?= number_format($hargaTermurah, 0, ',', '.') ?>
                                        <span class="price-label">/ perjalanan</span>
                                    <?php else: ?>
                                        <span class="price-label" style="color: #92400e;">🚫 Rute belum tersedia</span>
                                    <?php endif; ?>
                                </div>
                                <button class="btn btn-primary btn-sm btn-pesan <?= $hasMatchingRoute ? 'btn-pesan-match' : '' ?>" 
                                        data-kapal-id="<?= $kapal['id'] ?>"
                                        data-kapal-nama="<?= htmlspecialchars($kapal['nama_kapal']) ?>"
                                        data-kapasitas="<?= $kapal['kapasitas'] ?? 0 ?>"
                                        data-routes='<?= json_encode($routes) ?>'
                                        data-tanggal="<?= $tanggalFilter ?>"
                                        data-total-rute="<?= $totalRute ?>"
                                        data-matching-route="<?= $matchingRouteId ?>"
                                        data-matching-route-data='<?= json_encode($matchingRouteData) ?>'
                                        data-matching-route-asal="<?= htmlspecialchars($matchingRouteAsal) ?>"
                                        data-search-term="<?= htmlspecialchars($searchTerm) ?>"
                                        <?= ($totalRute == 0) ? 'disabled style="opacity:0.5;cursor:not-allowed;"' : '' ?>>
                                    <i class="fas fa-pen"></i> 
                                    <?= ($totalRute > 0) ? ($hasMatchingRoute ? 'Pesan Ke ' . htmlspecialchars($searchTerm) : 'Pesan Sekarang') : 'Rute Kosong' ?>
                                </button>
                            </div>
                            <?php if($totalRute == 0): ?>
                                <div class="kapal-warning">
                                    <span> ⚠️ Belum ada rute</span>
                                    <button onclick="autoGenerateRute(<?= $kapal['id'] ?>, this)" 
                                            class="btn btn-sm" 
                                            style="background: #f59e0b; color: #fff; padding: 0.2rem 0.8rem; border: none; border-radius: 4px; font-size: 0.7rem; cursor: pointer;">
                                        <i class="fas fa-plus"></i> Buat Rute Sekarang
                                    </button>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </main>
</div>

<!-- ========================================== -->
<!-- MODAL BOOKING - TANPA DROPDOWN RUTE -->
<!-- DITAMBAHKAN - Waktu Jemput & Waktu Selesai -->
<!-- DITAMBAHKAN - Pilihan Pembayaran DP, Full, atau Bayar di Tempat -->
<!-- ========================================== -->
<div class="modal-overlay" id="bookingModal">
    <div class="modal">
        <div class="modal-header">
            <h3>📝 Form Booking Kapal</h3>
            <button class="modal-close" onclick="closeModal()">&times;</button>
        </div>
        <form method="POST" action="?page=wisatawan&action=prosesBooking" class="booking-form" id="bookingForm">
            <input type="hidden" name="kapal_id" id="bookingKapalId" value="">
            <input type="hidden" name="durasi" value="1">
            <input type="hidden" name="tipe" id="bookingTipe" value="private">
            <input type="hidden" name="trip_id" id="bookingTripId" value="0">
            <input type="hidden" name="tanggal" id="bookingTanggalHidden" value="">
            <input type="hidden" name="harga_total" id="bookingHargaTotal" value="0">
            <input type="hidden" name="jenis_pembayaran" id="jenisPembayaranHidden" value="full">
            
            <!-- RUTE DI HIDDEN (OTOMATIS TERPILIH) -->
            <input type="hidden" name="route_id" id="bookingRouteId" value="">
            <input type="hidden" name="route_harga" id="bookingRouteHarga" value="0">
            <input type="hidden" name="route_tujuan" id="bookingRouteTujuan" value="">
            <input type="hidden" name="route_asal" id="bookingRouteAsal" value="">

            <!-- Informasi Kapal -->
            <div class="form-section">
                <h4>⛵ Kapal yang Dipesan</h4>
                <div class="selected-ship" id="selectedShipInfo">
                    <span id="selectedShipName">-</span>
                    <span id="selectedShipCapacity">Kapasitas: - orang</span>
                </div>
            </div>

            <!-- ========================================== -->
            <!-- RUTE - TANPA DROPDOWN, LANGSUNG OTOMATIS -->
            <!-- ========================================== -->
            <div class="form-section">
                <h4>🗺️ Rute Perjalanan</h4>
                <div class="form-group">
                    <div class="route-display" id="selectedRouteDisplay">
                        <div class="route-info-box" id="routeInfoBox">
                            <div class="route-icon">
                                <i class="fas fa-route"></i>
                            </div>
                            <div class="route-details">
                                <div class="route-label">Rute yang akan dipesan:</div>
                                <div class="route-text" id="displayRouteText">
                                    <span style="color: #a0aec0;">Belum ada rute dipilih</span>
                                </div>
                                <div class="route-price" id="displayRoutePrice">
                                    <span style="color: #a0aec0;">Harga: -</span>
                                </div>
                                <div class="route-pelabuhan" id="displayRoutePelabuhan" style="margin-top:0.2rem;">
                                    <span style="color: #a0aec0; font-size:0.85rem;">
                                        <i class="fas fa-anchor"></i> Pelabuhan Asal: <span id="displayPelabuhanAsal">-</span>
                                    </span>
                                </div>
                                <div class="route-match-info" id="routeMatchInfo" style="display: none;">
                                    <i class="fas fa-check-circle"></i> 
                                    <strong> ✅ Sesuai dengan destinasi yang Anda cari: <span id="routeMatchDestinasi"></span></strong>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="route-warning" id="routeWarning" style="display: none;">
                        <i class="fas fa-exclamation-triangle"></i>
                        <span>
                             ⚠️ Kapal ini belum memiliki rute ke destinasi yang Anda cari. 
                            <br><small>Silakan pilih kapal lain atau hubungi admin.</small>
                        </span>
                    </div>
                </div>
            </div>

            <!-- ========================================== -->
            <!-- TANGGAL KEBERANGKATAN -->
            <!-- ========================================== -->
            <div class="form-group">
                <label> 📅 Tanggal Keberangkatan <span class="required">*</span></label>
                <input type="date" name="tanggal_berangkat" id="bookingTanggal" 
                       class="form-input" 
                       min="<?= date('Y-m-d', strtotime('+1 day')) ?>" 
                       max="<?= date('Y-m-d', strtotime('+30 days')) ?>"
                       required>
            </div>

            <!-- ========================================== -->
            <!-- 🔥 WAKTU JEMPUT - FITUR BARU -->
            <!-- ========================================== -->
            <div class="form-group">
                <label> 🕐 Waktu Jemput <span class="required">*</span></label>
                <input type="time" name="waktu_jemput" id="bookingWaktuJemput" 
                       class="form-input" 
                       value="08:00"
                       required>
                <small class="form-hint">
                    <i class="fas fa-info-circle"></i> 
                    Waktu jemput yang disepakati. Jika supir terlambat lebih dari 2 jam, Anda berhak mengajukan claim.
                </small>
            </div>

            <!-- ========================================== -->
            <!-- 🔥 WAKTU SELESAI - FITUR BARU -->
            <!-- ========================================== -->
            <div class="form-group">
                <label> 🏁 Waktu Selesai (Perkiraan) <span class="required">*</span></label>
                <input type="time" name="waktu_selesai" id="bookingWaktuSelesai" 
                       class="form-input" 
                       value="17:00"
                       required>
                <small class="form-hint">
                    <i class="fas fa-info-circle"></i> 
                    Perkiraan waktu selesai perjalanan. Akan digunakan untuk tracking durasi perjalanan.
                </small>
            </div>

            <!-- Jumlah Penumpang -->
            <div class="form-group">
                <label> 👥 Jumlah Penumpang</label>
                <input type="number" name="jumlah_penumpang" id="bookingJumlahPenumpang" 
                       class="form-input" min="1" max="54" value="1" required>
                <small class="form-hint" id="kapasitasHint">Maksimal 54 orang. Harga TETAP per rute (tidak tergantung jumlah penumpang).</small>
            </div>

            <!-- ========================================== -->
            <!-- 🔥 PILIHAN PEMBAYARAN - DP, FULL, atau BAYAR DI TEMPAT -->
            <!-- ========================================== -->
            <!-- ========================================== -->
<!-- 🔥 PILIHAN PEMBAYARAN - DENGAN SALDO -->
<!-- ========================================== -->
<div class="form-section">
    <h4>💰 Pilihan Pembayaran</h4>
    <div class="payment-options">
        <!-- FULL -->
        <div class="payment-option" id="optionFull">
            <input type="radio" name="jenis_pembayaran" id="payFull" value="full" checked>
            <label for="payFull">
                <div class="payment-option-content">
                    <div class="payment-icon">💳</div>
                    <div class="payment-detail">
                        <span class="payment-title">Bayar Full</span>
                        <span class="payment-desc">Bayar lunas seluruh harga perjalanan</span>
                        <span class="payment-price" id="fullPrice">Rp 0</span>
                    </div>
                </div>
            </label>
        </div>
        
        <!-- DP 50% -->
        <div class="payment-option" id="optionDP">
            <input type="radio" name="jenis_pembayaran" id="payDP" value="dp">
            <label for="payDP">
                <div class="payment-option-content">
                    <div class="payment-icon">🏦</div>
                    <div class="payment-detail">
                        <span class="payment-title">Bayar DP 50%</span>
                        <span class="payment-desc">Bayar 50% di awal, sisanya nanti</span>
                        <span class="payment-price" id="dpPrice">Rp 0</span>
                    </div>
                </div>
            </label>
        </div>
        
        <!-- 🔥 BAYAR DENGAN SALDO - TAMBAHAN BARU -->
        <div class="payment-option payment-option-saldo" id="optionSaldo">
            <input type="radio" name="jenis_pembayaran" id="paySaldo" value="saldo">
            <label for="paySaldo">
                <div class="payment-option-content">
                    <div class="payment-icon">💰</div>
                    <div class="payment-detail">
                        <span class="payment-title">Bayar dengan Saldo</span>
                        <span class="payment-desc">Gunakan saldo aplikasi untuk membayar</span>
                        <span class="payment-price" id="saldoPrice">Rp 0</span>
                        <span class="payment-badge" id="saldoStatus">
                            Saldo: Rp <?= number_format($saldo ?? 0, 0, ',', '.') ?>
                        </span>
                    </div>
                </div>
            </label>
        </div>
        
        <!-- 🔥 BAYAR DI TEMPAT -->
        <div class="payment-option payment-option-cash" id="optionCash">
            <input type="radio" name="jenis_pembayaran" id="payCash" value="cash">
            <label for="payCash">
                <div class="payment-option-content">
                    <div class="payment-icon">💵</div>
                    <div class="payment-detail">
                        <span class="payment-title">Bayar di Tempat</span>
                        <span class="payment-desc">Bayar langsung kepada supir saat bertemu</span>
                        <span class="payment-price" id="cashPrice">Rp 0</span>
                        <span class="payment-badge">🟢 Tanpa Pembayaran Digital</span>
                    </div>
                </div>
            </label>
        </div>
    </div>
    
    <!-- 🔥 INFO SALDO -->
    <div id="saldoInfo" class="saldo-info" style="display:none; margin-top:0.8rem; padding:0.8rem 1rem; background:#dbeafe; border-radius:8px; border-left:4px solid #2b6cb0;">
        <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:0.5rem;">
            <div>
                <span style="font-weight:600; color:#1e40af;">
                    <i class="fas fa-wallet"></i> Saldo Anda:
                </span>
                <span style="font-weight:700; font-size:1.1rem; color:#1e40af;">
                    Rp <?= number_format($saldo ?? 0, 0, ',', '.') ?>
                </span>
            </div>
            <div id="saldoCukup" style="display:none; color:#065f46; font-weight:600;">
                <i class="fas fa-check-circle"></i> Saldo cukup
            </div>
            <div id="saldoTidakCukup" style="display:none; color:#991b1b; font-weight:600;">
                <i class="fas fa-exclamation-circle"></i> Saldo tidak cukup
            </div>
        </div>
        <div style="font-size:0.8rem; color:#1e40af; margin-top:0.3rem;">
            <i class="fas fa-info-circle"></i> 
            <?php if (($saldo ?? 0) > 0): ?>
                Saldo akan digunakan untuk membayar full booking ini.
            <?php else: ?>
                Saldo Anda masih 0. Silakan top up atau pilih metode pembayaran lain.
            <?php endif; ?>
        </div>
    </div>
    
    <small class="form-hint" style="color: #f59e0b;">
        <i class="fas fa-info-circle"></i> 
        Pilih DP jika ingin membayar sebagian. Pilih Saldo untuk menggunakan saldo aplikasi.
    </small>
    <small class="form-hint" style="color: #22c55e; margin-top:0.3rem;">
        <i class="fas fa-info-circle"></i> 
        <strong>Bayar di Tempat</strong> - Tidak perlu pembayaran online, bayar langsung ke supir.
    </small>
</div>
            <!-- Data Diri -->
            <div class="form-section">
                <h4>👤 Data Diri</h4>
                <div class="form-row">
                    <div class="form-group">
                        <label>Nama Lengkap <span class="required">*</span></label>
                        <input type="text" name="nama_lengkap" class="form-input" 
                               value="<?= htmlspecialchars($userName) ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Email <span class="required">*</span></label>
                        <input type="email" name="email" class="form-input" 
                               value="<?= htmlspecialchars($userEmail) ?>" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Nomor HP <span class="required">*</span></label>
                        <input type="text" name="no_hp" class="form-input" 
                               value="<?= htmlspecialchars($userNoHp) ?>" required>
                        <small class="form-hint">Nomor WhatsApp aktif</small>
                    </div>
                    <div class="form-group">
                        <label>NIK KTP <span class="required">*</span></label>
                        <input type="text" name="nik_ktp" class="form-input" 
                               placeholder="16 digit angka" maxlength="16" required>
                    </div>
                </div>
                <div class="form-group">
                    <label>📝 Catatan / Permintaan Khusus</label>
                    <textarea name="catatan" class="form-textarea" rows="2" 
                              placeholder="Contoh: butuh kursi khusus, dll"></textarea>
                </div>
            </div>

            <!-- Informasi Cara Booking -->
            <div class="form-section info-booking">
                <div class="info-icon">📌</div>
                <div>
                    <h4>Setelah Booking:</h4>
                    <p>Supir kapal akan memverifikasi pesanan Anda.</p>
                    <p class="highlight">Anda akan mendapatkan notifikasi WhatsApp setelah diverifikasi!</p>
                    <p style="font-size:0.8rem; margin-top:0.3rem; color:#1e40af;">
                        <i class="fas fa-clock"></i> 
                        Jika supir terlambat <strong>lebih dari 2 jam</strong> dari waktu jemput yang disepakati, 
                        Anda dapat membatalkan pesanan dan mengajukan claim pengembalian dana.
                    </p>
                    <p style="font-size:0.8rem; margin-top:0.3rem; color:#065f46; background:#d1fae5; padding:0.3rem 0.8rem; border-radius:6px;">
                        <i class="fas fa-money-bill-wave"></i> 
                        <strong>Bayar di Tempat:</strong> Pesanan langsung dikonfirmasi, tidak perlu verifikasi pembayaran.
                    </p>
                </div>
            </div>

            <!-- Ringkasan Pembayaran -->
            <div class="form-section summary-section">
                <h4>💰 Ringkasan Pembayaran</h4>
                <div class="summary-row">
                    <span>Harga Perjalanan (per rute):</span>
                    <span id="summaryHarga">Rp 0</span>
                </div>
                <div class="summary-row">
                    <span>Jumlah Penumpang:</span>
                    <span id="summaryJumlahPenumpang">1 orang</span>
                </div>
                <div class="summary-row" style="color: #065f46; font-size: 0.85rem;">
                    <span> <em>Harga tetap per rute, tidak tergantung jumlah penumpang</em></span>
                </div>
                <div class="summary-divider"></div>
                <div class="summary-row total">
                    <span><strong>Total Harga</strong></span>
                    <span id="summaryTotalHarga"><strong>Rp 0</strong></span>
                </div>
                <div class="summary-row" style="color: #2b6cb0; font-weight: 600; font-size:1rem; border-top: 2px solid #2b6cb0; padding-top:0.5rem; margin-top:0.3rem;">
                    <span><strong>💳 Yang Harus Dibayar Sekarang</strong></span>
                    <span id="summaryBayarSekarang"><strong>Rp 0</strong></span>
                </div>
                <div class="summary-row" id="summaryCashRow" style="display:none; color: #065f46; background: #d1fae5; padding:0.3rem 0.5rem; border-radius:4px; margin-top:0.3rem;">
                    <span><strong>💵 Bayar di Tempat</strong></span>
                    <span><strong>Bayar ke Supir</strong></span>
                </div>
                <small class="form-hint">* Harga sudah termasuk semua biaya</small>
            </div>

            <!-- ========================================== -->
            <!-- INFORMASI WAKTU JEMPUT & SELESAI DI RINGKASAN -->
            <!-- ========================================== -->
            <div class="form-section summary-section" style="background: #dbeafe; border-color: #93c5fd; margin-top:0.5rem;">
                <h4 style="color:#1e40af;">⏰ Waktu yang Disepakati</h4>
                <div class="summary-row">
                    <span>🕐 Waktu Jemput:</span>
                    <span id="summaryWaktuJemput"><strong>08:00</strong></span>
                </div>
                <div class="summary-row">
                    <span>🏁 Waktu Selesai:</span>
                    <span id="summaryWaktuSelesai"><strong>17:00</strong></span>
                </div>
                <div class="summary-row" style="color: #1e40af; font-size:0.8rem;">
                    <span>⚠️ Jika supir terlambat <strong>> 2 jam</strong>, Anda berhak claim dana</span>
                </div>
            </div>

            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="closeModal()">Batal</button>
                <button type="submit" class="btn btn-primary btn-lg" id="btnSubmitBooking">
                    <i class="fas fa-paper-plane"></i> Pesan Sekarang
                </button>
            </div>
        </form>
    </div>
</div>

<style>
/* ============================================
   STYLE BOOKING
   ============================================ */
.booking-wrapper {
    display: flex;
    gap: 24px;
    max-width: 1200px;
    margin: 1.5rem auto 0;
    padding: 0 20px;
    width: 100%;
    flex: 1;
    align-items: flex-start;
}

.main-content {
    flex: 1;
    min-width: 0;
    background: #fff;
    border-radius: 14px;
    padding: 1.8rem;
    box-shadow: 0 4px 20px rgba(0,0,0,0.06);
    border: 1px solid #e2e8f0;
}

.content-header {
    margin-bottom: 1.5rem;
}

.content-header h1 {
    font-size: 1.5rem;
    font-weight: 700;
    color: #1a202c;
    margin-bottom: 0.2rem;
}

.content-header p {
    color: #718096;
    font-size: 0.95rem;
}

.search-indicator {
    margin-top: 0.5rem;
    padding: 0.5rem 1rem;
    background: #dbeafe;
    border-radius: 8px;
    border-left: 4px solid #2b6cb0;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 0.5rem;
}

.alert {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 0.8rem 1.2rem;
    border-radius: 10px;
    margin-bottom: 1rem;
    border-left: 4px solid transparent;
}

.alert-success {
    background: #d1fae5;
    color: #065f46;
    border-left-color: #22c55e;
}

.alert-danger {
    background: #fee2e2;
    color: #991b1b;
    border-left-color: #ef4444;
}

.alert-close {
    margin-left: auto;
    background: none;
    border: none;
    font-size: 1rem;
    cursor: pointer;
    color: inherit;
    opacity: 0.6;
    padding: 0 4px;
}

.alert-close:hover { opacity: 1; }

.filter-section {
    background: #f7fafc;
    border-radius: 14px;
    padding: 1.2rem 1.5rem;
    margin-bottom: 1.5rem;
    border: 1px solid #e2e8f0;
}

.filter-row {
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;
    align-items: flex-end;
}

.filter-group {
    flex: 1;
    min-width: 140px;
}

.filter-group label {
    display: block;
    font-size: 0.8rem;
    font-weight: 600;
    color: #4a5568;
    margin-bottom: 0.3rem;
}

.filter-input {
    width: 100%;
    padding: 0.6rem 0.8rem;
    border: 1.5px solid #e2e8f0;
    border-radius: 8px;
    font-size: 0.9rem;
    background: #fff;
    transition: all 0.3s ease;
    cursor: pointer;
}

.filter-input:focus {
    border-color: #2b6cb0;
    outline: none;
    box-shadow: 0 0 0 4px rgba(43,108,176,0.08);
}

.filter-result-info {
    margin-top: 0.8rem;
    padding: 0.5rem 1rem;
    background: #fff;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
    font-size: 0.85rem;
    color: #4a5568;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 0.5rem;
}

.filter-result-info i { color: #2b6cb0; }

.btn {
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
    padding: 0.5rem 1.2rem;
    border: none;
    border-radius: 8px;
    font-weight: 600;
    font-size: 0.85rem;
    cursor: pointer;
    transition: all 0.3s ease;
    text-decoration: none;
}

.btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

.btn-primary { background: #2b6cb0; color: #fff; }
.btn-primary:hover { background: #1a4a7a; color: #fff; }

.btn-secondary { background: #e2e8f0; color: #4a5568; }
.btn-secondary:hover { background: #cbd5e0; color: #1a202c; }

.btn-success { background: #22c55e; color: #fff; }
.btn-success:hover { background: #16a34a; color: #fff; }

.btn-sm { padding: 0.3rem 0.8rem; font-size: 0.75rem; }
.btn-lg { padding: 0.7rem 1.8rem; font-size: 1rem; }
.btn:disabled { opacity: 0.6; cursor: not-allowed !important; }

.btn-pesan-match {
    background: #22c55e;
    animation: pulse-green 2s infinite;
}

@keyframes pulse-green {
    0%, 100% { box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.4); }
    50% { box-shadow: 0 0 0 8px rgba(34, 197, 94, 0); }
}

.kapal-section { margin-top: 0.5rem; }

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
    flex-wrap: wrap;
    gap: 0.5rem;
}

.section-header h3 {
    font-size: 1.05rem;
    font-weight: 700;
    color: #2d3748;
    margin: 0;
}

.kapal-count {
    font-size: 0.8rem;
    color: #718096;
    background: #edf2f7;
    padding: 0.2rem 0.8rem;
    border-radius: 20px;
}

.kapal-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 1.5rem;
}

.kapal-card {
    background: #fff;
    border-radius: 14px;
    border: 1px solid #e2e8f0;
    overflow: hidden;
    transition: all 0.3s ease;
    position: relative;
}

.kapal-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 40px rgba(0,0,0,0.08);
    border-color: #2b6cb0;
}

.kapal-card.has-matching-route {
    border-color: #22c55e;
    border-width: 2px;
}

.matching-badge {
    position: absolute;
    top: 10px;
    left: 50%;
    transform: translateX(-50%);
    background: #22c55e;
    color: #fff;
    padding: 0.2rem 0.8rem;
    border-radius: 20px;
    font-size: 0.65rem;
    font-weight: 600;
    z-index: 10;
    white-space: nowrap;
    box-shadow: 0 2px 8px rgba(34, 197, 94, 0.4);
}

.kapal-image {
    position: relative;
    height: 180px;
    background: #edf2f7;
    overflow: hidden;
}

.kapal-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.kapal-image-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 4rem;
    color: #a0aec0;
    background: #f7fafc;
}

.kapal-type {
    position: absolute;
    top: 10px;
    right: 10px;
    background: rgba(0,0,0,0.7);
    color: #fff;
    font-size: 0.65rem;
    font-weight: 600;
    padding: 0.2rem 0.8rem;
    border-radius: 12px;
    text-transform: uppercase;
}

.status-available {
    position: absolute;
    top: 10px;
    left: 10px;
    background: rgba(34, 197, 94, 0.9);
    color: #fff;
    font-size: 0.6rem;
    font-weight: 700;
    padding: 0.15rem 0.6rem;
    border-radius: 12px;
    text-transform: uppercase;
}

.kapal-body { padding: 1rem 1.2rem; }

.kapal-body h4 {
    font-size: 1.05rem;
    font-weight: 700;
    color: #1a202c;
    margin-bottom: 0.3rem;
}

.kapal-meta {
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;
    font-size: 0.8rem;
    color: #4a5568;
}

.meta-item {
    display: flex;
    align-items: center;
    gap: 0.2rem;
}

.kapal-fasilitas {
    font-size: 0.8rem;
    color: #4a5568;
    margin: 0.2rem 0;
    display: flex;
    align-items: center;
    gap: 0.3rem;
}

.kapal-tujuan {
    display: flex;
    flex-wrap: wrap;
    gap: 0.3rem;
    margin: 0.3rem 0;
}

.tujuan-label {
    font-size: 0.75rem;
    font-weight: 600;
    color: #718096;
    display: flex;
    align-items: center;
    gap: 0.2rem;
}

.tujuan-tag {
    font-size: 0.7rem;
    background: #ebf8ff;
    color: #2b6cb0;
    padding: 0.1rem 0.5rem;
    border-radius: 12px;
    border: 1px solid #bee3f8;
}

.tujuan-tag.tujuan-match {
    background: #d1fae5;
    color: #065f46;
    border-color: #86efac;
    font-weight: 600;
}

.kapal-pelabuhan {
    display: flex;
    flex-wrap: wrap;
    gap: 0.3rem;
    margin: 0.3rem 0;
}

.pelabuhan-label {
    font-size: 0.75rem;
    font-weight: 600;
    color: #718096;
    display: flex;
    align-items: center;
    gap: 0.2rem;
}

.pelabuhan-tag {
    font-size: 0.7rem;
    background: #fef3c7;
    color: #92400e;
    padding: 0.1rem 0.5rem;
    border-radius: 12px;
    border: 1px solid #fcd34d;
}

.pelabuhan-tag.pelabuhan-match {
    background: #dbeafe;
    color: #1e40af;
    border-color: #93c5fd;
    font-weight: 600;
}

.kapal-rute-info {
    display: flex;
    gap: 1rem;
    font-size: 0.75rem;
    color: #4a5568;
    margin-top: 0.3rem;
    padding: 0.3rem 0.5rem;
    background: #f7fafc;
    border-radius: 6px;
    flex-wrap: wrap;
    align-items: center;
}

.kapal-rute-info .rute-count { font-weight: 600; }
.kapal-rute-info .rute-price { color: #2b6cb0; font-weight: 600; }

.kapal-warning {
    background: #fef3c7;
    padding: 0.5rem 1.2rem;
    font-size: 0.75rem;
    color: #92400e;
    border-top: 1px solid #fcd34d;
    text-align: center;
    display: flex;
    justify-content: center;
    gap: 0.5rem;
    align-items: center;
    flex-wrap: wrap;
}

.kapal-footer {
    padding: 0.8rem 1.2rem 1.2rem;
    border-top: 1px solid #edf2f7;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 0.5rem;
    flex-wrap: wrap;
}

.price-tag {
    font-size: 1.1rem;
    font-weight: 700;
    color: #2b6cb0;
}

.price-label {
    font-size: 0.7rem;
    font-weight: 400;
    color: #a0aec0;
}

.empty-state {
    text-align: center;
    padding: 2rem;
    color: #718096;
}

.empty-icon {
    font-size: 4rem;
    margin-bottom: 1rem;
    opacity: 0.5;
}

.shared-trip-section {
    background: linear-gradient(135deg, #ecfdf5, #d1fae5);
    border-radius: 14px;
    padding: 1.2rem 1.5rem;
    margin-bottom: 1.5rem;
    border: 1px solid #a7f3d0;
}

.shared-trip-section h3 {
    font-size: 1.05rem;
    font-weight: 700;
    color: #065f46;
}

.shared-trip-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 1rem;
}

.shared-trip-card {
    background: #fff;
    border-radius: 12px;
    padding: 1rem;
    border: 1px solid #a7f3d0;
    transition: all 0.3s ease;
}

.shared-trip-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.08);
}

.trip-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.trip-badge {
    background: #f59e0b;
    color: #fff;
    font-size: 0.6rem;
    font-weight: 700;
    padding: 0.15rem 0.6rem;
    border-radius: 12px;
    text-transform: uppercase;
}

.trip-price {
    font-weight: 700;
    color: #065f46;
}

.trip-body h4 {
    font-size: 0.95rem;
    font-weight: 700;
    color: #1a202c;
    margin: 0.3rem 0;
}

.trip-body p {
    font-size: 0.8rem;
    color: #4a5568;
    margin: 0.1rem 0;
}

/* ========================================== */
/* PAYMENT OPTIONS - DENGAN BAYAR DI TEMPAT */
/* ========================================== */
.payment-options {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 1rem;
}

.payment-option {
    border: 2px solid #e2e8f0;
    border-radius: 12px;
    transition: all 0.3s ease;
    cursor: pointer;
}

.payment-option:hover {
    border-color: #2b6cb0;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

.payment-option input[type="radio"] {
    display: none;
}

.payment-option input[type="radio"]:checked + label {
    border-color: transparent;
}

.payment-option:has(input:checked) {
    border-color: #2b6cb0;
    background: #ebf8ff;
    box-shadow: 0 0 0 4px rgba(43,108,176,0.1);
}

.payment-option-cash:has(input:checked) {
    border-color: #22c55e;
    background: #d1fae5;
}

.payment-option label {
    display: block;
    cursor: pointer;
    padding: 0;
    margin: 0;
}

.payment-option-content {
    display: flex;
    align-items: center;
    gap: 0.8rem;
    padding: 0.8rem 1rem;
}

.payment-icon {
    font-size: 1.8rem;
    flex-shrink: 0;
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f7fafc;
    border-radius: 10px;
}

.payment-option:has(input:checked) .payment-icon {
    background: #dbeafe;
}

.payment-option-cash:has(input:checked) .payment-icon {
    background: #d1fae5;
}

.payment-detail {
    flex: 1;
}

.payment-title {
    display: block;
    font-weight: 700;
    font-size: 0.95rem;
    color: #1a202c;
}

.payment-desc {
    display: block;
    font-size: 0.75rem;
    color: #718096;
}

.payment-price {
    display: block;
    font-weight: 700;
    font-size: 1rem;
    color: #2b6cb0;
    margin-top: 0.2rem;
}

.payment-option:has(input:checked) .payment-price {
    color: #1a4a7a;
}

.payment-option-cash .payment-price {
    color: #065f46;
}

.payment-badge {
    display: inline-block;
    font-size: 0.6rem;
    font-weight: 600;
    color: #22c55e;
    background: #d1fae5;
    padding: 0.1rem 0.6rem;
    border-radius: 12px;
    margin-top: 0.2rem;
}

/* ========================================== */
/* CASH INFO */
/* ========================================== */
.cash-info {
    display: none;
    background: #d1fae5;
    padding: 0.8rem 1.2rem;
    border-radius: 8px;
    border-left: 4px solid #22c55e;
    margin: 0.5rem 0;
}

.cash-info.show {
    display: flex;
    gap: 0.8rem;
    align-items: flex-start;
}

.cash-info-icon {
    font-size: 1.5rem;
    color: #22c55e;
    flex-shrink: 0;
}

.cash-info-content h4 {
    color: #065f46;
    font-size: 0.9rem;
    margin-bottom: 0.2rem;
}

.cash-info-content p {
    color: #065f46;
    font-size: 0.85rem;
    margin: 0;
}

/* ========================================== */
/* MODAL */
/* ========================================== */
.modal-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 1000;
    align-items: center;
    justify-content: center;
    padding: 20px;
}

.modal-overlay.active { display: flex; }

.modal {
    background: #fff;
    border-radius: 16px;
    max-width: 700px;
    width: 100%;
    max-height: 90vh;
    overflow-y: auto;
    padding: 1.8rem 2rem;
    animation: modalIn 0.3s ease;
}

@keyframes modalIn {
    from { transform: scale(0.95) translateY(-20px); opacity: 0; }
    to { transform: scale(1) translateY(0); opacity: 1; }
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
    padding-bottom: 0.8rem;
    border-bottom: 1px solid #e2e8f0;
}

.modal-header h3 {
    font-size: 1.2rem;
    font-weight: 700;
    color: #1a202c;
    margin: 0;
}

.modal-close {
    background: none;
    border: none;
    font-size: 1.8rem;
    cursor: pointer;
    color: #a0aec0;
    transition: all 0.3s ease;
    line-height: 1;
}

.modal-close:hover { color: #1a202c; }

.booking-form .form-section { margin-bottom: 1.2rem; }

.booking-form .form-section h4 {
    font-size: 0.95rem;
    font-weight: 700;
    color: #2d3748;
    margin-bottom: 0.6rem;
}

.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
}

.form-group { margin-bottom: 0.8rem; }

.form-group label {
    display: block;
    font-size: 0.8rem;
    font-weight: 600;
    color: #4a5568;
    margin-bottom: 0.2rem;
}

.form-group .required { color: #ef4444; }

.form-input, .form-select, .form-textarea {
    width: 100%;
    padding: 0.6rem 0.8rem;
    border: 1.5px solid #e2e8f0;
    border-radius: 8px;
    font-size: 0.9rem;
    transition: all 0.3s ease;
    background: #fff;
    font-family: inherit;
}

.form-input:focus, .form-select:focus, .form-textarea:focus {
    border-color: #2b6cb0;
    outline: none;
    box-shadow: 0 0 0 4px rgba(43,108,176,0.08);
}

.form-hint {
    font-size: 0.7rem;
    color: #a0aec0;
    margin-top: 0.2rem;
    display: block;
}

.selected-ship {
    background: #f7fafc;
    padding: 0.6rem 1rem;
    border-radius: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid #e2e8f0;
}

.selected-ship #selectedShipName {
    font-weight: 700;
    color: #1a202c;
}

.selected-ship #selectedShipCapacity {
    font-size: 0.85rem;
    color: #718096;
}

/* ========================================== */
/* RUTE DISPLAY - TANPA DROPDOWN */
/* ========================================== */
.route-display { margin-top: 0.2rem; }

.route-info-box {
    display: flex;
    gap: 1rem;
    align-items: center;
    padding: 1rem 1.2rem;
    background: #f0fdf4;
    border: 2px solid #22c55e;
    border-radius: 12px;
    transition: all 0.3s ease;
}

.route-info-box:hover {
    background: #dcfce7;
    border-color: #16a34a;
}

.route-icon {
    font-size: 2rem;
    color: #22c55e;
    flex-shrink: 0;
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #dcfce7;
    border-radius: 10px;
}

.route-details { flex: 1; }

.route-label {
    font-size: 0.75rem;
    font-weight: 600;
    color: #065f46;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}

.route-text {
    font-size: 1rem;
    color: #1a202c;
    margin: 0.1rem 0;
}

.route-price {
    font-size: 0.9rem;
    color: #4a5568;
}

.route-pelabuhan {
    font-size: 0.85rem;
    color: #4a5568;
}

.route-pelabuhan i { color: #2b6cb0; }

.route-match-info {
    margin-top: 0.2rem;
    padding: 0.2rem 0.5rem;
    background: #d1fae5;
    border-radius: 4px;
    display: inline-block;
    color: #065f46;
    font-size: 0.75rem;
}

.route-warning {
    background: #fee2e2;
    padding: 0.8rem 1rem;
    border-radius: 8px;
    border-left: 4px solid #ef4444;
    margin-top: 0.5rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: #991b1b;
    font-size: 0.85rem;
}

.route-warning i {
    color: #ef4444;
    font-size: 1.2rem;
    flex-shrink: 0;
}

/* ========================================== */
/* INFO BOOKING */
/* ========================================== */
.info-booking {
    background: linear-gradient(135deg, #eff6ff, #dbeafe);
    border-radius: 12px;
    padding: 1rem 1.2rem;
    display: flex;
    gap: 1rem;
    align-items: flex-start;
    border: 1px solid #bfdbfe;
}

.info-booking .info-icon {
    font-size: 1.8rem;
    flex-shrink: 0;
}

.info-booking h4 {
    font-size: 0.9rem;
    font-weight: 700;
    color: #1e40af;
    margin-bottom: 0.2rem;
}

.info-booking p {
    font-size: 0.85rem;
    color: #1e40af;
    margin: 0;
}

.info-booking .highlight {
    font-weight: 600;
    color: #1e40af;
    margin-top: 0.2rem;
}

/* ========================================== */
/* SUMMARY SECTION */
/* ========================================== */
.summary-section {
    background: #f7fafc;
    border-radius: 12px;
    padding: 1rem 1.2rem;
    border: 1px solid #e2e8f0;
}

.summary-row {
    display: flex;
    justify-content: space-between;
    padding: 0.3rem 0;
    font-size: 0.9rem;
    color: #4a5568;
}

.summary-divider {
    height: 1px;
    background: #cbd5e0;
    margin: 0.3rem 0;
}

.summary-row.total {
    font-size: 1.1rem;
    padding-top: 0.5rem;
    border-top: 2px solid #cbd5e0;
}

/* ========================================== */
/* FORM ACTIONS */
/* ========================================== */
.form-actions {
    display: flex;
    gap: 1rem;
    justify-content: flex-end;
    margin-top: 1.5rem;
    padding-top: 1rem;
    border-top: 1px solid #e2e8f0;
}

/* ========================================== */
/* RESPONSIVE */
/* ========================================== */
@media (max-width: 768px) {
    .booking-wrapper {
        flex-direction: column;
        padding: 0 12px;
        margin-top: 1rem;
    }
    .main-content { padding: 1rem; }
    .filter-row { flex-direction: column; align-items: stretch; }
    .filter-group { min-width: 100%; }
    .form-row { grid-template-columns: 1fr; }
    .kapal-grid { grid-template-columns: 1fr; }
    .shared-trip-grid { grid-template-columns: 1fr; }
    .modal { padding: 1.2rem; }
    .selected-ship { flex-direction: column; align-items: flex-start; gap: 0.3rem; }
    .kapal-footer { flex-direction: column; align-items: stretch; }
    .price-tag { text-align: center; }
    .matching-badge { font-size: 0.5rem; padding: 0.1rem 0.5rem; top: 5px; }
    .route-info-box { flex-direction: column; text-align: center; padding: 0.8rem; }
    .route-icon { width: 40px; height: 40px; font-size: 1.5rem; }
    .payment-options { grid-template-columns: 1fr; }
}

@media (max-width: 480px) {
    .main-content { padding: 0.8rem; }
    .form-actions { flex-direction: column; }
    .form-actions .btn { width: 100%; justify-content: center; }
    .kapal-image { height: 140px; }
    .payment-option-content { flex-direction: column; text-align: center; }
    .payment-icon { margin: 0 auto; }
}
</style>

<script>
// ============================================
// FILTER TANGGAL - SUBMIT OTOMATIS
// ============================================
document.addEventListener('DOMContentLoaded', function() {
    const tanggalInput = document.getElementById('filterTanggal');
    const pelabuhanSelect = document.getElementById('pelabuhanFilter');
    const filterForm = document.getElementById('filterForm');
    
    if (tanggalInput) {
        tanggalInput.addEventListener('change', function() {
            filterForm.submit();
        });
    }
    
    // Auto-submit ketika pelabuhan dipilih
    if (pelabuhanSelect) {
        pelabuhanSelect.addEventListener('change', function() {
            filterForm.submit();
        });
    }
    
    const searchInput = document.querySelector('input[name="search"]');
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                filterForm.submit();
            }
        });
    }
    
    // ============================================
    // 🔥 PAYMENT OPTION - TAMPILKAN INFO CASH
    // ============================================
    const cashRadio = document.getElementById('payCash');
    const cashInfo = document.getElementById('cashInfo');
    
    if (cashRadio && cashInfo) {
        // Cek status awal
        if (cashRadio.checked) {
            cashInfo.classList.add('show');
            cashInfo.style.display = 'flex';
        }
        
        cashRadio.addEventListener('change', function() {
            if (this.checked) {
                cashInfo.classList.add('show');
                cashInfo.style.display = 'flex';
                updateSummary();
            } else {
                cashInfo.classList.remove('show');
                cashInfo.style.display = 'none';
                updateSummary();
            }
        });
    }
    
    // Juga untuk radio lainnya
    document.querySelectorAll('input[name="jenis_pembayaran"]').forEach(radio => {
        radio.addEventListener('change', function() {
            if (this.value !== 'cash' && cashInfo) {
                cashInfo.classList.remove('show');
                cashInfo.style.display = 'none';
            }
            updateSummary();
        });
    });
});

// ============================================
// BOOKING MODAL - OTOMATIS PILIH RUTE (TANPA DROPDOWN)
// ============================================
document.querySelectorAll('.btn-pesan:not([disabled])').forEach(btn => {
    btn.addEventListener('click', function() {
        const kapalId = this.dataset.kapalId;
        const kapalName = this.dataset.kapalNama;
        const kapasitas = parseInt(this.dataset.kapasitas) || 54;
        const tanggal = this.dataset.tanggal || '';
        const routes = JSON.parse(this.dataset.routes || '[]');
        const totalRute = parseInt(this.dataset.totalRute) || 0;
        const matchingRouteId = this.dataset.matchingRoute || null;
        const matchingRouteData = this.dataset.matchingRouteData ? JSON.parse(this.dataset.matchingRouteData) : null;
        const matchingRouteAsal = this.dataset.matchingRouteAsal || '';
        const searchTerm = this.dataset.searchTerm || '';
        
        if (totalRute === 0 || routes.length === 0) {
            alert(' Maaf, kapal ini belum memiliki rute. Silakan hubungi admin untuk informasi lebih lanjut.');
            return;
        }
        
        document.getElementById('bookingKapalId').value = kapalId;
        document.getElementById('selectedShipName').textContent = kapalName;
        document.getElementById('selectedShipCapacity').textContent = `Kapasitas: ${kapasitas} orang`;
        document.getElementById('kapasitasHint').textContent = `Maksimal ${kapasitas} orang. Harga TETAP per rute (tidak tergantung jumlah penumpang).`;
        document.getElementById('bookingJumlahPenumpang').max = kapasitas;
        document.getElementById('bookingJumlahPenumpang').value = 1;
        
        if (tanggal) {
            document.getElementById('bookingTanggal').value = tanggal;
            document.getElementById('bookingTanggalHidden').value = tanggal;
        }
        
        // ==============================================
        // CARI RUTE YANG COCOK DENGAN PENCARIAN
        // ==============================================
        let selectedRoute = null;
        let matchFound = false;
        let matchDestinasi = '';
        let routeAsal = '';
        let warningRoute = document.getElementById('routeWarning');
        let routeMatchInfo = document.getElementById('routeMatchInfo');
        let routeMatchDestinasi = document.getElementById('routeMatchDestinasi');
        let routeInfoBox = document.getElementById('routeInfoBox');
        let displayPelabuhanAsal = document.getElementById('displayPelabuhanAsal');
        
        // Cari rute yang match dengan searchTerm
        if (searchTerm.trim() !== '') {
            for (let route of routes) {
                if (route.tujuan && route.tujuan.toLowerCase().includes(searchTerm.toLowerCase())) {
                    selectedRoute = route;
                    matchFound = true;
                    matchDestinasi = route.tujuan;
                    routeAsal = route.asal || matchingRouteAsal || 'Parapat';
                    break;
                }
            }
        }
        
        // Jika tidak ada match, gunakan matchingRouteData dari button
        if (!selectedRoute && matchingRouteData) {
            selectedRoute = matchingRouteData;
            matchFound = true;
            matchDestinasi = matchingRouteData.tujuan || searchTerm;
            routeAsal = matchingRouteData.asal || matchingRouteAsal || 'Parapat';
        }
        
        // Jika masih tidak ada match, ambil rute pertama (default)
        if (!selectedRoute && routes.length > 0) {
            selectedRoute = routes[0];
            routeAsal = selectedRoute.asal || 'Parapat';
        }
        
        // ==============================================
        // TAMPILKAN RUTE YANG DIPILIH (TANPA DROPDOWN)
        // ==============================================
        if (selectedRoute) {
            // Set hidden inputs
            document.getElementById('bookingRouteId').value = selectedRoute.id;
            document.getElementById('bookingRouteHarga').value = selectedRoute.harga_jual || 0;
            document.getElementById('bookingRouteTujuan').value = selectedRoute.tujuan || '';
            document.getElementById('bookingRouteAsal').value = routeAsal || selectedRoute.asal || 'Parapat';
            
            // Tampilkan rute
            const displayText = document.getElementById('displayRouteText');
            const displayPrice = document.getElementById('displayRoutePrice');
            
            displayText.innerHTML = `
                <strong>${routeAsal || selectedRoute.asal || 'Parapat'} → ${selectedRoute.tujuan || '-'}</strong>
            `;
            displayPrice.innerHTML = `
                <span style="font-weight: 700; color: #2b6cb0; font-size: 1.1rem;">
                    Rp ${(selectedRoute.harga_jual || 0).toLocaleString('id-ID')}
                </span>
                <span style="color: #a0aec0; font-size: 0.75rem;">/ perjalanan</span>
            `;
            
            // Tampilkan pelabuhan asal
            displayPelabuhanAsal.textContent = routeAsal || selectedRoute.asal || 'Parapat';
            
            // Tampilkan info match
            if (matchFound && matchDestinasi) {
                routeMatchDestinasi.textContent = matchDestinasi;
                routeMatchInfo.style.display = 'inline-block';
                warningRoute.style.display = 'none';
                routeInfoBox.style.borderColor = '#22c55e';
                routeInfoBox.style.background = '#f0fdf4';
            } else if (searchTerm.trim() !== '') {
                routeMatchInfo.style.display = 'none';
                warningRoute.style.display = 'flex';
                routeInfoBox.style.borderColor = '#ef4444';
                routeInfoBox.style.background = '#fee2e2';
            } else {
                routeMatchInfo.style.display = 'none';
                warningRoute.style.display = 'none';
                routeInfoBox.style.borderColor = '#22c55e';
                routeInfoBox.style.background = '#f0fdf4';
            }
            
            // Update summary dengan harga DP/Full/Cash
            setTimeout(function() {
                updateSummary();
            }, 100);
            
        } else {
            // Tidak ada rute
            document.getElementById('displayRouteText').innerHTML = `
                <span style="color: #ef4444;">⚠️ Tidak ada rute tersedia</span>
            `;
            document.getElementById('displayRoutePrice').innerHTML = `
                <span style="color: #ef4444;">Harga: -</span>
            `;
            displayPelabuhanAsal.textContent = '-';
            routeMatchInfo.style.display = 'none';
            warningRoute.style.display = 'flex';
            routeInfoBox.style.borderColor = '#ef4444';
            routeInfoBox.style.background = '#fee2e2';
        }
        
        document.getElementById('bookingModal').classList.add('active');
        document.body.style.overflow = 'hidden';
    });
});

// Handler untuk tombol yang disabled
document.querySelectorAll('.btn-pesan[disabled]').forEach(btn => {
    btn.addEventListener('click', function(e) {
        e.preventDefault();
        alert(' Maaf, kapal ini belum memiliki rute. Silakan klik tombol "Buat Rute Otomatis" atau hubungi admin.');
    });
});

function closeModal() {
    document.getElementById('bookingModal').classList.remove('active');
    document.body.style.overflow = '';
}

// ============================================
// UPDATE SUMMARY - DENGAN DP/FULL/CASH
// ============================================
function updateSummary() {
    const routeHarga = parseInt(document.getElementById('bookingRouteHarga').value) || 0;
    const jumlah = parseInt(document.getElementById('bookingJumlahPenumpang').value) || 1;
    const waktuJemput = document.getElementById('bookingWaktuJemput').value || '08:00';
    const waktuSelesai = document.getElementById('bookingWaktuSelesai').value || '17:00';
    
    // Cek jenis pembayaran
    const jenisBayar = document.querySelector('input[name="jenis_pembayaran"]:checked');
    const jenis = jenisBayar ? jenisBayar.value : 'full';
    const totalHarga = routeHarga;
    
    // Hitung pembayaran
    let bayarSekarang = totalHarga;
    let labelBayar = 'Full';
    let isCash = false;
    
    if (jenis === 'dp') {
        bayarSekarang = Math.ceil(totalHarga * 0.5);
        labelBayar = 'DP 50%';
    } else if (jenis === 'cash') {
        bayarSekarang = totalHarga;
        labelBayar = 'Bayar di Tempat';
        isCash = true;
    }
    
    document.getElementById('summaryHarga').textContent = `Rp ${routeHarga.toLocaleString('id-ID')}`;
    document.getElementById('summaryJumlahPenumpang').textContent = `${jumlah} orang`;
    document.getElementById('summaryTotalHarga').innerHTML = `<strong>Rp ${totalHarga.toLocaleString('id-ID')}</strong>`;
    
    // Tampilkan bayar sekarang
    if (isCash) {
        document.getElementById('summaryBayarSekarang').innerHTML = `<strong style="color:#22c55e;">💵 Bayar ke Supir</strong>`;
        document.getElementById('summaryCashRow').style.display = 'flex';
    } else {
        document.getElementById('summaryBayarSekarang').innerHTML = `<strong>Rp ${bayarSekarang.toLocaleString('id-ID')}</strong>`;
        document.getElementById('summaryCashRow').style.display = 'none';
    }
    
    document.getElementById('summaryWaktuJemput').innerHTML = `<strong>${waktuJemput}</strong>`;
    document.getElementById('summaryWaktuSelesai').innerHTML = `<strong>${waktuSelesai}</strong>`;
    document.getElementById('bookingHargaTotal').value = totalHarga;
    document.getElementById('jenisPembayaranHidden').value = jenis;
    
    // Update tampilan harga di pilihan
    document.getElementById('fullPrice').textContent = `Rp ${totalHarga.toLocaleString('id-ID')}`;
    document.getElementById('dpPrice').textContent = `Rp ${Math.ceil(totalHarga * 0.5).toLocaleString('id-ID')}`;
    document.getElementById('cashPrice').textContent = `Rp ${totalHarga.toLocaleString('id-ID')}`;
}

// Event listeners untuk update summary
document.getElementById('bookingJumlahPenumpang')?.addEventListener('input', updateSummary);
document.getElementById('bookingTanggal')?.addEventListener('change', function() {
    document.getElementById('bookingTanggalHidden').value = this.value;
});
document.getElementById('bookingWaktuJemput')?.addEventListener('change', updateSummary);
document.getElementById('bookingWaktuSelesai')?.addEventListener('change', updateSummary);

// Event listener untuk pilihan pembayaran
document.querySelectorAll('input[name="jenis_pembayaran"]').forEach(radio => {
    radio.addEventListener('change', function() {
        updateSummary();
    });
});

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closeModal();
});

document.getElementById('bookingModal')?.addEventListener('click', function(e) {
    if (e.target === this) closeModal();
});

// ============================================
// SUBMIT FORM - VALIDASI DENGAN DP/FULL/CASH
// ============================================
document.getElementById('bookingForm')?.addEventListener('submit', function(e) {
    const routeId = document.getElementById('bookingRouteId').value;
    if (!routeId || parseInt(routeId) === 0) {
        e.preventDefault();
        alert(' Silakan pilih rute perjalanan terlebih dahulu.');
        return;
    }
    
    const tanggal = document.getElementById('bookingTanggal').value;
    if (!tanggal) {
        e.preventDefault();
        alert(' Silakan pilih tanggal keberangkatan.');
        return;
    }
    
    const waktuJemput = document.getElementById('bookingWaktuJemput').value;
    if (!waktuJemput) {
        e.preventDefault();
        alert(' Silakan pilih waktu jemput.');
        return;
    }
    
    const waktuSelesai = document.getElementById('bookingWaktuSelesai').value;
    if (!waktuSelesai) {
        e.preventDefault();
        alert(' Silakan pilih waktu selesai.');
        return;
    }
    
    const jumlah = parseInt(document.getElementById('bookingJumlahPenumpang').value);
    const kapasitas = parseInt(document.getElementById('bookingJumlahPenumpang').max) || 54;
    if (jumlah < 1 || jumlah > kapasitas) {
        e.preventDefault();
        alert(` Jumlah penumpang harus antara 1-${kapasitas} orang.`);
        return;
    }
    
    const nik = document.querySelector('input[name="nik_ktp"]').value;
    if (nik.length < 16 || !/^\d+$/.test(nik)) {
        e.preventDefault();
        alert(' NIK harus 16 digit angka.');
        return;
    }
    
    const hargaTotal = document.getElementById('bookingHargaTotal').value;
    if (!hargaTotal || parseInt(hargaTotal) === 0) {
        e.preventDefault();
        alert(' Silakan pilih rute terlebih dahulu.');
        return;
    }
    
    // Validasi jenis pembayaran
    const jenisBayar = document.querySelector('input[name="jenis_pembayaran"]:checked');
    if (!jenisBayar) {
        e.preventDefault();
        alert(' Silakan pilih jenis pembayaran (Full, DP, atau Bayar di Tempat).');
        return;
    }
});
</script>

<?php include __DIR__ . '/../layouts/footer.php'; ?>