<?php
/**
 * status_pesanan.php - Halaman Status Pesanan Wisatawan
 * DIPERBAIKI - Menampilkan SEMUA data seperti dari notifikasi
 * DITAMBAHKAN - Logika Claim dan tombol aksi lengkap
 * DIPERBAIKI - Menampilkan Jenis Pembayaran dengan benar (Full, DP, Bayar di Tempat)
 */
$activeMenu = 'riwayatPesanan';
$pageTitle = 'Status Pesanan - Wisatawan';
include __DIR__ . '/../layouts/header.php';

// Data dari controller
$pesanan = $pesanan ?? [];
$notifications = $notifications ?? [];

if (empty($pesanan)) {
    ?>
    <div class="alert alert-danger">
        <i class="fas fa-exclamation-circle"></i>
        Pesanan tidak ditemukan.
    </div>
    <a href="?page=wisatawan&action=riwayat" class="btn btn-primary">← Kembali ke Riwayat</a>
    <?php
    include __DIR__ . '/../layouts/footer.php';
    exit;
}

// ==============================================
// CEK STATUS UNTUK FITUR
// ==============================================
$isCompleted = ($pesanan['status_pesanan'] == 'completed' || $pesanan['status_pesanan'] == 'selesai');
$isConfirmed = ($pesanan['status_pesanan'] == 'confirmed' || $pesanan['status_pesanan'] == 'dikonfirmasi');
$isPaid = ($pesanan['status_pembayaran'] == 'lunas');
$isCancelled = ($pesanan['status_pesanan'] == 'cancelled' || $pesanan['status_pesanan'] == 'dibatalkan');
$isPending = ($pesanan['status_pesanan'] == 'pending' || $pesanan['status_pesanan'] == 'menunggu');

// ==============================================
// CEK APAKAH SUDAH DIJEMPUT
// ==============================================
$isDijemput = !empty($pesanan['waktu_jemput_aktual']);
$waktuJemputAktual = $isDijemput ? new DateTime($pesanan['waktu_jemput_aktual']) : null;
$waktuSelesaiAktual = !empty($pesanan['waktu_selesai_aktual']) ? new DateTime($pesanan['waktu_selesai_aktual']) : null;

// ==============================================
// CEK JENIS PEMBAYARAN
// ==============================================
$jenisPembayaran = $pesanan['jenis_pembayaran'] ?? 'full';
$jumlahDibayar = (int) ($pesanan['jumlah_dibayar'] ?? 0);
$sisaPembayaran = (int) ($pesanan['sisa_pembayaran'] ?? 0);

// ==============================================
// 🔥 MAP JENIS PEMBAYARAN
// ==============================================
$jenisMap = [
    'full' => ['label' => '💳 Bayar Full', 'badge' => 'badge-success', 'desc' => 'Bayar lunas seluruh harga'],
    'dp' => ['label' => '🏦 DP 50%', 'badge' => 'badge-warning', 'desc' => 'Bayar 50% di awal, sisanya nanti'],
    'cash' => ['label' => '💵 Bayar di Tempat', 'badge' => 'badge-cash', 'desc' => 'Bayar langsung ke supir saat bertemu'],
];
$jenisInfo = $jenisMap[$jenisPembayaran] ?? ['label' => 'Full', 'badge' => 'badge-secondary', 'desc' => ''];

// ==============================================
// CEK WAKTU JEMPUT DAN SELESAI
// ==============================================
$waktuJemputRencana = !empty($pesanan['waktu_jemput_rencana']) 
    ? date('H:i', strtotime($pesanan['waktu_jemput_rencana'])) 
    : '08:00';
$waktuSelesaiRencana = !empty($pesanan['waktu_selesai_rencana']) 
    ? date('H:i', strtotime($pesanan['waktu_selesai_rencana'])) 
    : '17:00';

// ==============================================
// 🔥 LOGIKA CLAIM
// ==============================================
$canClaim = false;
$claimMessage = '';
$claimStatus = $pesanan['status_claim'] ?? 'tidak';

// Cek apakah sudah ada claim sebelumnya
$existingClaim = null;
try {
    $stmt = $this->pdo->prepare("SELECT id, status_claim FROM claim_pengembalian WHERE pesanan_id = ?");
    $stmt->execute([$pesanan['id']]);
    $existingClaim = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($existingClaim) {
        $claimStatus = $existingClaim['status_claim'];
    }
} catch (Exception $e) {
    $existingClaim = null;
}

