<?php
/**
 * laporan.php - Halaman Laporan Lengkap dengan Grafik Interaktif
 * Versi Terbaru - Semua Grafik Berfungsi dengan Data Real
 */
include __DIR__ . '/../layouts/header.php';
$activeMenu = 'laporan';

// Data dari controller (sudah di-extract)
// $laporanKapal, $laporanPencairan, $laporanClaim, $summary, 
// $statistikWisatawan, $totalKapalDipesan, $totalDicairkan, $totalClaim,
// $tanggal_awal, $tanggal_akhir
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan - Admin Panel</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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

    <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;
            --purple: #8b5cf6;
            --purple-bg: #ede9fe;
            --teal: #14b8a6;
            --teal-bg: #ccfbf1;
            --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: #0d1117;
            --shadow-sm: 0 1px 3px rgba(0,0,0,0.06);
            --shadow: 0 4px 20px rgba(0,0,0,0.08);
            --shadow-lg: 0 10px 50px 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 {
            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: 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: flex-start;
            flex-wrap: wrap;
            gap: 1rem;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid var(--gray-100);
        }

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

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

        .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.8rem;
            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);
        }

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

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

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

        /* ============================================
           FILTER SECTION
           ============================================ */
        .filter-section {
            background: linear-gradient(135deg, var(--gray-50), #ffffff);
            border-radius: var(--radius-sm);
            padding: 1.2rem 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid var(--gray-200);
            box-shadow: var(--shadow-sm);
        }

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

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

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

        .filter-group label i {
            margin-right: 0.3rem;
        }

        .filter-input {
            width: 100%;
            padding: 0.5rem 0.8rem;
            border: 2px 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-input:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 4px rgba(43, 108, 176, 0.1);
        }

        .filter-info {
            margin-top: 0.8rem;
            padding: 0.5rem 1rem;
            background: var(--primary-bg);
            border-radius: var(--radius-sm);
            border: 1px solid rgba(43, 108, 176, 0.2);
            font-size: 0.85rem;
            color: var(--primary-dark);
        }

        .filter-info i {
            margin-right: 0.5rem;
        }

        /* ============================================
           STATS GRID
           ============================================ */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .stat-card {
            background: #fff;
            padding: 1.2rem 1.2rem;
            border-radius: var(--radius-sm);
            border: 1px solid var(--gray-200);
            box-shadow: var(--shadow-sm);
            transition: var(--transition);
            position: relative;
            overflow: hidden;
        }

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

        .stat-card:hover {
            transform: translateY(-4px);
            box-shadow: var(--shadow-lg);
        }

        .stat-card .stat-icon {
            font-size: 1.8rem;
            display: block;
            margin-bottom: 0.3rem;
        }

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

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

        .stat-card.primary::before { background: var(--primary); }
        .stat-card.success::before { background: var(--success); }
        .stat-card.warning::before { background: var(--warning); }
        .stat-card.purple::before { background: var(--purple); }
        .stat-card.danger::before { background: var(--danger); }
        .stat-card.teal::before { background: var(--teal); }

        /* ============================================
           CHART SECTION
           ============================================ */
        .chart-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
            margin-bottom: 1.5rem;
        }

        .chart-card {
            background: #fff;
            border-radius: var(--radius-sm);
            padding: 1.2rem;
            border: 1px solid var(--gray-200);
            transition: var(--transition);
        }

        .chart-card:hover {
            box-shadow: var(--shadow);
        }

        .chart-card .chart-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.8rem;
        }

        .chart-card .chart-header h4 {
            font-size: 0.95rem;
            font-weight: 700;
            color: var(--gray-700);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .chart-card .chart-header .chart-badge {
            font-size: 0.6rem;
            padding: 0.2rem 0.6rem;
            border-radius: 20px;
            background: var(--gray-100);
            color: var(--gray-600);
        }

        .chart-card canvas {
            max-height: 220px;
            max-width: 100%;
        }

        .chart-empty {
            text-align: center;
            padding: 2rem;
            color: var(--gray-400);
        }

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

        /* ============================================
           CARD SECTION
           ============================================ */
        .card-section {
            background: #fff;
            border-radius: var(--radius-sm);
            border: 1px solid var(--gray-200);
            margin-bottom: 1.5rem;
            overflow: hidden;
            transition: var(--transition);
        }

        .card-section:hover {
            box-shadow: var(--shadow);
        }

        .card-header {
            padding: 0.8rem 1.2rem;
            border-bottom: 1px solid var(--gray-200);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 0.5rem;
            background: linear-gradient(135deg, var(--gray-50), #ffffff);
        }

        .card-header h3 {
            font-size: 1rem;
            font-weight: 700;
            color: var(--gray-700);
            margin: 0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

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

        .badge-primary { background: var(--primary-bg); color: var(--primary); }
        .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-purple { background: var(--purple-bg); color: var(--purple); }

        /* ============================================
           TABLE
           ============================================ */
        .table-responsive {
            overflow-x: auto;
            padding: 0 0.5rem;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.85rem;
        }

        .table thead {
            background: var(--gray-50);
        }

        .table th {
            padding: 0.6rem 1rem;
            text-align: left;
            font-size: 0.7rem;
            text-transform: uppercase;
            font-weight: 700;
            color: var(--gray-500);
            border-bottom: 2px solid var(--gray-200);
            letter-spacing: 0.5px;
        }

        .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 td {
            background: var(--gray-50);
        }

        .table tfoot {
            background: var(--gray-50);
            font-weight: 700;
        }

        .table tfoot td {
            border-top: 2px solid var(--gray-200);
            padding: 0.6rem 1rem;
        }

        .text-center { text-align: center; }
        .text-muted { color: var(--gray-400); }
        .text-success { color: var(--success); }
        .text-danger { color: var(--danger); }
        .text-primary { color: var(--primary); }
        .text-warning { color: var(--warning); }

        /* ============================================
           INFO EXTRA
           ============================================ */
        .info-extra {
            display: flex;
            gap: 1.5rem;
            flex-wrap: wrap;
            margin-top: 1rem;
            padding: 0.8rem 1.2rem;
            background: linear-gradient(135deg, var(--gray-50), #ffffff);
            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
           ============================================ */
        #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; }

        @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(2, 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;
                align-items: flex-start;
            }

            .header-actions {
                width: 100%;
            }

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

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

            .stat-card .stat-number {
                font-size: 1.2rem;
            }

            .chart-section {
                grid-template-columns: 1fr;
            }

            .filter-row {
                flex-direction: column;
            }

            .filter-group {
                min-width: 100%;
            }

            .table {
                font-size: 0.75rem;
            }

            .table th,
            .table td {
                padding: 0.3rem 0.5rem;
            }

            .info-extra {
                flex-direction: column;
                gap: 0.3rem;
            }
        }

        @media (max-width: 480px) {
            .stats-grid {
                grid-template-columns: 1fr 1fr;
                gap: 0.5rem;
            }

            .stat-card {
                padding: 0.8rem 0.8rem;
            }

            .stat-card .stat-number {
                font-size: 1rem;
            }

            .stat-card .stat-icon {
                font-size: 1.2rem;
            }

            .header-left h2 {
                font-size: 1.2rem;
            }
        }

        /* ============================================
           PRINT STYLES
           ============================================ */
        @media print {
            .sidebar, .filter-section, .header-actions, .info-extra { 
                display: none !important; 
            }
            .dashboard-wrapper { 
                display: block !important; 
                margin: 0 !important; 
                padding: 0 !important; 
            }
            .main-content { 
                border: none !important; 
                box-shadow: none !important; 
                padding: 1rem !important; 
                border-radius: 0 !important; 
            }
            .stat-card { 
                border: 1px solid #ddd !important; 
                box-shadow: none !important; 
                break-inside: avoid;
            }
            .card-section { break-inside: avoid; }
            .chart-section { break-inside: avoid; }
        }
    </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" id="laporanContent">
        <!-- HEADER -->
        <div class="content-header">
            <div class="header-left">
                <h2>
                    <i class="fas fa-file-invoice-dollar"></i>
                    Laporan Lengkap
                </h2>
                <p>
                    <i class="fas fa-chart-line"></i> 
                    Laporan pendapatan, pencairan dana, dan claim pengembalian
                </p>
            </div>
            <div class="header-actions">
                <button onclick="window.print()" class="btn btn-primary">
                    <i class="fas fa-print"></i> Cetak
                </button>
                <button onclick="exportPDF()" class="btn btn-success">
                    <i class="fas fa-file-pdf"></i> PDF
                </button>
                <button onclick="exportExcel()" class="btn btn-outline">
                    <i class="fas fa-file-excel"></i> Excel
                </button>
            </div>
        </div>

        <!-- FILTER -->
        <div class="filter-section">
            <form method="GET" action="" id="filterForm">
                <input type="hidden" name="page" value="admin">
                <input type="hidden" name="action" value="laporan">
                <div class="filter-row">
                    <div class="filter-group">
                        <label><i class="fas fa-calendar-alt"></i> Tanggal Awal</label>
                        <input type="date" name="tanggal_awal" class="filter-input" 
                               value="<?= htmlspecialchars($tanggal_awal ?? date('Y-m-01')) ?>"
                               onchange="document.getElementById('filterForm').submit()">
                    </div>
                    <div class="filter-group">
                        <label><i class="fas fa-calendar-alt"></i> Tanggal Akhir</label>
                        <input type="date" name="tanggal_akhir" class="filter-input" 
                               value="<?= htmlspecialchars($tanggal_akhir ?? date('Y-m-d')) ?>"
                               onchange="document.getElementById('filterForm').submit()">
                    </div>
                    <div class="filter-group" style="flex:0.5; min-width:100px;">
                        <label>&nbsp;</label>
                        <button type="submit" class="btn btn-primary" style="width:100%; justify-content:center;">
                            <i class="fas fa-filter"></i> Filter
                        </button>
                    </div>
                    <div class="filter-group" style="flex:0.5; min-width:100px;">
                        <label>&nbsp;</label>
                        <a href="?page=admin&action=laporan" class="btn btn-outline" style="width:100%; justify-content:center;">
                            <i class="fas fa-undo"></i> Reset
                        </a>
                    </div>
                </div>
                <div class="filter-info">
                    <i class="fas fa-info-circle"></i>
                    Periode: <strong><?= date('d/m/Y', strtotime($tanggal_awal ?? date('Y-m-01'))) ?></strong> 
                    s.d <strong><?= date('d/m/Y', strtotime($tanggal_akhir ?? date('Y-m-d'))) ?></strong>
                    &nbsp;|&nbsp; 
                    <i class="fas fa-ship"></i> 
                    <strong><?= count($laporanKapal ?? []) ?></strong> Kapal aktif
                    &nbsp;|&nbsp;
                    <i class="fas fa-file-invoice"></i>
                    <strong><?= number_format($summary['total_pesanan'] ?? 0) ?></strong> Pesanan
                </div>
            </form>
        </div>

        <!-- STATISTIK UTAMA -->
        <div class="stats-grid">
            <div class="stat-card primary">
                <span class="stat-icon"><i class="fas fa-shopping-cart" style="color:var(--primary);"></i></span>
                <span class="stat-number"><?= number_format($summary['total_pesanan'] ?? 0) ?></span>
                <span class="stat-label">Total Pesanan</span>
            </div>
            <div class="stat-card success">
                <span class="stat-icon"><i class="fas fa-money-bill-wave" style="color:var(--success);"></i></span>
                <span class="stat-number" style="color:var(--success);">Rp <?= number_format($summary['total_pendapatan'] ?? 0, 0, ',', '.') ?></span>
                <span class="stat-label">Total Pendapatan</span>
            </div>
            <div class="stat-card warning">
                <span class="stat-icon"><i class="fas fa-users" style="color:var(--warning);"></i></span>
                <span class="stat-number"><?= number_format($statistikWisatawan['total_wisatawan'] ?? 0) ?></span>
                <span class="stat-label">Total Wisatawan</span>
            </div>
            <div class="stat-card purple">
                <span class="stat-icon"><i class="fas fa-ship" style="color:var(--purple);"></i></span>
                <span class="stat-number"><?= number_format($totalKapalDipesan ?? 0) ?></span>
                <span class="stat-label">Kapal Dipesan</span>
            </div>
        </div>

        <!-- STATISTIK KEUANGAN -->
        <div class="stats-grid" style="grid-template-columns: repeat(4, 1fr); margin-bottom: 1.5rem;">
            <div class="stat-card primary" style="border-left:4px solid var(--primary); background:var(--primary-bg);">
                <span class="stat-icon"><i class="fas fa-percent" style="color:var(--primary);"></i></span>
                <span class="stat-number" style="color:var(--primary); font-size:1.2rem;">Rp <?= number_format($summary['total_komisi'] ?? 0, 0, ',', '.') ?></span>
                <span class="stat-label">Komisi Admin</span>
            </div>
            <div class="stat-card success" style="border-left:4px solid var(--success); background:var(--success-bg);">
                <span class="stat-icon"><i class="fas fa-hand-holding-usd" style="color:var(--success);"></i></span>
                <span class="stat-number" style="color:#065f46; font-size:1.2rem;">Rp <?= number_format($totalDicairkan ?? 0, 0, ',', '.') ?></span>
                <span class="stat-label">Dana Dicairkan</span>
            </div>
            <div class="stat-card danger" style="border-left:4px solid var(--danger); background:var(--danger-bg);">
                <span class="stat-icon"><i class="fas fa-hand-holding-usd" style="color:var(--danger);"></i></span>
                <span class="stat-number" style="color:#991b1b; font-size:1.2rem;">Rp <?= number_format($totalClaim ?? 0, 0, ',', '.') ?></span>
                <span class="stat-label">Dana Diklaim</span>
            </div>
            <div class="stat-card teal" style="border-left:4px solid var(--teal); background:var(--teal-bg);">
                <span class="stat-icon"><i class="fas fa-wallet" style="color:var(--teal);"></i></span>
                <span class="stat-number" style="color:#0d7a6a; font-size:1.2rem;">Rp <?= number_format(($summary['total_diterima_supir'] ?? 0) - ($totalClaim ?? 0), 0, ',', '.') ?></span>
                <span class="stat-label">Saldo Bersih Supir</span>
            </div>
        </div>

        <!-- GRAFIK -->
        <div class="chart-section">
            <div class="chart-card">
                <div class="chart-header">
                    <h4><i class="fas fa-chart-bar" style="color:var(--primary);"></i> Pendapatan per Kapal</h4>
                    <span class="chart-badge"><i class="fas fa-ship"></i> <?= count($laporanKapal ?? []) ?> Kapal</span>
                </div>
                <canvas id="chartKapal"></canvas>
            </div>
            <div class="chart-card">
                <div class="chart-header">
                    <h4><i class="fas fa-chart-pie" style="color:var(--purple);"></i> Distribusi Pendapatan</h4>
                    <span class="chart-badge"><i class="fas fa-percent"></i> Share</span>
                </div>
                <canvas id="chartDistribusi"></canvas>
            </div>
        </div>

        <!-- GRAFIK TAMBAHAN -->
        <div class="chart-section" style="margin-bottom: 1.5rem;">
            <div class="chart-card">
                <div class="chart-header">
                    <h4><i class="fas fa-chart-line" style="color:var(--success);"></i> Pencairan per Supir</h4>
                    <span class="chart-badge"><i class="fas fa-users"></i> <?= count($laporanPencairan ?? []) ?> Supir</span>
                </div>
                <canvas id="chartPencairan"></canvas>
            </div>
            <div class="chart-card">
                <div class="chart-header">
                    <h4><i class="fas fa-chart-doughnut" style="color:var(--warning);"></i> Status Pembayaran</h4>
                    <span class="chart-badge"><i class="fas fa-credit-card"></i> Payment</span>
                </div>
                <canvas id="chartStatusPembayaran"></canvas>
            </div>
        </div>

        <!-- 1. LAPORAN PER KAPAL -->
        <div class="card-section">
            <div class="card-header">
                <h3><i class="fas fa-ship" style="color:var(--primary);"></i> Laporan Per Kapal</h3>
                <div style="display:flex; gap:0.5rem; flex-wrap:wrap;">
                    <span class="badge badge-primary"><i class="fas fa-ship"></i> <?= count($laporanKapal ?? []) ?> Kapal</span>
                    <span class="badge badge-success"><i class="fas fa-money-bill-wave"></i> Rp <?= number_format(array_sum(array_column($laporanKapal ?? [], 'total_pendapatan')), 0, ',', '.') ?></span>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table" id="tableKapal">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Nama Kapal</th>
                            <th>Pesanan</th>
                            <th>Pendapatan</th>
                            <th>Komisi Admin</th>
                            <th>Diterima Supir</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($laporanKapal)): ?>
                        <tr><td colspan="6" class="text-center text-muted" style="padding:2rem;">
                            <i class="fas fa-inbox" style="font-size:2rem;display:block;margin-bottom:0.5rem;opacity:0.5;"></i>
                            Belum ada data kapal
                        </td></tr>
                        <?php else: ?>
                        <?php $no=1; foreach($laporanKapal as $row): ?>
                        <tr>
                            <td><?= $no++ ?></td>
                            <td><strong><?= htmlspecialchars($row['nama_kapal']) ?></strong></td>
                            <td><?= number_format($row['total_pesanan']) ?></td>
                            <td style="color:var(--primary);font-weight:700;">Rp <?= number_format($row['total_pendapatan'],0,',','.') ?></td>
                            <td>Rp <?= number_format($row['total_komisi'],0,',','.') ?></td>
                            <td style="color:#065f46;font-weight:700;">Rp <?= number_format($row['total_diterima_supir'],0,',','.') ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="5" style="text-align:right;">Grand Total</td>
                            <td style="color:var(--primary);font-weight:800;font-size:1.05rem;">
                                Rp <?= number_format(array_sum(array_column($laporanKapal ?? [], 'total_pendapatan')),0,',','.') ?>
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>

        <!-- 2. DANA DICAIRKAN KE SUPIR -->
        <div class="card-section">
            <div class="card-header">
                <h3><i class="fas fa-hand-holding-usd" style="color:var(--success);"></i> Dana Dicairkan ke Supir</h3>
                <div style="display:flex; gap:0.5rem; flex-wrap:wrap;">
                    <span class="badge badge-success"><i class="fas fa-users"></i> <?= count($laporanPencairan ?? []) ?> Supir</span>
                    <span class="badge badge-primary"><i class="fas fa-money-bill-wave"></i> Rp <?= number_format($totalDicairkan ?? 0, 0, ',', '.') ?></span>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table" id="tablePencairan">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Nama Supir</th>
                            <th>Kontak</th>
                            <th>Kapal</th>
                            <th>Pesanan</th>
                            <th>Total Dicairkan</th>
                            <th>Pencairan Terakhir</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($laporanPencairan)): ?>
                        <tr><td colspan="7" class="text-center text-muted" style="padding:2rem;">
                            <i class="fas fa-inbox" style="font-size:2rem;display:block;margin-bottom:0.5rem;opacity:0.5;"></i>
                            Belum ada dana dicairkan
                        </td></tr>
                        <?php else: ?>
                        <?php $no=1; foreach($laporanPencairan as $row): ?>
                        <tr>
                            <td><?= $no++ ?></td>
                            <td><strong><?= htmlspecialchars($row['supir_nama']) ?></strong></td>
                            <td><?= htmlspecialchars($row['supir_hp'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($row['nama_kapal']) ?></td>
                            <td><?= number_format($row['total_pesanan']) ?></td>
                            <td style="color:#065f46;font-weight:700;">Rp <?= number_format($row['total_dicairkan'],0,',','.') ?></td>
                            <td><?= $row['tanggal_pencairan_terakhir'] ? date('d/m/Y H:i', strtotime($row['tanggal_pencairan_terakhir'])) : '-' ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="5" style="text-align:right;">Grand Total</td>
                            <td style="color:#065f46;font-weight:800;font-size:1.05rem;">
                                Rp <?= number_format($totalDicairkan ?? 0,0,',','.') ?>
                            </td>
                            <td></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>

        <!-- 3. DANA CLAIM WISATAWAN -->
        <div class="card-section">
            <div class="card-header">
                <h3><i class="fas fa-hand-holding-usd" style="color:var(--danger);"></i> Dana Diklaim Wisatawan</h3>
                <div style="display:flex; gap:0.5rem; flex-wrap:wrap;">
                    <span class="badge badge-danger"><i class="fas fa-users"></i> <?= count($laporanClaim ?? []) ?> Claim</span>
                    <span class="badge badge-primary"><i class="fas fa-money-bill-wave"></i> Rp <?= number_format($totalClaim ?? 0, 0, ',', '.') ?></span>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table" id="tableClaim">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Wisatawan</th>
                            <th>Kontak</th>
                            <th>Kode Pesanan</th>
                            <th>Kapal</th>
                            <th>Jumlah Claim</th>
                            <th>Tanggal Claim</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($laporanClaim)): ?>
                        <tr><td colspan="8" class="text-center text-muted" style="padding:2rem;">
                            <i class="fas fa-inbox" style="font-size:2rem;display:block;margin-bottom:0.5rem;opacity:0.5;"></i>
                            Belum ada claim diterima
                        </td></tr>
                        <?php else: ?>
                        <?php $no=1; foreach($laporanClaim as $row): ?>
                        <tr>
                            <td><?= $no++ ?></td>
                            <td><strong><?= htmlspecialchars($row['wisatawan_nama']) ?></strong></td>
                            <td><?= htmlspecialchars($row['wisatawan_hp'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($row['kode_pesanan']) ?></td>
                            <td><?= htmlspecialchars($row['nama_kapal']) ?></td>
                            <td style="color:#991b1b;font-weight:700;">Rp <?= number_format($row['jumlah_claim'],0,',','.') ?></td>
                            <td><?= date('d/m/Y H:i', strtotime($row['tanggal_claim'])) ?></td>
                            <td>
                                <span class="badge badge-success">Diterima</span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="5" style="text-align:right;">Grand Total</td>
                            <td style="color:#991b1b;font-weight:800;font-size:1.05rem;">
                                Rp <?= number_format($totalClaim ?? 0,0,',','.') ?>
                            </td>
                            <td colspan="2"></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>

        <!-- INFO TAMBAHAN -->
        <div class="info-extra">
            <div class="info-extra-item">
                <i class="fas fa-calendar-alt" style="color:var(--primary);"></i> 
                Laporan dibuat: <strong><?= date('d F Y H:i:s') ?></strong>
            </div>
            <div class="info-extra-item">
                <i class="fas fa-users" style="color:var(--warning);"></i> 
                Total Wisatawan: <strong><?= number_format($statistikWisatawan['total_wisatawan'] ?? 0) ?></strong>
            </div>
            <div class="info-extra-item">
                <i class="fas fa-shopping-cart" style="color:var(--primary);"></i> 
                Total Pesanan: <strong><?= number_format($statistikWisatawan['total_pesanan_wisatawan'] ?? 0) ?></strong>
            </div>
            <div class="info-extra-item">
                <i class="fas fa-money-bill-wave" style="color:var(--success);"></i> 
                Total Nilai Pesanan: <strong style="color:var(--success);">
                    Rp <?= number_format($statistikWisatawan['total_nilai_pesanan'] ?? 0, 0, ',', '.') ?>
                </strong>
            </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);">
                    Periode: <?= date('d/m/Y', strtotime($tanggal_awal ?? date('Y-m-01'))) ?> - <?= date('d/m/Y', strtotime($tanggal_akhir ?? date('Y-m-d'))) ?>
                </span>
            </div>
        </div>
    </main>
</div>

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

<!-- ============================================
   JAVASCRIPT - CHART.JS
   ============================================ -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // ============================================
    // DATA DARI PHP
    // ============================================
    const kapalData = <?= json_encode($laporanKapal ?? []) ?>;
    const pencairanData = <?= json_encode($laporanPencairan ?? []) ?>;
    const claimData = <?= json_encode($laporanClaim ?? []) ?>;
    const summary = <?= json_encode($summary ?? ['total_pesanan' => 0, 'total_pendapatan' => 0, 'total_komisi' => 0, 'total_diterima_supir' => 0]) ?>;
    
    // ============================================
    // 1. CHART BAR - Pendapatan per Kapal
    // ============================================
    const ctx1 = document.getElementById('chartKapal');
    if (ctx1 && kapalData.length > 0) {
        const labels = kapalData.map(item => item.nama_kapal);
        const pendapatan = kapalData.map(item => parseInt(item.total_pendapatan) || 0);
        const diterima = kapalData.map(item => parseInt(item.total_diterima_supir) || 0);
        
        new Chart(ctx1, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'Pendapatan',
                        data: pendapatan,
                        backgroundColor: 'rgba(43, 108, 176, 0.8)',
                        borderColor: '#2b6cb0',
                        borderWidth: 2,
                        borderRadius: 4
                    },
                    {
                        label: 'Diterima Supir',
                        data: diterima,
                        backgroundColor: 'rgba(34, 197, 94, 0.8)',
                        borderColor: '#22c55e',
                        borderWidth: 2,
                        borderRadius: 4
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        position: 'top',
                        labels: { font: { size: 10, weight: '600' } }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'Rp ' + value.toLocaleString('id-ID');
                            },
                            font: { size: 9 }
                        }
                    },
                    x: {
                        ticks: { font: { size: 9 } }
                    }
                }
            }
        });
    } else if (ctx1) {
        ctx1.parentElement.innerHTML = `
            <div class="chart-empty">
                <i class="fas fa-chart-bar"></i>
                <p>Belum ada data untuk grafik</p>
            </div>
        `;
    }

    // ============================================
    // 2. CHART DOUGHNUT - Distribusi Pendapatan
    // ============================================
    const ctx2 = document.getElementById('chartDistribusi');
    if (ctx2 && kapalData.length > 0) {
        const labels = kapalData.map(item => item.nama_kapal);
        const data = kapalData.map(item => parseInt(item.total_pendapatan) || 0);
        const colors = [
            '#2b6cb0', '#22c55e', '#f59e0b', '#8b5cf6', '#ef4444', 
            '#06b6d4', '#ec4899', '#14b8a6', '#f97316', '#6366f1'
        ];
        
        new Chart(ctx2, {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: data,
                    backgroundColor: colors.slice(0, labels.length),
                    borderWidth: 2,
                    borderColor: '#fff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { 
                            font: { size: 9 },
                            padding: 10
                        }
                    }
                },
                cutout: '60%'
            }
        });
    } else if (ctx2) {
        ctx2.parentElement.innerHTML = `
            <div class="chart-empty">
                <i class="fas fa-chart-pie"></i>
                <p>Belum ada data untuk grafik</p>
            </div>
        `;
    }

    // ============================================
    // 3. CHART BAR - Pencairan per Supir
    // ============================================
    const ctx3 = document.getElementById('chartPencairan');
    if (ctx3 && pencairanData.length > 0) {
        const labels = pencairanData.map(item => item.supir_nama);
        const data = pencairanData.map(item => parseInt(item.total_dicairkan) || 0);
        
        new Chart(ctx3, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Dana Dicairkan',
                    data: data,
                    backgroundColor: 'rgba(34, 197, 94, 0.8)',
                    borderColor: '#22c55e',
                    borderWidth: 2,
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        position: 'top',
                        labels: { font: { size: 10, weight: '600' } }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'Rp ' + value.toLocaleString('id-ID');
                            },
                            font: { size: 9 }
                        }
                    },
                    x: {
                        ticks: { font: { size: 9 } }
                    }
                }
            }
        });
    } else if (ctx3) {
        ctx3.parentElement.innerHTML = `
            <div class="chart-empty">
                <i class="fas fa-chart-bar"></i>
                <p>Belum ada data pencairan</p>
            </div>
        `;
    }

    // ============================================
    // 4. CHART DOUGHNUT - Status Pembayaran (dari summary)
    // ============================================
    const ctx4 = document.getElementById('chartStatusPembayaran');
    if (ctx4) {
        // Data dummy untuk status pembayaran (akan disesuaikan dengan data real)
        // Anda bisa menambahkan query di controller untuk mendapatkan data ini
        const paymentData = {
            lunas: <?= $stats['lunas'] ?? 0 ?>,
            menunggu: <?= $stats['menunggu_pembayaran'] ?? 0 ?>,
            belum: <?= $stats['belum_bayar'] ?? 0 ?>,
            gagal: <?= $stats['gagal'] ?? 0 ?>
        };
        
        const total = paymentData.lunas + paymentData.menunggu + paymentData.belum + paymentData.gagal;
        
        if (total > 0) {
            new Chart(ctx4, {
                type: 'doughnut',
                data: {
                    labels: ['Lunas', 'Menunggu Konfirmasi', 'Belum Bayar', 'Gagal'],
                    datasets: [{
                        data: [paymentData.lunas, paymentData.menunggu, paymentData.belum, paymentData.gagal],
                        backgroundColor: ['#22c55e', '#f59e0b', '#a0aec0', '#ef4444'],
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: { 
                                font: { size: 9 },
                                padding: 10
                            }
                        }
                    },
                    cutout: '60%'
                }
            });
        } else {
            ctx4.parentElement.innerHTML = `
                <div class="chart-empty">
                    <i class="fas fa-chart-doughnut"></i>
                    <p>Belum ada data pembayaran</p>
                </div>
            `;
        }
    }

    console.log('✅ Laporan loaded');
    console.log('📊 Kapal:', kapalData.length);
    console.log('📊 Supir:', pencairanData.length);
    console.log('📊 Claim:', claimData.length);
});

