<?php
/**
 * kelola_pesanan.php - Halaman Kelola Pesanan untuk Admin
 * Versi Terbaru dengan Design Modern & Filter Lengkap
 */
include __DIR__ . '/../layouts/header.php';
$activeMenu = 'kelolaPesanan';

// Data dari controller
$pesanan = $pesananList ?? [];
$notificationCounts = $notificationCounts ?? [
    'kapal_pending' => 0,
    'pesanan_pending' => 0,
    'request_hapus' => 0,
    'pembayaran_pending' => 0,
    'claim_pending' => 0,
    'pencairan_pending' => 0,
    'total' => 0
];

// Statistik
$stats = [
    'total' => count($pesanan),
    'tertunda' => 0,
    'dikonfirmasi' => 0,
    'selesai' => 0,
    'batalkan' => 0,
    'menunggu_pembayaran' => 0,
    'lunas' => 0,
    'gagal' => 0
];

foreach ($pesanan as $p) {
    $status = $p['status_pesanan'] ?? '';
    switch ($status) {
        case 'tertunda':
        case 'pending':
            $stats['tertunda']++;
            break;
        case 'dikonfirmasi':
        case 'confirmed':
            $stats['dikonfirmasi']++;
            break;
        case 'selesai':
        case 'completed':
            $stats['selesai']++;
            break;
        case 'batalkan':
        case 'cancelled':
            $stats['batalkan']++;
            break;
    }
    
    $payment = $p['status_pembayaran'] ?? '';
    switch ($payment) {
        case 'menunggu_konfirmasi':
            $stats['menunggu_pembayaran']++;
            break;
        case 'lunas':
            $stats['lunas']++;
            break;
        case 'gagal':
            $stats['gagal']++;
            break;
    }
}

// Ambil parameter filter dari GET
$filterStatus = isset($_GET['status']) ? $_GET['status'] : 'all';
$filterPayment = isset($_GET['payment']) ? $_GET['payment'] : 'all';
$searchQuery = isset($_GET['search']) ? trim($_GET['search']) : '';
$sortBy = isset($_GET['sort']) ? $_GET['sort'] : 'terbaru';

// Filter pesanan berdasarkan status
$filteredPesanan = $pesanan;
if ($filterStatus !== 'all') {
    $filteredPesanan = array_filter($filteredPesanan, function($p) use ($filterStatus) {
        $status = $p['status_pesanan'] ?? '';
        // Map status untuk filter
        $statusMap = [
            'tertunda' => ['tertunda', 'pending'],
            'dikonfirmasi' => ['dikonfirmasi', 'confirmed'],
            'selesai' => ['selesai', 'completed'],
            'batalkan' => ['batalkan', 'cancelled']
        ];
        $allowed = $statusMap[$filterStatus] ?? [$filterStatus];
        return in_array($status, $allowed);
    });
}

// Filter berdasarkan status pembayaran
if ($filterPayment !== 'all') {
    $filteredPesanan = array_filter($filteredPesanan, function($p) use ($filterPayment) {
        return ($p['status_pembayaran'] ?? '') == $filterPayment;
    });
}

// Filter berdasarkan search
if (!empty($searchQuery)) {
    $searchLower = strtolower($searchQuery);
    $filteredPesanan = array_filter($filteredPesanan, function($p) use ($searchLower) {
        $kode = strtolower($p['kode_pesanan'] ?? '');
        $wisatawan = strtolower($p['wisatawan'] ?? $p['wisatawan_nama'] ?? '');
        $kapal = strtolower($p['nama_kapal'] ?? '');
        return strpos($kode, $searchLower) !== false || 
               strpos($wisatawan, $searchLower) !== false ||
               strpos($kapal, $searchLower) !== false;
    });
}