if ($isCompleted) {
    $canClaim = false;
    $claimMessage = '🏁 Pesanan sudah selesai. Tidak dapat mengajukan claim.';
} elseif ($isCancelled) {
    $canClaim = false;
    $claimMessage = '❌ Pesanan sudah dibatalkan.';
} elseif (!$isConfirmed) {
    $canClaim = false;
    $claimMessage = '⏳ Pesanan belum dikonfirmasi oleh supir.';
} elseif (!$isPaid) {
    $canClaim = false;
    $claimMessage = '⚠️ Pembayaran belum lunas.';
} elseif ($isDijemput) {
    $canClaim = false;
    $claimMessage = '✅ Anda sudah dijemput oleh supir.';
} elseif ($claimStatus == 'menunggu' || $claimStatus == 'pending') {
    $canClaim = false;
    $claimMessage = '⏳ Claim Anda sedang diproses. Mohon tunggu.';
} elseif ($claimStatus == 'diterima' || $claimStatus == 'approved') {
    $canClaim = false;
    $claimMessage = '✅ Claim Anda sudah diterima. Dana akan dikembalikan.';
} elseif ($claimStatus == 'ditolak' || $claimStatus == 'rejected') {
    $canClaim = false;
    $claimMessage = '❌ Claim Anda ditolak. Silakan hubungi admin.';
} else {
    // Cek apakah supir terlambat > 2 jam atau tanggal sudah lewat
    $tanggalBerangkat = new DateTime($pesanan['tanggal_berangkat']);
    $now = new DateTime();
    $isTanggalLewat = ($tanggalBerangkat < $now);
    
    $waktuJemputRencanaObj = !empty($pesanan['waktu_jemput_rencana']) 
        ? DateTime::createFromFormat('H:i:s', $pesanan['waktu_jemput_rencana']) 
        : new DateTime('08:00:00');
    
    $batasWaktuJemput = clone $tanggalBerangkat;
    $batasWaktuJemput->setTime(
        $waktuJemputRencanaObj->format('H'),
        $waktuJemputRencanaObj->format('i'),
        $waktuJemputRencanaObj->format('s')
    );
    $batasWaktuJemput->modify('+2 hours');
    
    $isTerlambat = ($now > $batasWaktuJemput);
    
    if ($isTerlambat && !$isDijemput) {
        $canClaim = true;
        $claimMessage = '⚠️ Supir terlambat lebih dari 2 jam. Anda berhak mengajukan claim.';
    } elseif ($isTanggalLewat && !$isDijemput) {
        $canClaim = true;
        $claimMessage = '⚠️ Tanggal keberangkatan sudah lewat dan Anda tidak dijemput.';
    } else {
        $canClaim = false;
        $claimMessage = '⏳ Menunggu waktu jemput. Jika supir terlambat > 2 jam, Anda bisa claim.';
    }
}

// ==============================================
// CEK APAKAH BISA RESCHEDULE
// ==============================================
$canReschedule = false;
if ($isConfirmed && $isPaid && !$isCompleted && !$isCancelled) {
    if ($pesanan['reschedule_status'] != 'menunggu' && $pesanan['reschedule_status'] != 'pending') {
        if ($pesanan['reschedule_status'] != 'disetujui' && $pesanan['reschedule_status'] != 'approved') {
            $tanggalBerangkat = new DateTime($pesanan['tanggal_berangkat']);
            $now = new DateTime();
            if ($tanggalBerangkat > $now && !$isDijemput) {
                $canReschedule = true;
            }
        }
    }
}

// ==============================================
// CEK APAKAH BISA BATALKAN
// ==============================================
$canCancel = $isPending && $claimStatus == 'tidak';

// ==============================================
// CEK APAKAH BISA SELESAIKAN
// ==============================================
$canComplete = false;
if ($isConfirmed && $isPaid && !$isCompleted && !$isCancelled) {
    if ($claimStatus != 'diterima' && $claimStatus != 'menunggu') {
        if (($pesanan['status_pencairan'] ?? '') != 'cair' && ($pesanan['status_pencairan'] ?? '') != 'proses') {
            $canComplete = true;
        }
    }
}