// ============================================
// EXPORT PDF
// ============================================
function exportPDF() {
    const element = document.getElementById('laporanContent');
    const btn = event.target;
    const originalHtml = btn.innerHTML;
    
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Memproses...';
    btn.disabled = true;

    const opt = {
        margin: [10, 10, 10, 10],
        filename: 'Laporan_Admin_' + new Date().toISOString().slice(0,10) + '.pdf',
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { 
            scale: 2, 
            useCORS: true, 
            letterRendering: true,
            logging: false
        },
        jsPDF: { 
            unit: 'mm', 
            format: 'a4', 
            orientation: 'portrait' 
        },
        pagebreak: { 
            mode: ['avoid-all', 'css', 'legacy'] 
        }
    };

    html2pdf().set(opt).from(element).save().then(function() {
        btn.innerHTML = originalHtml;
        btn.disabled = false;
        showToast('✅ PDF berhasil diunduh', 'success');
    }).catch(function(err) {
        console.error('PDF Error:', err);
        btn.innerHTML = originalHtml;
        btn.disabled = false;
        showToast('❌ Gagal export PDF: ' + err.message, 'error');
    });
}

// ============================================
// EXPORT EXCEL
// ============================================
function exportExcel() {
    const tables = ['tableKapal', 'tablePencairan', 'tableClaim'];
    let allData = '';
    
    tables.forEach(tableId => {
        const table = document.getElementById(tableId);
        if (!table) return;
        
        const rows = table.querySelectorAll('tr');
        rows.forEach(row => {
            const cols = row.querySelectorAll('td, th');
            const rowData = [];
            cols.forEach(col => {
                let text = col.textContent.trim().replace(/,/g, ';');
                rowData.push(text);
            });
            if (rowData.length > 0) {
                allData += rowData.join(',') + '\n';
            }
        });
        allData += '\n';
    });
    
    if (!allData) {
        showToast('⚠️ Tidak ada data untuk diexport', 'warning');
        return;
    }
    
    const blob = new Blob([allData], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'Laporan_Admin_' + new Date().toISOString().slice(0,10) + '.csv';
    link.click();
    URL.revokeObjectURL(link.href);
    
    showToast('✅ Excel berhasil diunduh', 'success');
}

// ============================================
// TOAST NOTIFICATION
// ============================================
function showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    if (!container) {
        const newContainer = document.createElement('div');
        newContainer.id = 'toastContainer';
        document.body.appendChild(newContainer);
    }
    
    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>
    `;
    
    document.getElementById('toastContainer').appendChild(toast);
    setTimeout(() => {
        if (toast.parentElement) {
            toast.style.animation = 'slideOutRight 0.3s ease';
            setTimeout(() => toast.remove(), 300);
        }
    }, 5000);
}
</script>

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