<?php
/**
 * riwayat_pesanan.php - Halaman Riwayat Pesanan Wisatawan
 * VERSI TERBARU - Desain Card Premium dengan Fitur Pembatalan
 * DITAMBAHKAN - Tombol Batalkan untuk semua status (pending & confirmed)
 */
$activeMenu = 'riwayatPesanan';
$pageTitle = 'Riwayat Pesanan - Wisatawan';
include __DIR__ . '/../layouts/header.php';

// ==============================================
// DATA DARI CONTROLLER
// ==============================================
$pesanan = $pesanan ?? [];
$user = $user ?? null;
$unreadCount = $unreadCount ?? 0;
$claimTableExists = $claimTableExists ?? false;
$user_id = $user_id ?? $_SESSION['user_id'] ?? 0;
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Riwayat Pesanan - Wisatawan</title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <style>
        /* ============================================
           ROOT VARIABLES
           ============================================ */
        :root {
            --primary: #2b6cb0;
            --primary-light: #4299e1;
            --primary-dark: #1a4a7a;
            --primary-bg: #ebf4ff;
            --success: #22c55e;
            --success-bg: #d1fae5;
            --warning: #f59e0b;
            --warning-bg: #fef3c7;
            --danger: #ef4444;
            --danger-bg: #fee2e2;
            --info: #3b82f6;
            --info-bg: #dbeafe;
            --purple: #8b5cf6;
            --purple-bg: #ede9fe;
            --gray-50: #f7fafc;
            --gray-100: #edf2f7;
            --gray-200: #e2e8f0;
            --gray-300: #cbd5e0;
            --gray-400: #a0aec0;
            --gray-500: #718096;
            --gray-600: #4a5568;
            --gray-700: #2d3748;
            --gray-800: #1a202c;
            --gray-900: #171923;
            --shadow: 0 4px 20px rgba(0,0,0,0.06);
            --shadow-lg: 0 10px 40px rgba(0,0,0,0.1);
            --shadow-hover: 0 8px 30px rgba(0,0,0,0.12);
            --radius: 16px;
            --radius-sm: 10px;
            --transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: #f7fafc;
            color: var(--gray-800);
            line-height: 1.6;
        }

        /* ============================================
           DASHBOARD WRAPPER
           ============================================ */
        .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: #ffffff;
            border-radius: var(--radius);
            padding: 1.8rem;
            box-shadow: var(--shadow);
            border: 1px solid var(--gray-200);
            animation: fadeInUp 0.5s ease;
        }

        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* ============================================
           HEADER
           ============================================ */
        .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid var(--gray-100);
        }

        .content-header-left h2 {
            font-size: 1.5rem;
            font-weight: 800;
            color: var(--gray-900);
            display: flex;
            align-items: center;
            gap: 0.6rem;
        }

        .content-header-left h2 i {
            color: var(--primary);
            background: var(--primary-bg);
            padding: 0.4rem;
            border-radius: var(--radius-sm);
        }

        .content-header-left p {
            color: var(--gray-500);
            font-size: 0.9rem;
            margin-top: 0.2rem;
        }

        .header-actions {
            display: flex;
            gap: 0.6rem;
            flex-wrap: wrap;
        }

        /* ============================================
           BUTTONS
           ============================================ */
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1.2rem;
            border: none;
            border-radius: var(--radius-sm);
            font-weight: 600;
            font-size: 0.85rem;
            cursor: pointer;
            transition: var(--transition);
            text-decoration: none;
            font-family: inherit;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-lg);
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            color: #fff;
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, var(--primary-dark), #0d2b4f);
            color: #fff;
        }

        .btn-success {
            background: linear-gradient(135deg, var(--success), #16a34a);
            color: #fff;
        }

        .btn-success:hover {
            background: linear-gradient(135deg, #16a34a, #0d7a3a);
            color: #fff;
        }

        .btn-danger {
            background: linear-gradient(135deg, var(--danger), #dc2626);
            color: #fff;
        }

        .btn-danger:hover {
            background: linear-gradient(135deg, #dc2626, #b91c1c);
            color: #fff;
        }

        .btn-warning {
            background: linear-gradient(135deg, var(--warning), #d97706);
            color: #fff;
        }

        .btn-warning:hover {
            background: linear-gradient(135deg, #d97706, #b45309);
            color: #fff;
        }

        .btn-outline {
            background: transparent;
            color: var(--gray-600);
            border: 2px solid var(--gray-200);
        }

        .btn-outline:hover {
            background: var(--gray-50);
            border-color: var(--gray-400);
        }

        .btn-sm {
            padding: 0.3rem 0.8rem;
            font-size: 0.75rem;
        }

        .btn-xs {
            padding: 0.2rem 0.6rem;
            font-size: 0.65rem;
        }

        /* ============================================
           ALERT
           ============================================ */
        .alert {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 0.8rem 1.2rem;
            border-radius: var(--radius-sm);
            margin-bottom: 1rem;
            border-left: 4px solid transparent;
            animation: slideDown 0.4s ease;
        }

        @keyframes slideDown {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .alert-success {
            background: var(--success-bg);
            color: #065f46;
            border-left-color: var(--success);
        }

        .alert-danger {
            background: var(--danger-bg);
            color: #991b1b;
            border-left-color: var(--danger);
        }

        .alert-warning {
            background: var(--warning-bg);
            color: #92400e;
            border-left-color: var(--warning);
        }

        .alert-info {
            background: var(--info-bg);
            color: #1e40af;
            border-left-color: var(--info);
        }

        .alert-close {
            margin-left: auto;
            background: none;
            border: none;
            font-size: 1.2rem;
            cursor: pointer;
            color: inherit;
            opacity: 0.5;
            padding: 0 4px;
            transition: var(--transition);
        }

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

        /* ============================================
           EMPTY STATE
           ============================================ */
        .empty-state {
            text-align: center;
            padding: 3rem 2rem;
            background: var(--gray-50);
            border-radius: var(--radius);
            border: 2px dashed var(--gray-200);
        }

        .empty-state .empty-icon {
            font-size: 4rem;
            display: block;
            margin-bottom: 0.5rem;
        }

        .empty-state h3 {
            font-size: 1.3rem;
            font-weight: 700;
            color: var(--gray-800);
            margin-bottom: 0.3rem;
        }

        .empty-state p {
            color: var(--gray-500);
            font-size: 0.95rem;
            max-width: 400px;
            margin: 0 auto 1rem;
        }

        /* ============================================
           CARD GRID
           ============================================ */
        .order-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 1.2rem;
            margin-top: 0.5rem;
        }

        .order-card {
            background: #fff;
            border-radius: var(--radius);
            border: 1px solid var(--gray-200);
            overflow: hidden;
            transition: var(--transition);
            position: relative;
        }

        .order-card:hover {
            box-shadow: var(--shadow-hover);
            transform: translateY(-2px);
            border-color: var(--primary-light);
        }

        .order-card .order-header {
            padding: 1rem 1.5rem;
            background: var(--gray-50);
            border-bottom: 1px solid var(--gray-200);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 0.5rem;
        }

        .order-card .order-header .order-code {
            font-weight: 700;
            color: var(--primary);
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 0.4rem;
        }

        .order-card .order-header .order-code i {
            color: var(--primary);
        }

        .order-card .order-header .order-date {
            font-size: 0.8rem;
            color: var(--gray-500);
        }

        .order-card .order-body {
            padding: 1.2rem 1.5rem;
            display: flex;
            gap: 1.5rem;
            flex-wrap: wrap;
        }

        .order-card .order-body .order-image {
            width: 100px;
            height: 100px;
            border-radius: var(--radius-sm);
            overflow: hidden;
            flex-shrink: 0;
            background: var(--gray-100);
            border: 1px solid var(--gray-200);
        }

        .order-card .order-body .order-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .order-card .order-body .order-image .no-image {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2.5rem;
            color: var(--gray-400);
        }

        .order-card .order-body .order-info {
            flex: 1;
            min-width: 200px;
        }

        .order-card .order-body .order-info .order-title {
            font-size: 1.1rem;
            font-weight: 700;
            color: var(--gray-900);
            margin-bottom: 0.3rem;
        }

        .order-card .order-body .order-info .order-meta {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
            gap: 0.3rem 1rem;
            margin: 0.5rem 0;
        }

        .order-card .order-body .order-info .order-meta .meta-item {
            display: flex;
            align-items: center;
            gap: 0.4rem;
            font-size: 0.8rem;
            color: var(--gray-600);
        }

        .order-card .order-body .order-info .order-meta .meta-item i {
            width: 16px;
            color: var(--primary);
            font-size: 0.7rem;
        }

        .order-card .order-body .order-info .order-price {
            font-size: 1.2rem;
            font-weight: 800;
            color: var(--primary);
            margin: 0.3rem 0;
        }

        .order-card .order-body .order-status {
            flex-shrink: 0;
            min-width: 120px;
            display: flex;
            flex-direction: column;
            gap: 0.3rem;
            align-items: flex-end;
        }

        /* ============================================
           BADGE
           ============================================ */
        .badge {
            display: inline-flex;
            align-items: center;
            gap: 0.3rem;
            padding: 0.2rem 0.8rem;
            border-radius: 20px;
            font-size: 0.7rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }

        .badge-success {
            background: var(--success-bg);
            color: #065f46;
        }

        .badge-danger {
            background: var(--danger-bg);
            color: #991b1b;
        }

        .badge-warning {
            background: var(--warning-bg);
            color: #92400e;
        }

        .badge-info {
            background: var(--info-bg);
            color: #1e40af;
        }

        .badge-purple {
            background: var(--purple-bg);
            color: var(--purple);
        }

        .badge-secondary {
            background: var(--gray-200);
            color: var(--gray-600);
        }

        .badge-payment {
            font-size: 0.6rem;
            padding: 0.1rem 0.5rem;
            border-radius: 12px;
        }

        .badge-payment-lunas {
            background: var(--success-bg);
            color: #065f46;
        }

        .badge-payment-menunggu {
            background: var(--warning-bg);
            color: #92400e;
        }

        .badge-payment-belum {
            background: var(--gray-200);
            color: var(--gray-600);
        }

        /* ============================================
           ORDER FOOTER
           ============================================ */
        .order-card .order-footer {
            padding: 0.8rem 1.5rem;
            background: var(--gray-50);
            border-top: 1px solid var(--gray-200);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 0.5rem;
        }

        .order-card .order-footer .order-actions {
            display: flex;
            gap: 0.4rem;
            flex-wrap: wrap;
        }

        .order-card .order-footer .order-actions .btn {
            font-size: 0.7rem;
            padding: 0.25rem 0.8rem;
        }

        .order-card .order-footer .order-timeline {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.7rem;
            color: var(--gray-500);
        }

        .order-card .order-footer .order-timeline .dot {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: var(--gray-300);
        }

        .order-card .order-footer .order-timeline .dot.active {
            background: var(--success);
        }

        .order-card .order-footer .order-timeline .dot.warning {
            background: var(--warning);
        }

        /* ============================================
           MODAL CANCEL
           ============================================ */
        .modal-overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.5);
            backdrop-filter: blur(4px);
            z-index: 9999;
            align-items: center;
            justify-content: center;
            animation: fadeIn 0.3s ease;
        }

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

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .modal-box {
            background: #fff;
            border-radius: var(--radius);
            padding: 2rem;
            max-width: 450px;
            width: 90%;
            box-shadow: var(--shadow-lg);
            animation: scaleIn 0.3s ease;
        }

        @keyframes scaleIn {
            from { transform: scale(0.9); opacity: 0; }
            to { transform: scale(1); opacity: 1; }
        }

        .modal-box .modal-icon {
            text-align: center;
            font-size: 3rem;
            margin-bottom: 0.5rem;
        }

        .modal-box h3 {
            text-align: center;
            font-size: 1.2rem;
            font-weight: 700;
            color: var(--gray-900);
            margin-bottom: 0.3rem;
        }

        .modal-box p {
            text-align: center;
            color: var(--gray-500);
            font-size: 0.9rem;
            margin-bottom: 1.2rem;
        }

        .modal-box .modal-actions {
            display: flex;
            gap: 0.8rem;
            justify-content: center;
        }

        .modal-box .modal-actions .btn {
            min-width: 100px;
            justify-content: center;
        }

        .modal-box .modal-reason {
            width: 100%;
            padding: 0.6rem 0.8rem;
            border: 1.5px solid var(--gray-200);
            border-radius: var(--radius-sm);
            font-size: 0.85rem;
            font-family: inherit;
            resize: vertical;
            min-height: 60px;
            margin-bottom: 1rem;
            transition: var(--transition);
        }

        .modal-box .modal-reason:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 3px rgba(43, 108, 176, 0.1);
        }

        /* ============================================
           STATS MINI
           ============================================ */
        .stats-mini {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
            gap: 0.8rem;
            margin-bottom: 1.5rem;
        }

        .stat-mini-item {
            background: #fff;
            padding: 0.6rem 0.8rem;
            border-radius: var(--radius-sm);
            border: 1px solid var(--gray-200);
            text-align: center;
            transition: var(--transition);
        }

        .stat-mini-item:hover {
            border-color: var(--primary);
            transform: translateY(-2px);
            box-shadow: var(--shadow);
        }

        .stat-mini-number {
            font-size: 1.2rem;
            font-weight: 700;
            display: block;
            line-height: 1.2;
            color: var(--gray-900);
        }

        .stat-mini-label {
            font-size: 0.65rem;
            color: var(--gray-500);
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }

        /* ============================================
           TOAST
           ============================================ */
        #toastContainer {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 99999;
            max-width: 400px;
        }

        .toast-item {
            background: white;
            padding: 12px 16px;
            margin-bottom: 10px;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.15);
            animation: slideInRight 0.4s ease;
            font-family: 'Inter', sans-serif;
            font-size: 14px;
            color: #1a202c;
            display: flex;
            align-items: center;
            gap: 10px;
            border-left: 4px solid #3b82f6;
        }

        .toast-item.success { border-left-color: #22c55e; }
        .toast-item.error { border-left-color: #ef4444; }
        .toast-item.warning { border-left-color: #f59e0b; }
        .toast-item.info { border-left-color: #3b82f6; }

        @keyframes slideInRight {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        @keyframes slideOutRight {
            from { transform: translateX(0); opacity: 1; }
            to { transform: translateX(100%); opacity: 0; }
        }

        /* ============================================
           RESPONSIVE
           ============================================ */
        @media (max-width: 768px) {
            .dashboard-wrapper {
                flex-direction: column;
                padding: 0 12px;
                margin-top: 1rem;
            }

            .main-content {
                padding: 1rem;
            }

            .content-header {
                flex-direction: column;
                align-items: flex-start;
            }

            .header-actions {
                width: 100%;
            }

            .header-actions .btn {
                flex: 1;
                justify-content: center;
            }

            .order-card .order-body {
                flex-direction: column;
                align-items: flex-start;
            }

            .order-card .order-body .order-image {
                width: 100%;
                height: 150px;
            }

            .order-card .order-status {
                align-items: flex-start;
                width: 100%;
            }

            .order-card .order-footer {
                flex-direction: column;
                align-items: flex-start;
            }

            .order-card .order-footer .order-actions {
                width: 100%;
            }

            .order-card .order-footer .order-actions .btn {
                flex: 1;
                justify-content: center;
            }

            .modal-box {
                padding: 1.5rem;
            }

            .modal-box .modal-actions {
                flex-direction: column;
            }

            .modal-box .modal-actions .btn {
                width: 100%;
            }

            .stats-mini {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 480px) {
            .main-content {
                padding: 0.8rem;
            }

            .order-card .order-header {
                padding: 0.6rem 1rem;
            }

            .order-card .order-body {
                padding: 0.8rem 1rem;
            }

            .order-card .order-footer {
                padding: 0.6rem 1rem;
            }

            .order-card .order-body .order-info .order-meta {
                grid-template-columns: 1fr;
            }

            .stats-mini {
                grid-template-columns: 1fr 1fr;
                gap: 0.5rem;
            }

            .stat-mini-number {
                font-size: 1rem;
            }
        }
    </style>
</head>
<body>

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

    <main class="main-content">
        <!-- HEADER -->
        <div class="content-header">
            <div class="content-header-left">
                <h2>
                    <i class="fas fa-history"></i>
                    Riwayat Pesanan
                </h2>
                <p>
                    <i class="fas fa-ship"></i> 
                    Daftar semua pesanan kapal yang pernah Anda booking
                </p>
            </div>
            <div class="header-actions">
                <a href="?page=wisatawan&action=booking" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Booking Baru
                </a>
            </div>
        </div>

        <!-- ALERT MESSAGES -->
        <?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; ?>

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

        <?php if(empty($pesanan)): ?>
            <!-- EMPTY STATE -->
            <div class="empty-state">
                <span class="empty-icon">📭</span>
                <h3>Belum Ada Pesanan</h3>
                <p>Anda belum melakukan pemesanan kapal. Silakan booking kapal sekarang!</p>
                <a href="?page=wisatawan&action=booking" class="btn btn-primary">
                    <i class="fas fa-ship"></i> Booking Sekarang
                </a>
            </div>
        <?php else: ?>
            <!-- STATS MINI -->
            <?php 
                $totalOrders = count($pesanan);
                $pendingOrders = 0;
                $confirmedOrders = 0;
                $completedOrders = 0;
                $cancelledOrders = 0;
                
                foreach($pesanan as $p) {
                    $status = $p['status_pesanan'] ?? '';
                    if(in_array($status, ['pending', 'menunggu'])) $pendingOrders++;
                    elseif(in_array($status, ['confirmed', 'dikonfirmasi'])) $confirmedOrders++;
                    elseif(in_array($status, ['selesai', 'completed'])) $completedOrders++;
                    elseif(in_array($status, ['dibatalkan', 'cancelled'])) $cancelledOrders++;
                }
            ?>
            <div class="stats-mini">
                <div class="stat-mini-item">
                    <span class="stat-mini-number"><?= $totalOrders ?></span>
                    <span class="stat-mini-label">Total Pesanan</span>
                </div>
                <div class="stat-mini-item" style="border-left:3px solid var(--warning);">
                    <span class="stat-mini-number" style="color:#92400e;"><?= $pendingOrders ?></span>
                    <span class="stat-mini-label">Menunggu</span>
                </div>
                <div class="stat-mini-item" style="border-left:3px solid var(--info);">
                    <span class="stat-mini-number" style="color:#1e40af;"><?= $confirmedOrders ?></span>
                    <span class="stat-mini-label">Dikonfirmasi</span>
                </div>
                <div class="stat-mini-item" style="border-left:3px solid var(--success);">
                    <span class="stat-mini-number" style="color:#065f46;"><?= $completedOrders ?></span>
                    <span class="stat-mini-label">Selesai</span>
                </div>
                <div class="stat-mini-item" style="border-left:3px solid var(--danger);">
                    <span class="stat-mini-number" style="color:#991b1b;"><?= $cancelledOrders ?></span>
                    <span class="stat-mini-label">Dibatalkan</span>
                </div>
            </div>

            <!-- ORDER CARDS -->
            <div class="order-grid">
                <?php foreach($pesanan as $p): 
                    // Status Pesanan
                    $status = $p['status_pesanan'] ?? 'pending';
                    $statusMap = [
                        'dikonfirmasi' => ['badge-success', 'Dikonfirmasi', 'fa-check-circle'],
                        'confirmed' => ['badge-success', 'Dikonfirmasi', 'fa-check-circle'],
                        'selesai' => ['badge-success', 'Selesai', 'fa-check-double'],
                        'completed' => ['badge-success', 'Selesai', 'fa-check-double'],
                        'menunggu' => ['badge-warning', 'Menunggu', 'fa-clock'],
                        'pending' => ['badge-warning', 'Menunggu', 'fa-clock'],
                        'berjalan' => ['badge-info', 'Berjalan', 'fa-ship'],
                        'ditolak' => ['badge-danger', 'Ditolak', 'fa-times-circle'],
                        'rejected' => ['badge-danger', 'Ditolak', 'fa-times-circle'],
                        'gagal' => ['badge-danger', 'Gagal', 'fa-times-circle'],
                        'failed' => ['badge-danger', 'Gagal', 'fa-times-circle'],
                        'dibatalkan' => ['badge-danger', 'Dibatalkan', 'fa-times-circle'],
                        'cancelled' => ['badge-danger', 'Dibatalkan', 'fa-times-circle'],
                    ];
                    
                    $statusInfo = $statusMap[$status] ?? ['badge-secondary', ucfirst($status), 'fa-circle'];
                    
                    // Payment Status
                    $paymentStatus = $p['status_pembayaran'] ?? 'belum_bayar';
                    $paymentBadge = '';
                    $paymentText = '';
                    if($paymentStatus == 'lunas' || $paymentStatus == 'dikonfirmasi' || $paymentStatus == 'confirmed') {
                        $paymentBadge = 'badge-payment-lunas';
                        $paymentText = '✅ Lunas';
                    } elseif($paymentStatus == 'menunggu_konfirmasi') {
                        $paymentBadge = 'badge-payment-menunggu';
                        $paymentText = '⏳ Menunggu Konfirmasi';
                    } else {
                        $paymentBadge = 'badge-payment-belum';
                        $paymentText = '⏳ Belum Bayar';
                    }
                    
                    // Data
                    $kode_pesanan = $p['kode_pesanan'] ?? 'BOOK-' . uniqid();
                    $tanggal_berangkat = isset($p['tanggal_berangkat']) ? date('d/m/Y', strtotime($p['tanggal_berangkat'])) : '-';
                    $total_harga = $p['total_harga'] ?? 0;
                    $nama_kapal = $p['nama_kapal'] ?? 'Kapal';
                    $foto = $p['foto'] ?? '';
                    $durasi = $p['durasi_jam'] ?? 1;
                    $pelabuhan_asal = $p['pelabuhan_asal'] ?? $p['rute_asal'] ?? 'Parapat';
                    $pelabuhan_tujuan = $p['pelabuhan_tujuan'] ?? $p['rute_tujuan'] ?? 'Tuk-Tuk';
                    
                    // ==============================================
                    // 🔥 CEK BISA BAYAR
                    // ==============================================
                    $canPay = false;
                    if (($status == 'confirmed' || $status == 'dikonfirmasi') && 
                        !in_array($paymentStatus, ['lunas', 'dikonfirmasi', 'confirmed'])) {
                        $canPay = true;
                    }
                    
                    // ==============================================
                    // 🔥 CEK BISA BATALKAN - DITAMBAHKAN (BISA UNTUK SEMUA STATUS)
                    // ==============================================
                    $canCancel = false;
                    $cancelMessage = '';
                    
                    // Pesanan bisa dibatalkan jika statusnya pending ATAU confirmed (tanpa menunggu telat)
                    if (in_array($status, ['pending', 'menunggu', 'tertunda'])) {
                        $canCancel = true;
                        $cancelMessage = 'Pesanan dapat dibatalkan.';
                    } elseif (in_array($status, ['confirmed', 'dikonfirmasi'])) {
                        // Untuk confirmed, cek apakah sudah dijemput
                        $isDijemput = !empty($p['waktu_jemput_aktual']);
                        $isClaimPending = ($p['status_claim'] ?? '') == 'menunggu' || ($p['status_claim'] ?? '') == 'pending';
                        $isClaimDone = ($p['status_claim'] ?? '') == 'diterima' || ($p['status_claim'] ?? '') == 'ditolak';
                        
                        // Bisa batalkan jika: belum dijemput DAN belum ada claim pending/done
                        if (!$isDijemput && !$isClaimPending && !$isClaimDone) {
                            $canCancel = true;
                            $cancelMessage = 'Pesanan dapat dibatalkan.';
                        } else {
                            $canCancel = false;
                            if ($isDijemput) {
                                $cancelMessage = '✅ Sudah dijemput. Tidak bisa batalkan.';
                            } elseif ($isClaimPending) {
                                $cancelMessage = '⏳ Claim sedang diproses.';
                            } elseif ($isClaimDone) {
                                $cancelMessage = '📋 Claim sudah diproses.';
                            }
                        }
                    } else {
                        $canCancel = false;
                        $cancelMessage = 'Pesanan tidak dapat dibatalkan.';
                    }
                    
                    // ==============================================
                    // 🔥 CEK BISA RESCHEDULE
                    // ==============================================
                    $canReschedule = false;
                    if (($status == 'confirmed' || $status == 'dikonfirmasi') && 
                        in_array($paymentStatus, ['lunas', 'dikonfirmasi', 'confirmed'])) {
                        $rescheduleStatus = $p['reschedule_status'] ?? 'tidak';
                        if ($rescheduleStatus == 'tidak' || $rescheduleStatus == 'ditolak') {
                            $canReschedule = true;
                        }
                    }
                    
                    // ==============================================
                    // 🔥 CEK BISA SELESAIKAN
                    // ==============================================
                    $canComplete = false;
                    if (($status == 'confirmed' || $status == 'dikonfirmasi') && 
                        in_array($paymentStatus, ['lunas', 'dikonfirmasi', 'confirmed']) &&
                        ($p['status_claim'] ?? '') != 'diterima' &&
                        ($p['status_claim'] ?? '') != 'menunggu' &&
                        ($p['status_pencairan'] ?? '') != 'cair' &&
                        ($p['status_pencairan'] ?? '') != 'proses') {
                        $canComplete = true;
                    }
                    
                    // Claim status
                    $claimStatus = $p['status_claim'] ?? '';
                ?>
                    <div class="order-card" data-id="<?= $p['id'] ?>">
                        <!-- HEADER -->
                        <div class="order-header">
                            <div class="order-code">
                                <i class="fas fa-ticket-alt"></i>
                                <?= htmlspecialchars($kode_pesanan) ?>
                            </div>
                            <div class="order-date">
                                <i class="fas fa-calendar-alt"></i>
                                <?= $tanggal_berangkat ?>
                            </div>
                        </div>
                        
                        <!-- BODY -->
                        <div class="order-body">
                            <!-- Image -->
                            <div class="order-image">
                                <?php if(!empty($foto)): ?>
                                    <img src="/reservasi-kapal-wisata/uploads/kapal/<?= htmlspecialchars($foto) ?>" 
                                         alt="<?= htmlspecialchars($nama_kapal) ?>"
                                         onerror="this.style.display='none'; this.parentElement.querySelector('.no-image').style.display='flex'">
                                    <div class="no-image" style="display:none;">
                                        <i class="fas fa-ship"></i>
                                    </div>
                                <?php else: ?>
                                    <div class="no-image">
                                        <i class="fas fa-ship"></i>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Info -->
                            <div class="order-info">
                                <div class="order-title">
                                    <?= htmlspecialchars($nama_kapal) ?>
                                </div>
                                
                                <div class="order-meta">
                                    <span class="meta-item">
                                        <i class="fas fa-map-marker-alt"></i>
                                        <?= htmlspecialchars($pelabuhan_asal) ?> → <?= htmlspecialchars($pelabuhan_tujuan) ?>
                                    </span>
                                    <span class="meta-item">
                                        <i class="fas fa-clock"></i>
                                        <?= $durasi ?> Jam
                                    </span>
                                    <span class="meta-item">
                                        <i class="fas fa-users"></i>
                                        <?= $p['kapasitas'] ?? '-' ?> Orang
                                    </span>
                                    <span class="meta-item">
                                        <i class="fas fa-calendar-check"></i>
                                        <?= date('d/m/Y', strtotime($p['tanggal_berangkat'] ?? date('Y-m-d'))) ?>
                                    </span>
                                </div>
                                
                                <div class="order-price">
                                    Rp <?= number_format($total_harga, 0, ',', '.') ?>
                                </div>
                                
                                <div style="display:flex; gap:0.3rem; flex-wrap:wrap; margin-top:0.3rem;">
                                    <span class="badge <?= $statusInfo[0] ?>">
                                        <i class="fas <?= $statusInfo[2] ?>"></i>
                                        <?= $statusInfo[1] ?>
                                    </span>
                                    <span class="badge <?= $paymentBadge ?>">
                                        <?= $paymentText ?>
                                    </span>
                                    <?php if($claimStatus == 'menunggu'): ?>
                                        <span class="badge badge-warning">
                                            <i class="fas fa-clock"></i> Claim Menunggu
                                        </span>
                                    <?php elseif($claimStatus == 'diterima'): ?>
                                        <span class="badge badge-success">
                                            <i class="fas fa-check-circle"></i> Claim Diterima
                                        </span>
                                    <?php elseif($claimStatus == 'ditolak'): ?>
                                        <span class="badge badge-danger">
                                            <i class="fas fa-times-circle"></i> Claim Ditolak
                                        </span>
                                    <?php endif; ?>
                                    <?php if(($p['status_pencairan'] ?? '') == 'proses'): ?>
                                        <span class="badge badge-warning">
                                            <i class="fas fa-hourglass-half"></i> Dana Proses
                                        </span>
                                    <?php endif; ?>
                                    <?php if(($p['status_pencairan'] ?? '') == 'cair'): ?>
                                        <span class="badge badge-success">
                                            <i class="fas fa-money-bill-wave"></i> Dana Cair
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- FOOTER -->
                        <div class="order-footer">
                            <div class="order-actions">
                                <!-- Detail -->
                                <a href="?page=wisatawan&action=status&id=<?= $p['id'] ?>" class="btn btn-primary btn-xs">
                                    <i class="fas fa-eye"></i> Detail
                                </a>
                                
                                <!-- Bayar -->
                                <?php if($canPay): ?>
                                    <a href="?page=wisatawan&action=prosesPembayaran&id=<?= $p['id'] ?>" 
                                       class="btn btn-success btn-xs">
                                        <i class="fas fa-credit-card"></i> Bayar
                                    </a>
                                <?php endif; ?>
                                
                                <!-- 🔥 TOMBOL BATALKAN - LANGSUNG FORM TANPA MODAL -->
                                <?php if($canCancel): ?>
                                    <form method="POST" action="?page=wisatawan&action=prosesBatalPesanan" 
                                          style="display:inline-block;" 
                                          onsubmit="return confirm('⚠️ Yakin ingin membatalkan pesanan <?= htmlspecialchars($kode_pesanan) ?>?\n\nTindakan ini TIDAK DAPAT DIBATALKAN!')">
                                        <input type="hidden" name="pesanan_id" value="<?= $p['id'] ?>">
                                        <button type="submit" class="btn btn-danger btn-xs">
                                            <i class="fas fa-times"></i> Batalkan
                                        </button>
                                    </form>
                                <?php endif; ?>
                                
                                <!-- Reschedule -->
                                <?php if($canReschedule): ?>
                                    <a href="?page=wisatawan&action=reschedule&id=<?= $p['id'] ?>" 
                                       class="btn btn-warning btn-xs">
                                        <i class="fas fa-calendar-alt"></i> Reschedule
                                    </a>
                                <?php endif; ?>
                                
                                <!-- Selesaikan -->
                                <?php if($canComplete): ?>
                                    <form method="POST" action="?page=wisatawan&action=selesaikanPerjalanan" 
                                          style="display:inline-block;">
                                        <input type="hidden" name="pesanan_id" value="<?= $p['id'] ?>">
                                        <button type="submit" class="btn btn-success btn-xs btn-complete" 
                                                onclick="return confirm('Yakin perjalanan sudah selesai?')">
                                            <i class="fas fa-flag-checkered"></i> Selesai
                                        </button>
                                    </form>
                                <?php endif; ?>
                            </div>
                            
                            <div class="order-timeline">
                                <span>Status</span>
                                <span class="dot <?= in_array($status, ['pending', 'menunggu']) ? 'warning' : (in_array($status, ['confirmed', 'dikonfirmasi', 'selesai', 'completed']) ? 'active' : '') ?>"></span>
                                <span><?= $statusInfo[1] ?></span>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </main>
</div>

<!-- ============================================ -->
<!-- MODAL CANCEL (MASIH DIPERTAHANKAN UNTUK KASUS LAIN) -->
<!-- ============================================ -->
<div class="modal-overlay" id="cancelModal">
    <div class="modal-box">
        <div class="modal-icon">⚠️</div>
        <h3>Batalkan Pesanan</h3>
        <p>Anda yakin ingin membatalkan pesanan ini? Tindakan ini tidak dapat dibatalkan.</p>
        <form id="cancelForm" method="POST" action="?page=wisatawan&action=batalPesanan">
            <input type="hidden" name="id" id="cancelOrderId" value="">
            <textarea name="alasan" class="modal-reason" placeholder="Alasan pembatalan (opsional)"></textarea>
            <div class="modal-actions">
                <button type="button" class="btn btn-outline" onclick="closeCancelModal()">Batal</button>
                <button type="submit" class="btn btn-danger">
                    <i class="fas fa-times"></i> Ya, Batalkan
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Toast Container -->
<div id="toastContainer"></div>

<!-- ============================================ -->
<!-- JAVASCRIPT -->
<!-- ============================================ -->
<script>
    // ==============================================
    // MODAL CANCEL
    // ==============================================
    function openCancelModal(orderId) {
        document.getElementById('cancelOrderId').value = orderId;
        document.getElementById('cancelModal').classList.add('active');
        document.body.style.overflow = 'hidden';
    }

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

    // Close modal on overlay click
    document.getElementById('cancelModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeCancelModal();
        }
    });

    // Close modal on Escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeCancelModal();
        }
    });

    // ==============================================
    // AUTO CLOSE ALERT
    // ==============================================
    document.addEventListener('DOMContentLoaded', function() {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            setTimeout(() => {
                alert.style.opacity = '0';
                alert.style.transform = 'translateY(-10px)';
                setTimeout(() => alert.remove(), 400);
            }, 5000);
        });
    });

    // ==============================================
    // TOAST NOTIFICATION
    // ==============================================
    function showToast(message, type = 'info') {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = `toast-item ${type}`;
        toast.innerHTML = `
            <span style="flex:1;">${message}</span>
            <button onclick="this.parentElement.remove()" 
                    style="background:none;border:none;font-size:18px;cursor:pointer;color:#a0aec0;">
                ×
            </button>
        `;
        container.appendChild(toast);
        setTimeout(() => {
            if (toast.parentElement) {
                toast.style.animation = 'slideOutRight 0.3s ease';
                setTimeout(() => toast.remove(), 300);
            }
        }, 5000);
    }

    // ==============================================
    // CONFIRM COMPLETE
    // ==============================================
    document.querySelectorAll('.btn-complete').forEach(btn => {
        btn.addEventListener('click', function(e) {
            if (!confirm('Yakin perjalanan sudah selesai? Tindakan ini akan mengubah status pesanan menjadi selesai.')) {
                e.preventDefault();
            }
        });
    });

    console.log('✅ Riwayat Pesanan loaded');
</script>

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