// Sorting
switch ($sortBy) {
    case 'terbaru':
        usort($filteredPesanan, function($a, $b) {
            return strtotime($b['created_at'] ?? $b['tanggal_berangkat'] ?? '') - 
                   strtotime($a['created_at'] ?? $a['tanggal_berangkat'] ?? '');
        });
        break;
    case 'terlama':
        usort($filteredPesanan, function($a, $b) {
            return strtotime($a['created_at'] ?? $a['tanggal_berangkat'] ?? '') - 
                   strtotime($b['created_at'] ?? $b['tanggal_berangkat'] ?? '');
        });
        break;
    case 'termurah':
        usort($filteredPesanan, function($a, $b) {
            return ($a['total_harga'] ?? 0) - ($b['total_harga'] ?? 0);
        });
        break;
    case 'termahal':
        usort($filteredPesanan, function($a, $b) {
            return ($b['total_harga'] ?? 0) - ($a['total_harga'] ?? 0);
        });
        break;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Pesanan - Admin Panel</title>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&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;
            --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-sm: 0 1px 2px rgba(0,0,0,0.05);
            --shadow: 0 4px 20px rgba(0,0,0,0.06);
            --shadow-lg: 0 10px 40px rgba(0,0,0,0.08);
            --radius: 12px;
            --radius-sm: 8px;
            --transition: all 0.3s 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: 1440px;
            margin: 1.5rem auto 0;
            padding: 0 20px 2rem;
            width: 100%;
            align-items: flex-start;
        }

        .main-content {
            flex: 1;
            min-width: 0;
            background: #ffffff;
            border-radius: var(--radius);
            box-shadow: var(--shadow);
            padding: 1.8rem;
            border: 1px solid var(--gray-200);
            animation: fadeIn 0.4s ease;
        }

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

        /* ============================================
           HEADER
           ============================================ */
        .content-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            flex-wrap: wrap;
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

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

        .header-left h2 i {
            color: var(--primary);
        }

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

        .header-left p strong {
            color: var(--primary);
            font-weight: 700;
        }

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

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

        .btn-primary {
            background: var(--primary);
            color: #fff;
        }

        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(43, 108, 176, 0.3);
        }

        .btn-success {
            background: var(--success);
            color: #fff;
        }

        .btn-success:hover {
            background: #16a34a;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(34, 197, 94, 0.3);
        }

        .btn-danger {
            background: var(--danger);
            color: #fff;
        }

        .btn-danger:hover {
            background: #dc2626;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
        }

        .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);
            transform: translateY(-2px);
        }

        .btn-secondary {
            background: var(--gray-200);
            color: var(--gray-700);
        }

        .btn-secondary:hover {
            background: var(--gray-300);
        }

        .btn-sm {
            padding: 0.25rem 0.6rem;
            font-size: 0.7rem;
        }

        .btn-action {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 32px;
            height: 32px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: var(--transition);
            font-size: 0.75rem;
            text-decoration: none;
            color: #fff;
        }

        .btn-action:hover {
            transform: scale(1.1);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }

        .btn-action:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none !important;
        }

        .btn-view {
            background: var(--primary);
            color: #fff;
        }

        .btn-view:hover {
            background: var(--primary-dark);
        }

        .btn-confirm {
            background: var(--success);
            color: #fff;
        }

        .btn-confirm:hover {
            background: #16a34a;
        }

        .btn-cancel {
            background: var(--danger);
            color: #fff;
        }

        .btn-cancel:hover {
            background: #dc2626;
        }

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

        .stat-card {
            background: #fff;
            padding: 0.8rem 1rem;
            border-radius: var(--radius-sm);
            border: 1px solid var(--gray-200);
            display: flex;
            align-items: center;
            gap: 0.8rem;
            transition: var(--transition);
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
        }

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

        .stat-card.active {
            border-color: var(--primary);
            background: var(--primary-bg);
        }

        .stat-card.active::before {
            background: var(--primary);
        }

        .stat-card .stat-icon {
            width: 38px;
            height: 38px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
            flex-shrink: 0;
        }

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

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

        .stat-card.total::before { background: var(--primary); }
        .stat-card.total .stat-icon { background: var(--primary-bg); color: var(--primary); }

        .stat-card.tertunda::before { background: var(--warning); }
        .stat-card.tertunda .stat-icon { background: var(--warning-bg); color: #92400e; }
        .stat-card.tertunda.active { border-color: var(--warning); background: var(--warning-bg); }

        .stat-card.dikonfirmasi::before { background: var(--info); }
        .stat-card.dikonfirmasi .stat-icon { background: var(--info-bg); color: #1e40af; }
        .stat-card.dikonfirmasi.active { border-color: var(--info); background: var(--info-bg); }

        .stat-card.selesai::before { background: var(--success); }
        .stat-card.selesai .stat-icon { background: var(--success-bg); color: #065f46; }
        .stat-card.selesai.active { border-color: var(--success); background: var(--success-bg); }

        .stat-card.batalkan::before { background: var(--danger); }
        .stat-card.batalkan .stat-icon { background: var(--danger-bg); color: #991b1b; }
        .stat-card.batalkan.active { border-color: var(--danger); background: var(--danger-bg); }

        /* ============================================
           FILTER SECTION
           ============================================ */
        .filter-section {
            background: var(--gray-50);
            border-radius: var(--radius-sm);
            padding: 1rem 1.2rem;
            margin-bottom: 1.5rem;
            border: 1px solid var(--gray-200);
        }

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

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

        .filter-group label {
            display: block;
            font-weight: 600;
            font-size: 0.7rem;
            text-transform: uppercase;
            letter-spacing: 0.3px;
            color: var(--gray-500);
            margin-bottom: 0.2rem;
        }

        .filter-group input,
        .filter-group select {
            width: 100%;
            padding: 0.4rem 0.8rem;
            border: 1.5px solid var(--gray-200);
            border-radius: var(--radius-sm);
            font-size: 0.85rem;
            background: #fff;
            transition: var(--transition);
            font-family: inherit;
            color: var(--gray-700);
        }

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

        .filter-group .btn {
            width: 100%;
            justify-content: center;
        }

        /* ============================================
           TABLE
           ============================================ */
        .table-wrapper {
            background: #fff;
            border-radius: var(--radius-sm);
            border: 1px solid var(--gray-200);
            overflow: hidden;
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.85rem;
            min-width: 900px;
        }

        table thead {
            background: var(--gray-50);
            border-bottom: 2px solid var(--gray-200);
        }

        table th {
            padding: 0.6rem 1rem;
            text-align: left;
            font-weight: 700;
            font-size: 0.7rem;
            text-transform: uppercase;
            letter-spacing: 0.3px;
            color: var(--gray-600);
            white-space: nowrap;
        }

        table th i {
            margin-right: 0.3rem;
            opacity: 0.6;
        }

        table td {
            padding: 0.6rem 1rem;
            border-bottom: 1px solid var(--gray-100);
            vertical-align: middle;
        }

        table tbody tr {
            transition: var(--transition);
        }

        table tbody tr:hover {
            background: var(--gray-50);
        }

        table tbody tr:last-child td {
            border-bottom: none;
        }

        .table-empty {
            text-align: center;
            padding: 3rem !important;
            color: var(--gray-500);
        }

        .table-empty i {
            font-size: 3rem;
            display: block;
            margin-bottom: 0.5rem;
            opacity: 0.5;
        }

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

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

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

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

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

        .badge-payment-belum_bayar {
            background: var(--gray-100);
            color: var(--gray-600);
        }

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

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

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

        /* ============================================
           INFO EXTRA
           ============================================ */
        .info-extra {
            display: flex;
            gap: 1.5rem;
            flex-wrap: wrap;
            margin-top: 1rem;
            padding: 0.8rem 1rem;
            background: var(--gray-50);
            border-radius: var(--radius-sm);
            border: 1px solid var(--gray-200);
        }

        .info-extra-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.85rem;
            color: var(--gray-600);
        }

        .info-extra-item i {
            font-size: 1rem;
            width: 20px;
            text-align: center;
        }

        .info-extra-item strong {
            color: var(--gray-800);
        }

        /* ============================================
           TOAST NOTIFICATION
           ============================================ */
        #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: 1024px) {
            .stats-grid {
                grid-template-columns: repeat(3, 1fr);
            }
        }

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

            .main-content {
                padding: 1rem;
            }

            .content-header {
                flex-direction: column;
            }

            .header-actions {
                width: 100%;
            }

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

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

            .filter-row {
                flex-direction: column;
                gap: 0.5rem;
            }

            .filter-group {
                min-width: auto;
            }

            table {
                font-size: 0.75rem;
                min-width: 700px;
            }

            table th,
            table td {
                padding: 0.4rem 0.6rem;
            }

            .btn-action {
                width: 28px;
                height: 28px;
                font-size: 0.7rem;
            }
        }

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

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

            .stat-card {
                padding: 0.5rem 0.6rem;
            }

            .stat-number {
                font-size: 1.1rem;
            }

            .stat-icon {
                width: 30px;
                height: 30px;
                font-size: 0.8rem;
            }

            table {
                font-size: 0.65rem;
                min-width: 600px;
            }

            table th,
            table td {
                padding: 0.3rem 0.4rem;
            }

            .btn-action {
                width: 24px;
                height: 24px;
                font-size: 0.6rem;
            }

            .badge {
                font-size: 0.55rem;
                padding: 0.1rem 0.4rem;
            }
        }
    </style>