// Status map untuk badge
$statusMap = [
    'pending' => ['badge-warning', '⏳ Menunggu Verifikasi', 'fa-clock'],
    'confirmed' => ['badge-success', '✅ Dikonfirmasi', 'fa-check-circle'],
    'dikonfirmasi' => ['badge-success', '✅ Dikonfirmasi', 'fa-check-circle'],
    'completed' => ['badge-info', '🏁 Selesai', 'fa-flag-checkered'],
    'selesai' => ['badge-info', '🏁 Selesai', 'fa-flag-checkered'],
    'cancelled' => ['badge-danger', '❌ Dibatalkan', 'fa-times-circle'],
    'dibatalkan' => ['badge-danger', '❌ Dibatalkan', 'fa-times-circle'],
];
?>

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

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

    <main class="main-content">
        <div class="content-header">
            <div>
                <h2><i class="fas fa-file-invoice" style="color:#2b6cb0;"></i> Detail Pesanan</h2>
                <p>Detail lengkap pesanan kapal Anda.</p>
            </div>
            <div>
                <a href="?page=wisatawan&action=riwayat" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Kembali ke Riwayat
                </a>
            </div>
        </div>

        <?php if(isset($_SESSION['flash_success'])): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <?= htmlspecialchars($_SESSION['flash_success']) ?>
                <button class="alert-close" onclick="this.parentElement.remove()">&times;</button>
                <?php unset($_SESSION['flash_success']); ?>
            </div>
        <?php endif; ?>

        <?php if(isset($_SESSION['flash_error'])): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i>
                <?= htmlspecialchars($_SESSION['flash_error']) ?>
                <button class="alert-close" onclick="this.parentElement.remove()">&times;</button>
                <?php unset($_SESSION['flash_error']); ?>
            </div>
        <?php endif; ?>

        <!-- ========================================== -->
        <!-- 🔥 ALERT CLAIM -->
        <!-- ========================================== -->
        <?php if($canClaim): ?>
            <div class="alert alert-info" style="border-left-color: #3b82f6; background: #dbeafe;">
                <i class="fas fa-hand-holding-usd" style="color:#2563eb; font-size:1.5rem;"></i>
                <div>
                    <strong>⚠️ Anda Berhak Mengajukan Claim!</strong>
                    <p style="margin:0.3rem 0 0;">
                        <?= $claimMessage ?>
                    </p>
                    <a href="?page=wisatawan&action=ajukanClaim&pesanan_id=<?= $pesanan['id'] ?>" 
                       class="btn btn-danger btn-sm" style="margin-top:0.5rem; display:inline-flex; align-items:center; gap:0.3rem;">
                        <i class="fas fa-hand-holding-usd"></i> Ajukan Claim Sekarang
                    </a>
                </div>
            </div>
        <?php endif; ?>

        <!-- 🔥 ALERT CLAIM SUDAH DIAJUKAN -->
        <?php if($claimStatus == 'menunggu' || $claimStatus == 'pending'): ?>
            <div class="alert alert-warning" style="border-left-color: #f59e0b; background: #fef3c7;">
                <i class="fas fa-clock" style="color:#f59e0b; font-size:1.5rem;"></i>
                <div>
                    <strong>⏳ Claim Sedang Diproses</strong>
                    <p style="margin:0.3rem 0 0;">
                        Claim pengembalian dana Anda sedang menunggu verifikasi admin. Mohon tunggu 1x24 jam.
                    </p>
                </div>
            </div>
        <?php endif; ?>

        <?php if($claimStatus == 'diterima' || $claimStatus == 'approved'): ?>
            <div class="alert alert-success" style="border-left-color: #22c55e; background: #d1fae5;">
                <i class="fas fa-check-circle" style="color:#22c55e; font-size:1.5rem;"></i>
                <div>
                    <strong>✅ Claim Diterima!</strong>
                    <p style="margin:0.3rem 0 0;">
                        Claim Anda sudah diterima. Dana akan dikembalikan ke <strong>Saldo Aplikasi</strong> Anda.
                    </p>
                </div>
            </div>
        <?php endif; ?>

        <?php if($claimStatus == 'ditolak' || $claimStatus == 'rejected'): ?>
            <div class="alert alert-danger" style="border-left-color: #ef4444; background: #fee2e2;">
                <i class="fas fa-times-circle" style="color:#ef4444; font-size:1.5rem;"></i>
                <div>
                    <strong>❌ Claim Ditolak</strong>
                    <p style="margin:0.3rem 0 0;">
                        Claim Anda ditolak. Silakan hubungi admin untuk informasi lebih lanjut.
                    </p>
                </div>
            </div>
        <?php endif; ?>

        <!-- ========================================== -->
        <!-- STATUS BANNER -->
        <!-- ========================================== -->
        <div class="status-banner status-<?= $pesanan['status_pesanan'] ?? 'pending' ?>">
            <div class="status-banner-icon">
                <?php
                $statusIcons = [
                    'pending' => 'fa-clock',
                    'confirmed' => 'fa-check-circle',
                    'dikonfirmasi' => 'fa-check-circle',
                    'completed' => 'fa-flag-checkered',
                    'selesai' => 'fa-flag-checkered',
                    'cancelled' => 'fa-times-circle',
                    'dibatalkan' => 'fa-times-circle',
                ];
                $icon = $statusIcons[$pesanan['status_pesanan']] ?? 'fa-circle';
                ?>
                <i class="fas <?= $icon ?>"></i>
            </div>
            <div class="status-banner-content">
                <h3>
                    <?php
                    $statusLabels = [
                        'pending' => '⏳ Menunggu Verifikasi',
                        'confirmed' => '✅ Dikonfirmasi',
                        'dikonfirmasi' => '✅ Dikonfirmasi',
                        'completed' => '🏁 Selesai',
                        'selesai' => '🏁 Selesai',
                        'cancelled' => '❌ Dibatalkan',
                        'dibatalkan' => '❌ Dibatalkan',
                    ];
                    echo $statusLabels[$pesanan['status_pesanan']] ?? ucfirst($pesanan['status_pesanan']);
                    ?>
                </h3>
                <p>Kode Pesanan: <strong><?= htmlspecialchars($pesanan['kode_pesanan']) ?></strong></p>
                <p style="font-size:0.8rem; opacity:0.7; margin-top:0.2rem;">
                    <i class="fas fa-calendar-alt"></i> 
                    <?= date('d/m/Y', strtotime($pesanan['tanggal_berangkat'])) ?> 
                    <i class="fas fa-clock" style="margin-left:0.5rem;"></i> 
                    Jemput: <?= $waktuJemputRencana ?> | Selesai: <?= $waktuSelesaiRencana ?>
                </p>
            </div>
        </div>

        <!-- ========================================== -->
        <!-- INFORMASI PESANAN - LENGKAP -->
        <!-- ========================================== -->
        <div class="detail-grid">
            <!-- KIRI: Informasi Pesanan & Kapal -->
            <div class="detail-left">
                <!-- Informasi Pesanan -->
                <div class="info-card">
                    <h3><i class="fas fa-info-circle"></i> Informasi Pesanan</h3>
                    <div class="info-row">
                        <span class="info-label">Kode Pesanan</span>
                        <span class="info-value"><strong><?= htmlspecialchars($pesanan['kode_pesanan']) ?></strong></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Tanggal Pesanan</span>
                        <span class="info-value"><?= date('d/m/Y H:i', strtotime($pesanan['created_at'])) ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Tanggal Berangkat</span>
                        <span class="info-value"><?= date('d/m/Y', strtotime($pesanan['tanggal_berangkat'])) ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Durasi Sewa</span>
                        <span class="info-value"><?= $pesanan['durasi_hari'] ?? ceil(($pesanan['durasi_jam'] ?? 24) / 24) ?> hari</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Jumlah Penumpang</span>
                        <span class="info-value"><?= $pesanan['jumlah_tiket'] ?? 1 ?> orang</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Total Harga</span>
                        <span class="info-value harga">Rp <?= number_format($pesanan['total_harga'], 0, ',', '.') ?></span>
                    </div>
                    
                    <!-- ========================================== -->
                    <!-- 🔥 JENIS PEMBAYARAN - DIPERBAIKI -->
                    <!-- ========================================== -->
                    <div class="info-row">
                        <span class="info-label">Jenis Pembayaran</span>
                        <span class="info-value">
                            <span class="badge <?= $jenisInfo['badge'] ?>">
                                <?= $jenisInfo['label'] ?>
                            </span>
                            <?php if($jenisPembayaran == 'cash'): ?>
                                <span style="display:block; font-size:0.7rem; color:#065f46; margin-top:2px;">
                                    <i class="fas fa-info-circle"></i> <?= $jenisInfo['desc'] ?>
                                </span>
                            <?php endif; ?>
                        </span>
                    </div>
                    
                    <!-- ========================================== -->
                    <!-- 🔥 DETAIL PEMBAYARAN UNTUK DP / CASH -->
                    <!-- ========================================== -->
                    <?php if($jenisPembayaran == 'dp'): ?>
                        <div class="info-row" style="background: #dbeafe; padding:0.3rem 0.5rem; border-radius:4px;">
                            <span class="info-label">💰 DP Dibayar (50%)</span>
                            <span class="info-value harga">Rp <?= number_format($jumlahDibayar, 0, ',', '.') ?></span>
                        </div>
                        <div class="info-row" style="background: #fef3c7; padding:0.3rem 0.5rem; border-radius:4px;">
                            <span class="info-label">⏳ Sisa Pembayaran</span>
                            <span class="info-value text-warning">Rp <?= number_format($sisaPembayaran, 0, ',', '.') ?></span>
                        </div>
                    <?php elseif($jenisPembayaran == 'cash'): ?>
                        <div class="info-row" style="background: #d1fae5; padding:0.3rem 0.5rem; border-radius:4px;">
                            <span class="info-label">💵 Status</span>
                            <span class="info-value" style="color:#065f46; font-weight:600;">
                                <i class="fas fa-money-bill-wave"></i> Bayar Langsung ke Supir
                            </span>
                        </div>
                        <div class="info-row" style="font-size:0.75rem; color:#718096; padding:0.2rem 0.5rem;">
                            <span class="info-label"><i class="fas fa-info-circle"></i> Catatan</span>
                            <span class="info-value">Bayar langsung kepada supir saat bertemu di lokasi</span>
                        </div>
                    <?php endif; ?>
                    
                    <div class="info-row">
                        <span class="info-label">Rute Perjalanan</span>
                        <span class="info-value"><?= htmlspecialchars($pesanan['route_asal'] ?? '-') ?> → <?= htmlspecialchars($pesanan['route_tujuan'] ?? '-') ?></span>
                    </div>
                </div>

                <!-- ========================================== -->
                <!-- 🔥 WAKTU PERJALANAN - DITAMBAHKAN -->
                <!-- ========================================== -->
                <div class="info-card timeline-card" style="border-color: #93c5fd; background: #eff6ff;">
                    <h3 style="color: #1e40af;"><i class="fas fa-clock" style="color:#1e40af;"></i> Waktu Perjalanan</h3>
                    
                    <div class="info-row">
                        <span class="info-label">🕐 Waktu Jemput (Rencana)</span>
                        <span class="info-value"><strong><?= $waktuJemputRencana ?></strong></span>
                    </div>
                    
                    <div class="info-row">
                        <span class="info-label">🏁 Waktu Selesai (Rencana)</span>
                        <span class="info-value"><strong><?= $waktuSelesaiRencana ?></strong></span>
                    </div>
                    
                    <?php if($isDijemput): ?>
                        <div class="info-row" style="background: #d1fae5; padding:0.3rem 0.5rem; border-radius:4px;">
                            <span class="info-label">✅ Jemput Aktual</span>
                            <span class="info-value" style="color:#065f46; font-weight:600;">
                                <?= $waktuJemputAktual->format('d/m/Y H:i') ?>
                            </span>
                        </div>
                    <?php endif; ?>
                    
                    <?php if($waktuSelesaiAktual): ?>
                        <div class="info-row" style="background: #d1fae5; padding:0.3rem 0.5rem; border-radius:4px;">
                            <span class="info-label">🏁 Selesai Aktual</span>
                            <span class="info-value" style="color:#065f46; font-weight:600;">
                                <?= $waktuSelesaiAktual->format('d/m/Y H:i') ?>
                            </span>
                        </div>
                    <?php endif; ?>
                    
                    <div class="info-row" style="margin-top:0.3rem; border-top:1px dashed #93c5fd; padding-top:0.5rem;">
                        <span class="info-label" style="color:#1e40af; font-size:0.7rem; display:flex; align-items:center; gap:0.3rem;">
                            <i class="fas fa-info-circle"></i> 
                            Status Keberangkatan: 
                            <strong>
                                <?php 
                                $keberangkatanMap = [
                                    'menunggu' => '⏳ Menunggu Jemput',
                                    'dalam_perjalanan' => '🚐 Dalam Perjalanan',
                                    'selesai' => '🏁 Selesai'
                                ];
                                $status = $pesanan['status_keberangkatan'] ?? 'menunggu';
                                echo $keberangkatanMap[$status] ?? ucfirst($status);
                                ?>
                            </strong>
                        </span>
                    </div>
                </div>

                <!-- Informasi Kapal -->
                <div class="info-card">
                    <h3><i class="fas fa-ship"></i> Informasi Kapal</h3>
                    <div class="info-row">
                        <span class="info-label">Nama Kapal</span>
                        <span class="info-value"><strong><?= htmlspecialchars($pesanan['nama_kapal']) ?></strong></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Jenis Kapal</span>
                        <span class="info-value"><?= htmlspecialchars($pesanan['jenis_kapal'] ?? '-') ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Pemilik Kapal</span>
                        <span class="info-value"><?= htmlspecialchars($pesanan['pemilik_nama'] ?? '-') ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Kontak Pemilik</span>
                        <span class="info-value"><?= htmlspecialchars($pesanan['pemilik_hp'] ?? '-') ?></span>
                    </div>
                </div>
            </div>

            <!-- KANAN: Wisatawan & Status -->
            <div class="detail-right">
                <!-- Data Wisatawan -->
                <div class="info-card" style="border-color: #22c55e; border-left: 4px solid #22c55e;">
                    <h3><i class="fas fa-user" style="color:#22c55e;"></i> Data Wisatawan</h3>
                    <div class="info-row">
                        <span class="info-label">Nama Lengkap</span>
                        <span class="info-value"><strong><?= htmlspecialchars($pesanan['wisatawan_nama'] ?? $_SESSION['nama'] ?? '-') ?></strong></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Email</span>
                        <span class="info-value"><?= htmlspecialchars($pesanan['wisatawan_email'] ?? $_SESSION['email'] ?? '-') ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Nomor HP</span>
                        <span class="info-value"><?= htmlspecialchars($pesanan['wisatawan_hp'] ?? $_SESSION['no_hp'] ?? '-') ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">NIK KTP</span>
                        <span class="info-value"><?= htmlspecialchars($pesanan['nik_ktp'] ?? '-') ?></span>
                    </div>
                    <?php if(!empty($pesanan['catatan'])): ?>
                        <div class="info-row" style="background: #fef3c7; padding:0.3rem 0.5rem; border-radius:4px; margin-top:0.3rem;">
                            <span class="info-label">📝 Catatan / Permintaan Khusus</span>
                            <span class="info-value" style="color:#92400e; font-size:0.8rem; text-align:left; word-break:break-word;"><?= nl2br(htmlspecialchars($pesanan['catatan'])) ?></span>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Status -->
                <div class="info-card">
                    <h3><i class="fas fa-tasks"></i> Status</h3>
                    
                    <div class="info-row">
                        <span class="info-label">Status Pesanan</span>
                        <span class="info-value">
                            <?php
                            $status = $statusMap[$pesanan['status_pesanan']] ?? ['badge-secondary', ucfirst($pesanan['status_pesanan']), 'fa-circle'];
                            ?>
                            <span class="badge <?= $status[0] ?>">
                                <i class="fas <?= $status[2] ?>"></i>
                                <?= $status[1] ?>
                            </span>
                        </span>
                    </div>
                    
                    <!-- ========================================== -->
                    <!-- 🔥 STATUS PEMBAYARAN - DIPERBAIKI -->
                    <!-- ========================================== -->
                    <div class="info-row">
                        <span class="info-label">Status Pembayaran</span>
                        <span class="info-value">
                            <?php if($jenisPembayaran == 'cash'): ?>
                                <span class="badge badge-cash">
                                    <i class="fas fa-money-bill-wave"></i> Bayar di Tempat
                                </span>
                            <?php elseif($pesanan['status_pembayaran'] == 'lunas'): ?>
                                <span class="badge badge-success">
                                    <i class="fas fa-check-circle"></i> LUNAS
                                </span>
                            <?php elseif($pesanan['status_pembayaran'] == 'menunggu_konfirmasi'): ?>
                                <span class="badge badge-warning">
                                    <i class="fas fa-clock"></i> Menunggu Konfirmasi
                                </span>
                            <?php elseif($pesanan['status_pembayaran'] == 'belum_bayar'): ?>
                                <span class="badge badge-warning">
                                    <i class="fas fa-clock"></i> Belum Bayar
                            </span>
                            <?php else: ?>
                                <span class="badge badge-secondary">
                                    <?= ucfirst(str_replace('_', ' ', $pesanan['status_pembayaran'])) ?>
                                </span>
                            <?php endif; ?>
                        </span>
                    </div>
                    
                    <!-- ========================================== -->
                    <!-- 🔥 RINGKASAN PEMBAYARAN UNTUK CASH -->
                    <!-- ========================================== -->
                    <?php if($jenisPembayaran == 'cash'): ?>
                        <div class="info-row" style="background: #d1fae5; padding:0.3rem 0.5rem; border-radius:4px; margin-top:0.3rem;">
                            <span class="info-label" style="color:#065f46;">💵 Metode</span>
                            <span class="info-value" style="color:#065f46; font-weight:600;">Bayar Langsung ke Supir</span>
                        </div>
                    <?php endif; ?>
                    
                    <!-- ========================================== -->
                    <!-- 🔥 SISA PEMBAYARAN UNTUK DP -->
                    <!-- ========================================== -->
                    <?php if($jenisPembayaran == 'dp' && $sisaPembayaran > 0): ?>
                        <div class="info-row" style="background: #fef3c7; padding:0.3rem 0.5rem; border-radius:4px; margin-top:0.3rem;">
                            <span class="info-label" style="color:#92400e;">⏳ Sisa Pembayaran</span>
                            <span class="info-value" style="color:#92400e; font-weight:600;">
                                Rp <?= number_format($sisaPembayaran, 0, ',', '.') ?>
                            </span>
                        </div>
                    <?php endif; ?>
                    
                    <div class="info-row">
                        <span class="info-label">Status Claim</span>
                        <span class="info-value">
                            <?php
                            $claimMap = [
                                'tidak' => ['badge-secondary', 'Tidak Ada', 'fa-circle'],
                                'menunggu' => ['badge-warning', '⏳ Menunggu', 'fa-clock'],
                                'pending' => ['badge-warning', '⏳ Menunggu', 'fa-clock'],
                                'diterima' => ['badge-success', '✅ Dana Dikembalikan', 'fa-check-circle'],
                                'approved' => ['badge-success', '✅ Dana Dikembalikan', 'fa-check-circle'],
                                'ditolak' => ['badge-danger', '❌ Ditolak', 'fa-times-circle'],
                                'rejected' => ['badge-danger', '❌ Ditolak', 'fa-times-circle'],
                            ];
                            $claim = $claimMap[$claimStatus] ?? ['badge-secondary', 'Tidak Ada', 'fa-circle'];
                            ?>
                            <span class="badge <?= $claim[0] ?>">
                                <i class="fas <?= $claim[2] ?>"></i>
                                <?= $claim[1] ?>
                            </span>
                        </span>
                    </div>
                    
                    <?php if($claimStatus == 'menunggu' || $claimStatus == 'pending'): ?>
                        <div class="info-row">
                            <span class="info-label">Alasan Claim</span>
                            <span class="info-value"><?= htmlspecialchars($pesanan['alasan_claim'] ?? '-') ?></span>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Status Keberangkatan -->
                    <?php if(!empty($pesanan['status_keberangkatan'])): ?>
                    <div class="info-row">
                        <span class="info-label">Status Keberangkatan</span>
                        <span class="info-value">
                            <?php
                            $keberangkatanMap = [
                                'menunggu' => ['badge-warning', '⏳ Menunggu Jemput', 'fa-clock'],
                                'dalam_perjalanan' => ['badge-info', '🚐 Dalam Perjalanan', 'fa-ship'],
                                'selesai' => ['badge-success', '🏁 Selesai', 'fa-flag-checkered'],
                            ];
                            $keberangkatan = $keberangkatanMap[$pesanan['status_keberangkatan']] ?? ['badge-secondary', ucfirst($pesanan['status_keberangkatan']), 'fa-circle'];
                            ?>
                            <span class="badge <?= $keberangkatan[0] ?>">
                                <i class="fas <?= $keberangkatan[2] ?>"></i>
                                <?= $keberangkatan[1] ?>
                            </span>
                        </span>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- ========================================== -->
                <!-- 🔥 RINGKASAN PEMBAYARAN - LENGKAP -->
                <!-- ========================================== -->
                <div class="info-card" style="border-color: #a0aec0; background: #f7fafc;">
                    <h3><i class="fas fa-credit-card" style="color:#718096;"></i> Ringkasan Pembayaran</h3>
                    <div class="info-row">
                        <span class="info-label">Total Harga</span>
                        <span class="info-value harga">Rp <?= number_format($pesanan['total_harga'], 0, ',', '.') ?></span>
                    </div>
                    
                    <?php if(!empty($pesanan['metode_pembayaran'])): ?>
                    <div class="info-row">
                        <span class="info-label">Metode Pembayaran</span>
                        <span class="info-value"><?= htmlspecialchars($pesanan['metode_pembayaran']) ?></span>
                    </div>
                    <?php endif; ?>
                    
                    <?php if(!empty($pesanan['tanggal_bayar'])): ?>
                    <div class="info-row">
                        <span class="info-label">Tanggal Bayar</span>
                        <span class="info-value"><?= date('d/m/Y H:i', strtotime($pesanan['tanggal_bayar'])) ?></span>
                    </div>
                    <?php endif; ?>
                    
                    <!-- ========================================== -->
                    <!-- 🔥 TAMPILAN UNTUK CASH -->
                    <!-- ========================================== -->
                    <?php if($jenisPembayaran == 'cash'): ?>
                        <div class="info-row" style="background: #d1fae5; padding:0.3rem 0.5rem; border-radius:4px; margin-top:0.3rem;">
                            <span class="info-label" style="color:#065f46;">💵 Status</span>
                            <span class="info-value" style="color:#065f46; font-weight:600;">
                                <i class="fas fa-money-bill-wave"></i> Bayar di Tempat
                            </span>
                        </div>
                        <div class="info-row" style="font-size:0.75rem; color:#718096; padding:0.2rem 0.5rem;">
                            <span class="info-label"><i class="fas fa-info-circle"></i> Catatan</span>
                            <span class="info-value">Bayar langsung kepada supir saat bertemu di lokasi</span>
                        </div>
                    <?php endif; ?>
                    
                    <!-- ========================================== -->
                    <!-- 🔥 TAMPILAN UNTUK DP -->
                    <!-- ========================================== -->
                    <?php if($jenisPembayaran == 'dp' && $sisaPembayaran > 0): ?>
                        <div class="info-row" style="background: #fef3c7; padding:0.3rem 0.5rem; border-radius:4px; margin-top:0.3rem;">
                            <span class="info-label">⏳ Sisa Pembayaran</span>
                            <span class="info-value text-warning">Rp <?= number_format($sisaPembayaran, 0, ',', '.') ?></span>
                        </div>
                    <?php endif; ?>
                    
                    <?php if($pesanan['status_pembayaran'] == 'lunas'): ?>
                        <div class="info-row" style="background: #d1fae5; padding:0.3rem 0.5rem; border-radius:4px; margin-top:0.3rem;">
                            <span class="info-label">✅ Status</span>
                            <span class="info-value" style="color:#065f46; font-weight:600;">Pembayaran Lunas</span>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- ========================================== -->
        <!-- 🔥 ACTION SECTION - TOMBOL AKSI LENGKAP -->
        <!-- ========================================== -->
        <div class="action-section" style="margin-top: 1.5rem; padding-top: 1rem; border-top: 2px solid #e2e8f0; display: flex; gap: 0.8rem; flex-wrap: wrap;">

            <!-- 🔥 TOMBOL BATALKAN (hanya jika pending) -->
            <?php if($canCancel): ?>
                <a href="?page=wisatawan&action=formBatalPesanan&id=<?= $pesanan['id'] ?>" 
                   class="btn btn-danger">
                    <i class="fas fa-times"></i> Batalkan Pesanan
                </a>
            <?php endif; ?>

            <!-- 🔥 TOMBOL AJUKAN CLAIM (jika bisa claim) -->
            <?php if($canClaim): ?>
                <a href="?page=wisatawan&action=ajukanClaim&pesanan_id=<?= $pesanan['id'] ?>" 
                   class="btn btn-danger">
                    <i class="fas fa-hand-holding-usd"></i> Ajukan Claim
                </a>
            <?php endif; ?>

            <!-- 🔥 TOMBOL UBAH JADWAL -->
            <?php if($canReschedule): ?>
                <a href="?page=wisatawan&action=reschedule&id=<?= $pesanan['id'] ?>" 
                   class="btn btn-warning">
                    <i class="fas fa-calendar-alt"></i> Ubah Jadwal
                </a>
            <?php endif; ?>

            <!-- 🔥 TOMBOL SELESAIKAN PERJALANAN -->
            <?php if($canComplete): ?>
                <form method="POST" action="?page=wisatawan&action=selesaikanPerjalanan" style="display:inline-block;">
                    <input type="hidden" name="pesanan_id" value="<?= $pesanan['id'] ?>">
                    <button type="submit" class="btn btn-success" 
                            onclick="return confirm('Yakin perjalanan sudah selesai?')">
                        <i class="fas fa-flag-checkered"></i> Selesaikan Perjalanan
                    </button>
                </form>
            <?php endif; ?>

            <!-- Tombol Kembali -->
            <a href="?page=wisatawan&action=riwayat" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Kembali ke Riwayat
            </a>
        </div>

        <!-- ========================================== -->
        <!-- NOTIFICATIONS -->
        <!-- ========================================== -->
        <?php if(!empty($notifications)): ?>
        <div class="info-card" style="margin-top:1.5rem;">
            <h3><i class="fas fa-bell"></i> Riwayat Notifikasi</h3>
            <div class="notification-list">
                <?php foreach($notifications as $notif): ?>
                <div class="notification-item">
                    <div class="notif-icon">
                        <i class="fas fa-<?= strpos($notif['title'] ?? '', '✅') !== false ? 'check-circle' : 
                                        (strpos($notif['title'] ?? '', '❌') !== false ? 'times-circle' : 
                                        (strpos($notif['title'] ?? '', '📋') !== false ? 'clipboard-list' : 'bell')) ?>"></i>
                    </div>
                    <div class="notif-content">
                        <div class="notif-title"><?= htmlspecialchars($notif['title'] ?? 'Notifikasi') ?></div>
                        <div class="notif-message"><?= htmlspecialchars($notif['message'] ?? '') ?></div>
                        <div class="notif-time"><?= date('d/m/Y H:i', strtotime($notif['created_at'] ?? 'now')) ?></div>
                    </div>
                    <?php if(empty($notif['is_read'])): ?>
                    <div class="notif-status">
                        <span class="badge badge-warning">Baru</span>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

    </main>