</head>
<body>

<div class="dashboard-wrapper">
    <!-- SIDEBAR -->
    <?php 
    $pendingKapalCount = $notificationCounts['kapal_pending'] ?? 0;
    $pendingPesananCount = $notificationCounts['pesanan_pending'] ?? 0;
    $pendingHapusCount = $notificationCounts['request_hapus'] ?? 0;
    $pendingPembayaranCount = $notificationCounts['pembayaran_pending'] ?? 0;
    $pendingClaimCount = $notificationCounts['claim_pending'] ?? 0;
    $pendingPencairanCount = $notificationCounts['pencairan_pending'] ?? 0;
    include __DIR__ . '/includes/sidebar_admin.php'; 
    ?>

    <!-- MAIN CONTENT -->
    <main class="main-content">
        <!-- HEADER -->
        <div class="content-header">
            <div class="header-left">
                <h2>
                    <i class="fas fa-clipboard-list"></i>
                    Kelola Pesanan
                </h2>
                <p>
                    <i class="fas fa-ship"></i> 
                    Menampilkan <strong><?= count($filteredPesanan) ?></strong> dari <strong><?= count($pesanan) ?></strong> pesanan
                </p>
            </div>
            <div class="header-actions">
                <button class="btn btn-outline btn-sm" onclick="exportData()">
                    <i class="fas fa-download"></i> Export
                </button>
                <button class="btn btn-primary btn-sm" onclick="refreshData()">
                    <i class="fas fa-sync-alt"></i> Refresh
                </button>
            </div>
        </div>

        <!-- STATS CARDS -->
        <div class="stats-grid">
            <a href="?page=admin&action=kelolaPesanan&status=all" class="stat-card total <?= $filterStatus == 'all' ? 'active' : '' ?>" style="text-decoration:none;">
                <div class="stat-icon"><i class="fas fa-boxes"></i></div>
                <div>
                    <div class="stat-number"><?= $stats['total'] ?></div>
                    <div class="stat-label">Total</div>
                </div>
            </a>
            <a href="?page=admin&action=kelolaPesanan&status=tertunda" class="stat-card tertunda <?= $filterStatus == 'tertunda' ? 'active' : '' ?>" style="text-decoration:none;">
                <div class="stat-icon"><i class="fas fa-clock"></i></div>
                <div>
                    <div class="stat-number"><?= $stats['tertunda'] ?></div>
                    <div class="stat-label">Tertunda</div>
                </div>
            </a>
            <a href="?page=admin&action=kelolaPesanan&status=dikonfirmasi" class="stat-card dikonfirmasi <?= $filterStatus == 'dikonfirmasi' ? 'active' : '' ?>" style="text-decoration:none;">
                <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
                <div>
                    <div class="stat-number"><?= $stats['dikonfirmasi'] ?></div>
                    <div class="stat-label">Dikonfirmasi</div>
                </div>
            </a>
            <a href="?page=admin&action=kelolaPesanan&status=selesai" class="stat-card selesai <?= $filterStatus == 'selesai' ? 'active' : '' ?>" style="text-decoration:none;">
                <div class="stat-icon"><i class="fas fa-check-double"></i></div>
                <div>
                    <div class="stat-number"><?= $stats['selesai'] ?></div>
                    <div class="stat-label">Selesai</div>
                </div>
            </a>
            <a href="?page=admin&action=kelolaPesanan&status=batalkan" class="stat-card batalkan <?= $filterStatus == 'batalkan' ? 'active' : '' ?>" style="text-decoration:none;">
                <div class="stat-icon"><i class="fas fa-times-circle"></i></div>
                <div>
                    <div class="stat-number"><?= $stats['batalkan'] ?></div>
                    <div class="stat-label">Dibatalkan</div>
                </div>
            </a>
        </div>

        <!-- FILTER SECTION -->
        <div class="filter-section">
            <form method="GET" action="" id="filterForm">
                <input type="hidden" name="page" value="admin">
                <input type="hidden" name="action" value="kelolaPesanan">
                
                <div class="filter-row">
                    <div class="filter-group">
                        <label><i class="fas fa-search"></i> Cari</label>
                        <input type="text" name="search" id="searchInput" 
                               placeholder="Cari kode, wisatawan, atau kapal..." 
                               value="<?= htmlspecialchars($searchQuery) ?>"
                               onkeyup="document.getElementById('filterForm').submit()">
                    </div>
                    <div class="filter-group">
                        <label><i class="fas fa-filter"></i> Status</label>
                        <select name="status" onchange="document.getElementById('filterForm').submit()">
                            <option value="all" <?= $filterStatus == 'all' ? 'selected' : '' ?>>Semua Status</option>
                            <option value="tertunda" <?= $filterStatus == 'tertunda' ? 'selected' : '' ?>>⏳ Tertunda</option>
                            <option value="dikonfirmasi" <?= $filterStatus == 'dikonfirmasi' ? 'selected' : '' ?>>✅ Dikonfirmasi</option>
                            <option value="selesai" <?= $filterStatus == 'selesai' ? 'selected' : '' ?>>🎉 Selesai</option>
                            <option value="batalkan" <?= $filterStatus == 'batalkan' ? 'selected' : '' ?>>❌ Dibatalkan</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label><i class="fas fa-credit-card"></i> Pembayaran</label>
                        <select name="payment" onchange="document.getElementById('filterForm').submit()">
                            <option value="all" <?= $filterPayment == 'all' ? 'selected' : '' ?>>Semua Pembayaran</option>
                            <option value="belum_bayar" <?= $filterPayment == 'belum_bayar' ? 'selected' : '' ?>>⏳ Belum Bayar</option>
                            <option value="menunggu_konfirmasi" <?= $filterPayment == 'menunggu_konfirmasi' ? 'selected' : '' ?>>🔄 Menunggu Konfirmasi</option>
                            <option value="lunas" <?= $filterPayment == 'lunas' ? 'selected' : '' ?>>✅ Lunas</option>
                            <option value="gagal" <?= $filterPayment == 'gagal' ? 'selected' : '' ?>>❌ Gagal</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label><i class="fas fa-sort"></i> Urutkan</label>
                        <select name="sort" onchange="document.getElementById('filterForm').submit()">
                            <option value="terbaru" <?= $sortBy == 'terbaru' ? 'selected' : '' ?>>Terbaru</option>
                            <option value="terlama" <?= $sortBy == 'terlama' ? 'selected' : '' ?>>Terlama</option>
                            <option value="termurah" <?= $sortBy == 'termurah' ? 'selected' : '' ?>>Termurah</option>
                            <option value="termahal" <?= $sortBy == 'termahal' ? 'selected' : '' ?>>Termahal</option>
                        </select>
                    </div>
                    <div class="filter-group" style="flex:0.5; min-width:100px;">
                        <label>&nbsp;</label>
                        <a href="?page=admin&action=kelolaPesanan" class="btn btn-secondary" style="width:100%; justify-content:center;">
                            <i class="fas fa-undo"></i> Reset
                        </a>
                    </div>
                </div>
            </form>
        </div>

        <!-- TABLE -->
        <div class="table-wrapper">
            <table id="pesananTable">
                <thead>
                    <tr>
                        <th><i class="fas fa-hashtag"></i> Kode</th>
                        <th><i class="fas fa-user"></i> Wisatawan</th>
                        <th><i class="fas fa-ship"></i> Kapal</th>
                        <th><i class="fas fa-calendar-alt"></i> Tanggal</th>
                        <th><i class="fas fa-clock"></i> Durasi</th>
                        <th><i class="fas fa-money-bill-wave"></i> Total</th>
                        <th><i class="fas fa-info-circle"></i> Status</th>
                        <th><i class="fas fa-credit-card"></i> Pembayaran</th>
                        <th><i class="fas fa-cog"></i> Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($filteredPesanan)): ?>
                        <tr>
                            <td colspan="9" class="table-empty">
                                <i class="fas fa-inbox"></i>
                                <?php if(!empty($searchQuery) || $filterStatus != 'all' || $filterPayment != 'all'): ?>
                                    <h4 style="color:var(--gray-700); margin-top:0.5rem;">Tidak ada hasil</h4>
                                    <p style="color:var(--gray-400);">Coba ubah filter atau kata kunci pencarian</p>
                                    <a href="?page=admin&action=kelolaPesanan" class="btn btn-primary" style="margin-top:0.5rem;">
                                        <i class="fas fa-undo"></i> Reset Filter
                                    </a>
                                <?php else: ?>
                                    <h4 style="color:var(--gray-700); margin-top:0.5rem;">Belum ada pesanan</h4>
                                    <p style="color:var(--gray-400);">Pesanan akan muncul setelah wisatawan melakukan pemesanan</p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach($filteredPesanan as $p): 
                            // Status Badge
                            $statusBadge = '';
                            $statusIcon = '';
                            $statusText = '';
                            $status = $p['status_pesanan'] ?? '';
                            switch($status) {
                                case 'tertunda':
                                case 'pending':
                                    $statusBadge = 'badge-status-tertunda';
                                    $statusIcon = '<i class="fas fa-clock"></i>';
                                    $statusText = 'Tertunda';
                                    break;
                                case 'dikonfirmasi':
                                case 'confirmed':
                                    $statusBadge = 'badge-status-dikonfirmasi';
                                    $statusIcon = '<i class="fas fa-check-circle"></i>';
                                    $statusText = 'Dikonfirmasi';
                                    break;
                                case 'selesai':
                                case 'completed':
                                    $statusBadge = 'badge-status-selesai';
                                    $statusIcon = '<i class="fas fa-check-double"></i>';
                                    $statusText = 'Selesai';
                                    break;
                                case 'batalkan':
                                case 'cancelled':
                                    $statusBadge = 'badge-status-batalkan';
                                    $statusIcon = '<i class="fas fa-times-circle"></i>';
                                    $statusText = 'Dibatalkan';
                                    break;
                                default:
                                    $statusBadge = 'badge-status-tertunda';
                                    $statusIcon = '<i class="fas fa-clock"></i>';
                                    $statusText = $status ?: 'Unknown';
                            }
                            
                            // Payment Badge
                            $paymentBadge = '';
                            $paymentIcon = '';
                            $paymentText = '';
                            $payment = $p['status_pembayaran'] ?? '';
                            switch($payment) {
                                case 'belum_bayar':
                                    $paymentBadge = 'badge-payment-belum_bayar';
                                    $paymentIcon = '<i class="fas fa-clock"></i>';
                                    $paymentText = 'Belum Bayar';
                                    break;
                                case 'menunggu_konfirmasi':
                                    $paymentBadge = 'badge-payment-menunggu_konfirmasi';
                                    $paymentIcon = '<i class="fas fa-hourglass-half"></i>';
                                    $paymentText = 'Menunggu Konfirmasi';
                                    break;
                                case 'lunas':
                                    $paymentBadge = 'badge-payment-lunas';
                                    $paymentIcon = '<i class="fas fa-check-circle"></i>';
                                    $paymentText = 'Lunas';
                                    break;
                                case 'gagal':
                                    $paymentBadge = 'badge-payment-gagal';
                                    $paymentIcon = '<i class="fas fa-times-circle"></i>';
                                    $paymentText = 'Gagal';
                                    break;
                                default:
                                    $paymentBadge = 'badge-payment-belum_bayar';
                                    $paymentIcon = '<i class="fas fa-clock"></i>';
                                    $paymentText = 'Belum Bayar';
                            }
                            
                            $wisatawan = $p['wisatawan'] ?? $p['wisatawan_nama'] ?? 'Unknown';
                            $kodePesanan = $p['kode_pesanan'] ?? '#' . ($p['id'] ?? '');
                            $canConfirm = in_array($status, ['tertunda', 'pending']);
                            $canCancel = in_array($status, ['tertunda', 'pending']);
                        ?>
                            <tr>
                                <td>
                                    <strong><?= htmlspecialchars($kodePesanan) ?></strong>
                                </td>
                                <td>
                                    <div style="display:flex; align-items:center; gap:0.4rem;">
                                        <i class="fas fa-user-circle" style="color:var(--gray-400); font-size:1.1rem;"></i>
                                        <div>
                                            <div style="font-weight:500; font-size:0.85rem;">
                                                <?= htmlspecialchars($wisatawan) ?>
                                            </div>
                                            <?php if(!empty($p['wisatawan_hp'])): ?>
                                                <div style="font-size:0.6rem; color:var(--gray-400);">
                                                    <i class="fas fa-phone"></i> <?= htmlspecialchars($p['wisatawan_hp']) ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div style="display:flex; align-items:center; gap:0.3rem;">
                                        <i class="fas fa-ship" style="color:var(--primary);"></i>
                                        <span style="font-weight:500;"><?= htmlspecialchars($p['nama_kapal'] ?? 'N/A') ?></span>
                                    </div>
                                </td>
                                <td>
                                    <?php if(!empty($p['tanggal_berangkat'])): ?>
                                        <div style="font-weight:500;"><?= date('d/m/Y', strtotime($p['tanggal_berangkat'])) ?></div>
                                        <div style="font-size:0.6rem; color:var(--gray-400);">
                                            <?= date('H:i', strtotime($p['tanggal_berangkat'])) ?>
                                        </div>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td style="text-align:center;">
                                    <?= $p['durasi_jam'] ?? 1 ?> <span style="font-size:0.6rem;color:var(--gray-400);">jam</span>
                                </td>
                                <td style="font-weight:700; color:var(--primary); font-size:0.95rem;">
                                    Rp <?= number_format($p['total_harga'] ?? 0, 0, ',', '.') ?>
                                </td>
                                <td>
                                    <span class="badge <?= $statusBadge ?>">
                                        <?= $statusIcon ?> <?= $statusText ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge <?= $paymentBadge ?>">
                                        <?= $paymentIcon ?> <?= $paymentText ?>
                                    </span>
                                </td>
                                <td>
                                    <div style="display:flex; gap:0.3rem; flex-wrap:wrap;">
                                        <!-- Tombol Detail -->
                                        <a href="?page=admin&action=detailPesanan&id=<?= $p['id'] ?? 0 ?>" 
                                           class="btn-action btn-view" 
                                           title="Lihat Detail">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        
                                        <!-- Tombol Confirm (hanya untuk tertunda/pending) -->
                                        <?php if($canConfirm): ?>
                                            <button onclick="confirmOrder(<?= $p['id'] ?? 0 ?>)" 
                                                    class="btn-action btn-confirm" 
                                                    title="Konfirmasi Pesanan">
                                                <i class="fas fa-check"></i>
                                            </button>
                                        <?php endif; ?>
                                        
                                        <!-- Tombol Cancel (hanya untuk tertunda/pending) -->
                                        <?php if($canCancel): ?>
                                            <button onclick="cancelOrder(<?= $p['id'] ?? 0 ?>)" 
                                                    class="btn-action btn-cancel" 
                                                    title="Batalkan Pesanan">
                                                <i class="fas fa-times"></i>
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- INFO EXTRA -->
        <div class="info-extra">
            <div class="info-extra-item">
                <i class="fas fa-credit-card" style="color:var(--warning);"></i>
                <span>
                    <strong><?= $stats['menunggu_pembayaran'] ?></strong> 
                    menunggu konfirmasi pembayaran
                </span>
            </div>
            <div class="info-extra-item">
                <i class="fas fa-check-circle" style="color:var(--success);"></i>
                <span>
                    <strong><?= $stats['lunas'] ?></strong> 
                    pembayaran lunas
                </span>
            </div>
            <div class="info-extra-item">
                <i class="fas fa-times-circle" style="color:var(--danger);"></i>
                <span>
                    <strong><?= $stats['gagal'] ?></strong> 
                    pembayaran gagal
                </span>
            </div>
            <div class="info-extra-item" style="margin-left:auto;">
                <i class="fas fa-clock" style="color:var(--gray-400);"></i>
                <span style="font-size:0.7rem;color:var(--gray-400);">
                    Last updated: <?= date('d/m/Y H:i:s') ?>
                </span>
            </div>
        </div>
    </main>