</div>

<script>
// ==========================================
// KONFIRMASI SELESAIKAN PERJALANAN
// ==========================================
function confirmSelesaikan() {
    return confirm(
        '⚠️ Konfirmasi Selesaikan Perjalanan\n\n' +
        '📌 Apakah Anda yakin ingin menyelesaikan perjalanan ini?\n\n' +
        '✅ Kapal: <?= htmlspecialchars($pesanan['nama_kapal']) ?>\n' +
        '📅 Tanggal: <?= date('d/m/Y', strtotime($pesanan['tanggal_berangkat'])) ?>\n' +
        '💰 Total: Rp <?= number_format($pesanan['total_harga'], 0, ',', '.') ?>\n\n' +
        '⚠️ Setelah diselesaikan:\n' +
        '• Dana akan dicairkan ke supir\n' +
        '• Anda tidak dapat mengajukan claim lagi\n' +
        '• Status perjalanan menjadi SELESAI'
    );
}
</script>

<style>
/* ============================================
   LAYOUT
   ============================================ */
.dashboard-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 {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
    flex-wrap: wrap;
    gap: 10px;
}

.content-header h2 {
    font-size: 1.4rem;
    font-weight: 700;
    color: #1a202c;
    margin: 0;
}

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

.alert {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    padding: 0.8rem 1.2rem;
    border-radius: 10px;
    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-warning {
    background: #fffbeb;
    color: #92400e;
    border-left-color: #f59e0b;
}

.alert-info {
    background: #dbeafe;
    color: #1e40af;
    border-left-color: #3b82f6;
}

.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; }

.status-banner {
    display: flex;
    align-items: center;
    gap: 1.2rem;
    padding: 1rem 1.5rem;
    border-radius: 12px;
    margin-bottom: 1.5rem;
    border: 2px solid;
}

.status-banner.status-pending {
    background: #fef3c7;
    border-color: #f59e0b;
}

.status-banner.status-confirmed,
.status-banner.status-dikonfirmasi {
    background: #d1fae5;
    border-color: #22c55e;
}

.status-banner.status-completed,
.status-banner.status-selesai {
    background: #dbeafe;
    border-color: #3b82f6;
}

.status-banner.status-cancelled,
.status-banner.status-dibatalkan {
    background: #fee2e2;
    border-color: #ef4444;
}

.status-banner-icon {
    font-size: 2.5rem;
    color: inherit;
}

.status-banner-content h3 {
    font-size: 1.1rem;
    font-weight: 700;
    margin: 0;
}

.status-banner-content p {
    margin: 0.1rem 0 0;
    font-size: 0.9rem;
    opacity: 0.8;
}

.detail-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1.5rem;
}

.info-card {
    background: #fff;
    border-radius: 12px;
    padding: 1.2rem 1.5rem;
    border: 1px solid #e2e8f0;
    margin-bottom: 1.5rem;
}