</div>

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

<!-- ============================================
   JAVASCRIPT
   ============================================ -->
<script>
    // ============================================
    // 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 ORDER
    // ============================================
    function confirmOrder(id) {
        if (!confirm('Yakin ingin mengkonfirmasi pesanan ini?')) return;
        
        const btn = event.target.closest('button');
        const originalHtml = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        btn.disabled = true;
        
        fetch('index.php?action=confirmPesanan&id=' + id, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('✅ ' + data.message, 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                showToast('❌ ' + data.message, 'error');
                btn.innerHTML = originalHtml;
                btn.disabled = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('❌ Error: ' + error.message, 'error');
            btn.innerHTML = originalHtml;
            btn.disabled = false;
        });
    }

    // ============================================
    // CANCEL ORDER
    // ============================================
    function cancelOrder(id) {
        if (!confirm('⚠️ Yakin ingin membatalkan pesanan ini?')) return;
        
        const reason = prompt('Alasan pembatalan (opsional):');
        if (reason === null) return;
        
        const btn = event.target.closest('button');
        const originalHtml = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        btn.disabled = true;
        
        const formData = new FormData();
        formData.append('id', id);
        if (reason && reason.trim()) {
            formData.append('reason', reason.trim());
        }
        
        fetch('index.php?action=cancelPesanan&id=' + id, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('✅ ' + data.message, 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                showToast('❌ ' + data.message, 'error');
                btn.innerHTML = originalHtml;
                btn.disabled = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('❌ Error: ' + error.message, 'error');
            btn.innerHTML = originalHtml;
            btn.disabled = false;
        });
    }

    // ============================================
    // EXPORT DATA
    // ============================================
    function exportData() {
        const rows = document.querySelectorAll('#pesananTable tbody tr');
        if (rows.length === 0 || rows[0].querySelector('.table-empty')) {
            showToast('⚠️ Tidak ada data untuk diexport', 'warning');
            return;
        }
        
        let csv = 'Kode,Wisatawan,Kapal,Tanggal,Durasi,Total,Status,Pembayaran\n';
        rows.forEach(row => {
            const cols = row.querySelectorAll('td');
            if (cols.length < 8) return;
            const data = [
                cols[0].textContent.trim(),
                cols[1].textContent.trim().replace(/,/g, ';'),
                cols[2].textContent.trim(),
                cols[3].textContent.trim(),
                cols[4].textContent.trim(),
                cols[5].textContent.trim().replace(/[^0-9.]/g, ''),
                cols[6].textContent.trim(),
                cols[7].textContent.trim()
            ];
            csv += data.join(',') + '\n';
        });
        
        const blob = new Blob([csv], { type: 'text/csv' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `pesanan_${new Date().toISOString().split('T')[0]}.csv`;
        a.click();
        URL.revokeObjectURL(url);
        showToast('✅ Data berhasil diexport', 'success');
    }

    // ============================================
    // REFRESH DATA
    // ============================================
    function refreshData() {
        const btn = event.target.closest('button');
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Loading...';
        btn.disabled = true;
        location.reload();
    }

    // ============================================
    // KEYBOARD SHORTCUTS
    // ============================================
    document.addEventListener('keydown', function(e) {
        // Ctrl+F untuk focus search
        if (e.ctrlKey && e.key === 'f') {
            e.preventDefault();
            document.getElementById('searchInput').focus();
        }
        // Escape untuk reset filter
        if (e.key === 'Escape') {
            window.location.href = '?page=admin&action=kelolaPesanan';
        }
    });

    console.log('✅ Kelola Pesanan loaded');
    console.log(`📊 Total: ${document.querySelectorAll('#pesananTable tbody tr').length} pesanan`);
</script>

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