.info-card h3 {
    font-size: 1rem;
    font-weight: 700;
    color: #2d3748;
    margin-bottom: 0.8rem;
    padding-bottom: 0.5rem;
    border-bottom: 1px solid #e2e8f0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.info-row {
    display: flex;
    justify-content: space-between;
    padding: 0.3rem 0;
    border-bottom: 1px solid #f7fafc;
}

.info-row:last-child { border-bottom: none; }

.info-label {
    color: #718096;
    font-size: 0.8rem;
    font-weight: 500;
}

.info-value {
    font-size: 0.85rem;
    color: #1a202c;
    text-align: right;
    max-width: 60%;
    word-break: break-word;
}

.info-value.harga {
    font-weight: 700;
    color: #2b6cb0;
    font-size: 1rem;
}

.text-warning { color: #f59e0b; }

/* ============================================
   BADGE - TERMASUK CASH
   ============================================ */
.badge {
    display: inline-flex;
    align-items: center;
    gap: 0.2rem;
    padding: 0.15rem 0.6rem;
    border-radius: 20px;
    font-size: 0.65rem;
    font-weight: 600;
}

.badge-success {
    background: #d1fae5;
    color: #065f46;
}

.badge-danger {
    background: #fee2e2;
    color: #991b1b;
}

.badge-warning {
    background: #fef3c7;
    color: #92400e;
}

.badge-secondary {
    background: #e5e7eb;
    color: #4b5563;
}

.badge-info {
    background: #dbeafe;
    color: #1e40af;
}

.badge-cash {
    background: #d1fae5;
    color: #065f46;
    border: 1px solid #86efac;
}

/* ============================================
   BUTTONS
   ============================================ */
.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-success {
    background: #22c55e;
    color: #fff;
}
.btn-success:hover { background: #16a34a; color: #fff; }

.btn-danger {
    background: #ef4444;
    color: #fff;
}
.btn-danger:hover { background: #dc2626; color: #fff; }

.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-warning {
    background: #f59e0b;
    color: #fff;
}
.btn-warning:hover { background: #d97706; color: #fff; }

.action-section {
    display: flex;
    gap: 0.8rem;
    flex-wrap: wrap;
}

.notification-list {
    max-height: 300px;
    overflow-y: auto;
}

.notification-item {
    display: flex;
    gap: 0.8rem;
    padding: 0.6rem 0;
    border-bottom: 1px solid #f7fafc;
}

.notification-item:last-child { border-bottom: none; }

.notif-icon {
    font-size: 1.2rem;
    flex-shrink: 0;
    margin-top: 0.1rem;
}

.notif-content {
    flex: 1;
}

.notif-title {
    font-weight: 600;
    font-size: 0.85rem;
    color: #1a202c;
}

.notif-message {
    font-size: 0.8rem;
    color: #4a5568;
    white-space: pre-wrap;
    word-break: break-word;
}

.notif-time {
    font-size: 0.65rem;
    color: #a0aec0;
    margin-top: 0.1rem;
}

/* ============================================
   RESPONSIVE
   ============================================ */
@media (max-width: 768px) {
    .dashboard-wrapper {
        flex-direction: column;
        padding: 0 12px;
        margin-top: 1rem;
    }
    .main-content {
        padding: 1rem;
    }
    .detail-grid {
        grid-template-columns: 1fr;
    }
    .content-header {
        flex-direction: column;
        align-items: flex-start;
    }
    .action-section {
        flex-direction: column;
    }
    .action-section .btn {
        width: 100%;
        justify-content: center;
    }
    .info-row {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.1rem;
    }
    .info-value {
        text-align: left;
        max-width: 100%;
    }
    .status-banner {
        flex-direction: column;
        text-align: center;
        padding: 1rem;
    }
}

@media (max-width: 480px) {
    .main-content {
        padding: 0.8rem;
    }
    .info-card {
        padding: 0.8rem 1rem;
    }
}
</style>

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