<?php
// Konfigurasi Database
// $host = 'localhost';
// $user = 'root';
// $pass = '';
// $db   = 'pos_m';
// // Error reporting untuk development
error_reporting(E_ALL);
ini_set('display_errors', 1);
try {
    // Koneksi dengan error handling
    // $conn = new mysqli($host, $user, $pass, $db);
include_once '../data.php';
$conn = new mysqli($servername, $username, $password, $dbname);    
    if ($conn->connect_error) {
        throw new Exception("Koneksi database gagal: " . $conn->connect_error);
    }
    $conn->set_charset("utf8");
    
    // Default range tanggal: bulan ini
    $start_date = date('Y-m-01');
    $end_date = date('Y-m-t');
    
    // Validasi dan sanitasi input
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['start_date']) && isset($_POST['end_date'])) {
            $start_date = filter_var($_POST['start_date'], FILTER_SANITIZE_STRING);
            $end_date = filter_var($_POST['end_date'], FILTER_SANITIZE_STRING);
        }
        $selected_cabang = isset($_POST['cabang']) ? $_POST['cabang'] : '';
    } else {
        $selected_cabang = '';
    }
    
    // Ambil daftar cabang untuk filter
    $cabang_query = "SELECT kode, nama FROM cabang ORDER BY nama ASC";
    $cabang_result = $conn->query($cabang_query);
    $cabang_list = [];
    while ($row = $cabang_result->fetch_assoc()) {
        $cabang_list[] = $row;
    }
    
    // Tentukan apakah menampilkan data global atau per cabang
    $is_global_view = empty($selected_cabang);
    
    // Query untuk data ringkasan (penjualan)
    if ($is_global_view) {
        // Data global (semua cabang)
        $summary_sql = "
        SELECT 
            j.cab, cabang.nama AS cabang_nama,
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan,
            SUM(CAST(p.quantity AS DECIMAL(10,2))) as total_quantity,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            AVG(CAST(p.netto AS DECIMAL(15,2))) as avg_transaksi,
            SUM(CAST(p.discr AS DECIMAL(15,2))) as total_diskon,
            SUM(CAST(p.ppn AS DECIMAL(15,2))) as total_ppn,
            SUM(CAST(p.service AS DECIMAL(15,2))) as total_service
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        LEFT JOIN cabang ON j.cab = cabang.kode
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND p.payment < '01'
        GROUP BY j.cab, cabang.nama
        ORDER BY total_penjualan DESC
        ";
        
        $stmt = $conn->prepare($summary_sql);
        $stmt->bind_param("ss", $start_date, $end_date);
        $stmt->execute();
        $summary_result = $stmt->get_result();
        
        $summary_data = [];
        while ($row = $summary_result->fetch_assoc()) {
            $summary_data[] = $row;
        }
        $stmt->close();
        
        // Hitung total keseluruhan
        $total_keseluruhan = 0;
        $total_transaksi_keseluruhan = 0;
        $total_quantity_keseluruhan = 0;
        foreach ($summary_data as $data) {
            $total_keseluruhan += $data['total_penjualan'];
            $total_transaksi_keseluruhan += $data['total_transaksi'];
            $total_quantity_keseluruhan += $data['total_quantity'];
        }
        
        $view_title = "Dashboard Penjualan Global";
        $cabang_info = "Semua Cabang";
        
    } else {
        // Data per cabang
        $cabang_info_query = "SELECT nama FROM cabang WHERE kode = ?";
        $stmt = $conn->prepare($cabang_info_query);
        $stmt->bind_param("s", $selected_cabang);
        $stmt->execute();
        $cabang_info_result = $stmt->get_result();
        
        // Perbaikan: Cek apakah query mengembalikan hasil
        if ($cabang_info_result && $cabang_info_result->num_rows > 0) {
            $cabang_info_row = $cabang_info_result->fetch_assoc();
            $cabang_info = $cabang_info_row['nama'];
        } else {
            // Jika cabang tidak ditemukan, gunakan kode sebagai fallback
            $cabang_info = "Cabang " . $selected_cabang;
        }
        $stmt->close();
        
        $summary_sql = "
        SELECT 
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan,
            SUM(CAST(p.quantity AS DECIMAL(10,2))) as total_quantity,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            AVG(CAST(p.netto AS DECIMAL(15,2))) as avg_transaksi,
            SUM(CAST(p.discr AS DECIMAL(15,2))) as total_diskon,
            SUM(CAST(p.ppn AS DECIMAL(15,2))) as total_ppn,
            SUM(CAST(p.service AS DECIMAL(15,2))) as total_service
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND j.cab = ? AND p.payment < '01'
        ";
        
        $stmt = $conn->prepare($summary_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
        $stmt->execute();
        $summary_result = $stmt->get_result();
        
        // Perbaikan: Cek apakah query mengembalikan hasil
        if ($summary_result && $summary_result->num_rows > 0) {
            $summary_data = [$summary_result->fetch_assoc()];
        } else {
            // Jika tidak ada data, gunakan nilai default
            $summary_data = [[
                'total_penjualan' => 0,
                'total_quantity' => 0,
                'total_transaksi' => 0,
                'avg_transaksi' => 0,
                'total_diskon' => 0,
                'total_ppn' => 0,
                'total_service' => 0
            ]];
        }
        $stmt->close();
        
        // Set total values
        $total_keseluruhan = $summary_data[0]['total_penjualan'];
        $total_transaksi_keseluruhan = $summary_data[0]['total_transaksi'];
        $total_quantity_keseluruhan = $summary_data[0]['total_quantity'];
        
        $view_title = "Dashboard Penjualan: " . $cabang_info;
    }
    
    // Query untuk data per hari (untuk grafik tren) - penjualan
    if ($is_global_view) {
        $tren_sql = "
        SELECT 
            j.tanggal,
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan,
            COUNT(DISTINCT j.nomor) as total_transaksi
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND p.payment < '01'
        GROUP BY j.tanggal
        ORDER BY j.tanggal ASC
        ";
        
        $stmt = $conn->prepare($tren_sql);
        $stmt->bind_param("ss", $start_date, $end_date);
    } else {
        $tren_sql = "
        SELECT 
            j.tanggal,
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan,
            COUNT(DISTINCT j.nomor) as total_transaksi
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND j.cab = ? AND p.payment < '01'
        GROUP BY j.tanggal
        ORDER BY j.tanggal ASC
        ";
        
        $stmt = $conn->prepare($tren_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
    }
    
    $stmt->execute();
    $tren_result = $stmt->get_result();
    
    $tren_data = [];
    while ($row = $tren_result->fetch_assoc()) {
        $tren_data[] = $row;
    }
    $stmt->close();
    
    // Query untuk data per produk (top 10) - penjualan
    if ($is_global_view) {
        $produk_sql = "
        SELECT 
            p.kode, p.name AS nama_barang, p.group_name,
            SUM(CAST(p.quantity AS DECIMAL(10,2))) as total_quantity,
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND p.payment < '01'
        GROUP BY p.kode, p.name, p.group_name
        ORDER BY total_quantity DESC
        LIMIT 10
        ";
        
        $stmt = $conn->prepare($produk_sql);
        $stmt->bind_param("ss", $start_date, $end_date);
    } else {
        $produk_sql = "
        SELECT 
            p.kode, p.name AS nama_barang, p.group_name,
            SUM(CAST(p.quantity AS DECIMAL(10,2))) as total_quantity,
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND j.cab = ? AND p.payment < '01'
        GROUP BY p.kode, p.name, p.group_name
        ORDER BY total_quantity DESC
        LIMIT 10
        ";
        
        $stmt = $conn->prepare($produk_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
    }
    
    $stmt->execute();
    $produk_result = $stmt->get_result();
    
    $produk_data = [];
    while ($row = $produk_result->fetch_assoc()) {
        $produk_data[] = $row;
    }
    $stmt->close();
    
    // Query untuk data per tipe transaksi - penjualan
    if ($is_global_view) {
        $tipe_sql = "
        SELECT 
            tt.nama AS tipe_transaksi,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        LEFT JOIN tipe_transaksi tt ON j.tipe = tt.kode
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND p.payment < '01'
        GROUP BY tt.nama
        ORDER BY total_transaksi DESC
        ";
        
        $stmt = $conn->prepare($tipe_sql);
        $stmt->bind_param("ss", $start_date, $end_date);
    } else {
        $tipe_sql = "
        SELECT 
            tt.nama AS tipe_transaksi,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        LEFT JOIN tipe_transaksi tt ON j.tipe = tt.kode
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND j.cab = ? AND p.payment < '01'
        GROUP BY tt.nama
        ORDER BY total_transaksi DESC
        ";
        
        $stmt = $conn->prepare($tipe_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
    }
    
    $stmt->execute();
    $tipe_result = $stmt->get_result();
    
    $tipe_data = [];
    while ($row = $tipe_result->fetch_assoc()) {
        $tipe_data[] = $row;
    }
    $stmt->close();
    
    // Hitung total untuk tipe transaksi
    $total_tipe_transaksi = 0;
    $total_tipe_penjualan = 0;
    foreach ($tipe_data as $data) {
        $total_tipe_transaksi += $data['total_transaksi'];
        $total_tipe_penjualan += $data['total_penjualan'];
    }
    
    // Query untuk data metode pembayaran (menggantikan query per jam)
    if ($is_global_view) {
        $payment_sql = "
        SELECT 
            p.name ,
            CASE 
                WHEN p.payment = '01' THEN 'Tunai'
                WHEN p.payment = '02' THEN 'Kartu Kredit'
                WHEN p.payment = '03' THEN 'Kartu Debit'
                WHEN p.payment = '04' THEN 'Transfer Bank'
                WHEN p.payment = '05' THEN 'E-Wallet'
                WHEN p.payment = '06' THEN 'Voucher'
                ELSE p.payment
            END AS metode_pembayaran,
            p.payment,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            SUM(CAST(p.harga AS DECIMAL(15,2))) as total_penjualan,
            AVG(CAST(p.harga AS DECIMAL(15,2))) as avg_transaksi
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND p.payment > '01' AND p.harga > 0
        GROUP BY p.name
        ORDER BY total_penjualan DESC
        ";
        
        $stmt = $conn->prepare($payment_sql);
        $stmt->bind_param("ss", $start_date, $end_date);
    } else {
        $payment_sql = "
        SELECT 
            p.name,
            CASE 
                WHEN p.payment = '01' THEN 'Tunai'
                WHEN p.payment = '02' THEN 'Kartu Kredit'
                WHEN p.payment = '03' THEN 'Kartu Debit'
                WHEN p.payment = '04' THEN 'Transfer Bank'
                WHEN p.payment = '05' THEN 'E-Wallet'
                WHEN p.payment = '06' THEN 'Voucher'
                ELSE p.payment
            END AS metode_pembayaran,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            SUM(CAST(p.harga AS DECIMAL(15,2))) as total_penjualan,
            AVG(CAST(p.harga AS DECIMAL(15,2))) as avg_transaksi
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND j.cab = ? AND p.payment > '01' AND p.harga > 0
        GROUP BY p.name
        ORDER BY total_penjualan DESC
        ";
        
        $stmt = $conn->prepare($payment_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
    }
    
    $stmt->execute();
    $payment_result = $stmt->get_result();
    
    $payment_data = [];
    while ($row = $payment_result->fetch_assoc()) {
        $payment_data[] = $row;
    }
    $stmt->close();
    
    // Hitung total untuk metode pembayaran
    $total_payment_transaksi = 0;
    $total_payment_penjualan = 0;
    foreach ($payment_data as $data) {
        $total_payment_transaksi += $data['total_transaksi'];
        $total_payment_penjualan += $data['total_penjualan'];
    }
    $total_payment_avg = $total_payment_transaksi > 0 ? $total_payment_penjualan / $total_payment_transaksi : 0;
    
    // Query untuk data per kasir (hanya untuk view per cabang) - penjualan
    if (!$is_global_view) {
        $kasir_sql = "
        SELECT 
            u.nama AS kasir_nama,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        LEFT JOIN users u ON j.kasir = u.kode
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND j.cab = ? AND p.payment < '01'
        GROUP BY u.nama
        ORDER BY total_transaksi DESC
        ";
        
        $stmt = $conn->prepare($kasir_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
        $stmt->execute();
        $kasir_result = $stmt->get_result();
        
        $kasir_data = [];
        while ($row = $kasir_result->fetch_assoc()) {
            $kasir_data[] = $row;
        }
        $stmt->close();
        
        // Hitung total untuk performa kasir
        $total_kasir_transaksi = 0;
        $total_kasir_penjualan = 0;
        foreach ($kasir_data as $data) {
            $total_kasir_transaksi += $data['total_transaksi'];
            $total_kasir_penjualan += $data['total_penjualan'];
        }
        $total_kasir_avg = $total_kasir_transaksi > 0 ? $total_kasir_penjualan / $total_kasir_transaksi : 0;
    } else {
        $kasir_data = [];
        $total_kasir_transaksi = 0;
        $total_kasir_penjualan = 0;
        $total_kasir_avg = 0;
    }
    
    // Query untuk data per kategori produk - penjualan
    if ($is_global_view) {
        $kategori_sql = "
        SELECT 
            p.group_name,
            SUM(CAST(p.quantity AS DECIMAL(10,2))) as total_quantity,
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND p.payment < '01'
        GROUP BY p.group_name
        ORDER BY total_penjualan DESC
        ";
        
        $stmt = $conn->prepare($kategori_sql);
        $stmt->bind_param("ss", $start_date, $end_date);
    } else {
        $kategori_sql = "
        SELECT 
            p.group_name,
            SUM(CAST(p.quantity AS DECIMAL(10,2))) as total_quantity,
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND j.cab = ? AND p.payment < '01'
        GROUP BY p.group_name
        ORDER BY total_penjualan DESC
        ";
        
        $stmt = $conn->prepare($kategori_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
    }
    
    $stmt->execute();
    $kategori_result = $stmt->get_result();
    
    $kategori_data = [];
    while ($row = $kategori_result->fetch_assoc()) {
        $kategori_data[] = $row;
    }
    $stmt->close();
    
    // Query untuk data per hari dalam seminggu - penjualan
    if ($is_global_view) {
        $hari_sql = "
        SELECT 
            DAYNAME(j.tanggal) as hari,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND p.payment < '01'
        GROUP BY DAYNAME(j.tanggal)
        ORDER BY 
            CASE DAYNAME(j.tanggal)
                WHEN 'Monday' THEN 1
                WHEN 'Tuesday' THEN 2
                WHEN 'Wednesday' THEN 3
                WHEN 'Thursday' THEN 4
                WHEN 'Friday' THEN 5
                WHEN 'Saturday' THEN 6
                WHEN 'Sunday' THEN 7
            END
        ";
        
        $stmt = $conn->prepare($hari_sql);
        $stmt->bind_param("ss", $start_date, $end_date);
    } else {
        $hari_sql = "
        SELECT 
            DAYNAME(j.tanggal) as hari,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND j.cab = ? AND p.payment < '01'
        GROUP BY DAYNAME(j.tanggal)
        ORDER BY 
            CASE DAYNAME(j.tanggal)
                WHEN 'Monday' THEN 1
                WHEN 'Tuesday' THEN 2
                WHEN 'Wednesday' THEN 3
                WHEN 'Thursday' THEN 4
                WHEN 'Friday' THEN 5
                WHEN 'Saturday' THEN 6
                WHEN 'Sunday' THEN 7
            END
        ";
        
        $stmt = $conn->prepare($hari_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
    }
    
    $stmt->execute();
    $hari_result = $stmt->get_result();
    
    $hari_data = [];
    while ($row = $hari_result->fetch_assoc()) {
        $hari_data[] = $row;
    }
    $stmt->close();
    
    $conn->close();
    
} catch (Exception $e) {
    $error_message = $e->getMessage();
    $summary_data = [];
    $tren_data = [];
    $produk_data = [];
    $tipe_data = [];
    $payment_data = [];
    $kasir_data = [];
    $kategori_data = [];
    $hari_data = [];
    $cabang_list = [];
    $total_keseluruhan = 0;
    $total_transaksi_keseluruhan = 0;
    $total_quantity_keseluruhan = 0;
    $total_tipe_transaksi = 0;
    $total_tipe_penjualan = 0;
    $total_payment_transaksi = 0;
    $total_payment_penjualan = 0;
    $total_payment_avg = 0;
    $total_kasir_transaksi = 0;
    $total_kasir_penjualan = 0;
    $total_kasir_avg = 0;
    $view_title = "Dashboard Penjualan";
    $cabang_info = "Error";
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Penjualan Multi-Cabang</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
            color: #333;
        }
        
        .navbar {
            background-color: #2c3e50 !important;
            box-shadow: 0 2px 4px rgba(0,0,0,.1);
        }
        
        .navbar-brand {
            font-weight: 700;
            color: white !important;
        }
        
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            margin-bottom: 20px;
            transition: all 0.3s;
        }
        
        .card:hover {
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid rgba(0,0,0,.05);
            font-weight: 600;
            color: #2c3e50;
        }
        
        .stat-card {
            border-left: 4px solid;
            padding: 15px;
            height: 100%;
        }
        
        .stat-card.primary {
            border-left-color: #007bff;
        }
        
        .stat-card.success {
            border-left-color: #28a745;
        }
        
        .stat-card.warning {
            border-left-color: #ffc107;
        }
        
        .stat-card.danger {
            border-left-color: #dc3545;
        }
        
        .stat-card.info {
            border-left-color: #17a2b8;
        }
        
        .stat-value {
            font-size: 24px;
            font-weight: 700;
            margin: 10px 0;
        }
        
        .stat-label {
            color: #6c757d;
            font-size: 14px;
        }
        
        .stat-icon {
            font-size: 32px;
            opacity: 0.7;
        }
        
        .filter-section {
            background-color: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
        }
        
        .chart-container {
            position: relative;
            height: 300px;
            width: 100%;
        }
        
        .table-responsive {
            border-radius: 8px;
        }
        
        .table th {
            background-color: #f8f9fa;
            border-top: none;
            font-weight: 600;
            color: #495057;
        }
        
        .badge {
            font-weight: 500;
        }
        
        .error-message {
            background-color: #fff0f1;
            color: #d90429;
            border-left: 5px solid #d90429;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .no-data {
            background-color: #fff9e6;
            color: #ff8c00;
            border-left: 5px solid #ff8c00;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .footer {
            margin-top: 30px;
            padding: 20px 0;
            color: #6c757d;
            font-size: 14px;
            text-align: center;
            border-top: 1px solid #e9ecef;
        }
        
        .dashboard-title {
            color: #2c3e50;
            font-weight: 700;
            margin-bottom: 20px;
        }
        
        .view-info {
            background-color: #e7f5ff;
            border-left: 4px solid #007bff;
            padding: 10px 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        
        .payment-badge {
            display: inline-block;
            padding: 0.35em 0.65em;
            font-size: 0.75em;
            font-weight: 700;
            line-height: 1;
            text-align: center;
            white-space: nowrap;
            vertical-align: baseline;
            border-radius: 0.25rem;
        }
        
        .payment-02 {
            background-color: #cfe2ff;
            color: #084298;
        }
        
        .payment-03 {
            background-color: #cff4fc;
            color: #055160;
        }
        
        .payment-04 {
            background-color: #d1e7dd;
            color: #0f5132;
        }
        
        .payment-05 {
            background-color: #f8d7da;
            color: #842029;
        }
        
        .payment-06 {
            background-color: #fff3cd;
            color: #664d03;
        }
        
        .total-row {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        
        .total-row td {
            border-top: 2px solid #dee2e6;
        }
    </style>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="fas fa-chart-line me-2"></i>Dashboard Penjualan
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <div class="navbar-nav ms-auto">
                    <span class="navbar-text">
                        <i class="far fa-calendar-alt me-1"></i>
                        <?= date('d/m/Y', strtotime($start_date)) ?> - <?= date('d/m/Y', strtotime($end_date)) ?>
                    </span>
                </div>
            </div>
        </div>
    </nav>
    <div class="container-fluid py-4">
        <!-- Filter Section -->
        <div class="filter-section">
            <form id="filterForm" method="POST" action="">
                <div class="row g-3 align-items-end">
                    <div class="col-md-3">
                        <label for="start_date" class="form-label">Tanggal Mulai</label>
                        <input type="date" class="form-control" id="start_date" name="start_date" 
                               value="<?= htmlspecialchars($start_date, ENT_QUOTES, 'UTF-8') ?>" required>
                    </div>
                    <div class="col-md-3">
                        <label for="end_date" class="form-label">Tanggal Akhir</label>
                        <input type="date" class="form-control" id="end_date" name="end_date" 
                               value="<?= htmlspecialchars($end_date, ENT_QUOTES, 'UTF-8') ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label for="cabang" class="form-label">Cabang</label>
                        <select class="form-select" id="cabang" name="cabang">
                            <option value="">Semua Cabang</option>
                            <?php foreach ($cabang_list as $cabang): ?>
                                <option value="<?= $cabang['kode'] ?>" <?= ($selected_cabang == $cabang['kode']) ? 'selected' : '' ?>>
                                    <?= $cabang['nama'] ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-filter me-2"></i>Tampilkan
                        </button>
                    </div>
                </div>
            </form>
        </div>
        <?php if (isset($error_message)): ?>
            <div class="error-message">
                <i class="fas fa-exclamation-triangle me-2"></i>Error: <?= htmlspecialchars($error_message) ?>
            </div>
        <?php elseif (empty($summary_data)): ?>
            <div class="no-data">
                <i class="fas fa-info-circle me-2"></i>Tidak ada data penjualan untuk rentang tanggal ini.
            </div>
        <?php else: ?>
            <!-- Dashboard Title and Info -->
            <div class="row mb-3">
                <div class="col-12">
                    <h2 class="dashboard-title"><?= $view_title ?></h2>
                    <div class="view-info">
                        <i class="fas fa-info-circle me-2"></i>Menampilkan data untuk: <strong><?= $cabang_info ?></strong>
                    </div>
                </div>
            </div>
            <!-- Summary Cards -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="card stat-card primary">
                        <div class="card-body d-flex justify-content-between align-items-center">
                            <div>
                                <div class="stat-label">Total Penjualan</div>
                                <div class="stat-value">Rp <?= number_format($total_keseluruhan, 0, ',', '.') ?></div>
                            </div>
                            <div class="stat-icon text-primary">
                                <i class="fas fa-money-bill-wave"></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card stat-card success">
                        <div class="card-body d-flex justify-content-between align-items-center">
                            <div>
                                <div class="stat-label">Total Transaksi</div>
                                <div class="stat-value"><?= number_format($total_transaksi_keseluruhan, 0, ',', '.') ?></div>
                            </div>
                            <div class="stat-icon text-success">
                                <i class="fas fa-shopping-cart"></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card stat-card warning">
                        <div class="card-body d-flex justify-content-between align-items-center">
                            <div>
                                <div class="stat-label">Rata-rata Transaksi</div>
                                <div class="stat-value">Rp <?= number_format($total_transaksi_keseluruhan > 0 ? $total_keseluruhan / $total_transaksi_keseluruhan : 0, 0, ',', '.') ?></div>
                            </div>
                            <div class="stat-icon text-warning">
                                <i class="fas fa-chart-line"></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card stat-card info">
                        <div class="card-body d-flex justify-content-between align-items-center">
                            <div>
                                <div class="stat-label">Total Quantity</div>
                                <div class="stat-value"><?= number_format($total_quantity_keseluruhan, 0, ',', '.') ?></div>
                            </div>
                            <div class="stat-icon text-info">
                                <i class="fas fa-boxes"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Charts Row 1 -->
            <div class="row mb-4">
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-header">
                            <i class="fas fa-chart-line me-2"></i>Tren Penjualan Harian
                        </div>
                        <div class="card-body">
                            <div class="chart-container">
                                <canvas id="salesTrendChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-header">
                            <i class="fas fa-chart-pie me-2"></i>Penjualan per Kategori
                        </div>
                        <div class="card-body">
                            <div class="chart-container">
                                <canvas id="categoryChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Charts Row 2 -->
            <div class="row mb-4">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <i class="fas fa-credit-card me-2"></i>Metode Pembayaran
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>Metode Pembayaran</th>
                                            <th class="text-end">Transaksi</th>
                                            <th class="text-end">Total Penjualan</th>
                                            <th class="text-end">Rata-rata</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($payment_data as $data): ?>
                                            <tr>
                                                <td>
                                                    <span class="payment-badge payment-<?= $data['name'] ?>">
                                                        <?= $data['name'] ?>
                                                    </span>
                                                </td>
                                                <td class="text-end"><?= number_format($data['total_transaksi'], 0, ',', '.') ?></td>
                                                <td class="text-end">Rp <?= number_format($data['total_penjualan'], 0, ',', '.') ?></td>
                                                <td class="text-end">Rp <?= number_format($data['avg_transaksi'], 0, ',', '.') ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                    <tfoot>
                                        <tr class="total-row">
                                            <td><strong>TOTAL</strong></td>
                                            <td class="text-end"><strong><?= number_format($total_payment_transaksi, 0, ',', '.') ?></strong></td>
                                            <td class="text-end"><strong>Rp <?= number_format($total_payment_penjualan, 0, ',', '.') ?></strong></td>
                                            <td class="text-end"><strong>Rp <?= number_format($total_payment_avg, 0, ',', '.') ?></strong></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <i class="fas fa-calendar-week me-2"></i>Distribusi Transaksi per Hari
                        </div>
                        <div class="card-body">
                            <div class="chart-container">
                                <canvas id="dailyChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Tables Row -->
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <i class="fas fa-box me-2"></i>Produk Terlaris
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>Produk</th>
                                            <th>Kategori</th>
                                            <th class="text-end">Qty</th>
                                            <th class="text-end">Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($produk_data as $data): ?>
                                            <tr>
                                                <td><?= $data['nama_barang'] ?></td>
                                                <td><span class="badge bg-secondary"><?= $data['group_name'] ?></span></td>
                                                <td class="text-end"><?= number_format($data['total_quantity'], 0, ',', '.') ?></td>
                                                <td class="text-end">Rp <?= number_format($data['total_penjualan'], 0, ',', '.') ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <i class="fas fa-credit-card me-2"></i>Tipe Transaksi
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>Tipe Transaksi</th>
                                            <th class="text-end">Transaksi</th>
                                            <th class="text-end">Total Penjualan</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($tipe_data as $data): ?>
                                            <tr>
                                                <td><?= $data['tipe_transaksi'] ?></td>
                                                <td class="text-end"><?= number_format($data['total_transaksi'], 0, ',', '.') ?></td>
                                                <td class="text-end">Rp <?= number_format($data['total_penjualan'], 0, ',', '.') ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                    <tfoot>
                                        <tr class="total-row">
                                            <td><strong>TOTAL</strong></td>
                                            <td class="text-end"><strong><?= number_format($total_tipe_transaksi, 0, ',', '.') ?></strong></td>
                                            <td class="text-end"><strong>Rp <?= number_format($total_tipe_penjualan, 0, ',', '.') ?></strong></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Additional Table for Branch View -->
            <?php if (!$is_global_view && !empty($kasir_data)): ?>
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <i class="fas fa-user me-2"></i>Performa Kasir
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Kasir</th>
                                                <th class="text-end">Transaksi</th>
                                                <th class="text-end">Total Penjualan</th>
                                                <th class="text-end">Rata-rata Transaksi</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($kasir_data as $data): ?>
                                                <tr>
                                                    <td><?= $data['kasir_nama'] ?></td>
                                                    <td class="text-end"><?= number_format($data['total_transaksi'], 0, ',', '.') ?></td>
                                                    <td class="text-end">Rp <?= number_format($data['total_penjualan'], 0, ',', '.') ?></td>
                                                    <td class="text-end">Rp <?= number_format($data['total_transaksi'] > 0 ? $data['total_penjualan'] / $data['total_transaksi'] : 0, 0, ',', '.') ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                        <tfoot>
                                            <tr class="total-row">
                                                <td><strong>TOTAL</strong></td>
                                                <td class="text-end"><strong><?= number_format($total_kasir_transaksi, 0, ',', '.') ?></strong></td>
                                                <td class="text-end"><strong>Rp <?= number_format($total_kasir_penjualan, 0, ',', '.') ?></strong></td>
                                                <td class="text-end"><strong>Rp <?= number_format($total_kasir_avg, 0, ',', '.') ?></strong></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            <!-- Additional Table for Global View -->
            <?php if ($is_global_view): ?>
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <i class="fas fa-building me-2"></i>Penjualan per Cabang
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Cabang</th>
                                                <th class="text-end">Total Penjualan</th>
                                                <th class="text-end">Transaksi</th>
                                                <th class="text-end">Avg. Transaksi</th>
                                                <th class="text-end">Total Qty</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($summary_data as $data): ?>
                                                <tr>
                                                    <td><?= $data['cabang_nama'] ?></td>
                                                    <td class="text-end">Rp <?= number_format($data['total_penjualan'], 0, ',', '.') ?></td>
                                                    <td class="text-end"><?= number_format($data['total_transaksi'], 0, ',', '.') ?></td>
                                                    <td class="text-end">Rp <?= number_format($data['total_transaksi'] > 0 ? $data['total_penjualan'] / $data['total_transaksi'] : 0, 0, ',', '.') ?></td>
                                                    <td class="text-end"><?= number_format($data['total_quantity'], 0, ',', '.') ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                        <tfoot>
                                            <tr class="total-row">
                                                <td><strong>TOTAL</strong></td>
                                                <td class="text-end"><strong>Rp <?= number_format($total_keseluruhan, 0, ',', '.') ?></strong></td>
                                                <td class="text-end"><strong><?= number_format($total_transaksi_keseluruhan, 0, ',', '.') ?></strong></td>
                                                <td class="text-end"><strong>Rp <?= number_format($total_transaksi_keseluruhan > 0 ? $total_keseluruhan / $total_transaksi_keseluruhan : 0, 0, ',', '.') ?></strong></td>
                                                <td class="text-end"><strong><?= number_format($total_quantity_keseluruhan, 0, ',', '.') ?></strong></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
    <footer class="footer">
        <div class="container-fluid">
            <p class="mb-0">&copy; <?= date('Y') ?> Dashboard Penjualan Multi-Cabang. All rights reserved.</p>
        </div>
    </footer>
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Sales Trend Chart
            const salesTrendCtx = document.getElementById('salesTrendChart').getContext('2d');
            new Chart(salesTrendCtx, {
                type: 'line',
                data: {
                    labels: <?= json_encode(array_column($tren_data, 'tanggal')) ?>,
                    datasets: [{
                        label: 'Penjualan (Rp)',
                        data: <?= json_encode(array_column($tren_data, 'total_penjualan')) ?>,
                        backgroundColor: 'rgba(0, 123, 255, 0.1)',
                        borderColor: 'rgba(0, 123, 255, 1)',
                        borderWidth: 2,
                        tension: 0.3,
                        fill: true
                    }, {
                        label: 'Transaksi',
                        data: <?= json_encode(array_column($tren_data, 'total_transaksi')) ?>,
                        backgroundColor: 'rgba(40, 167, 69, 0.1)',
                        borderColor: 'rgba(40, 167, 69, 1)',
                        borderWidth: 2,
                        tension: 0.3,
                        fill: true,
                        yAxisID: 'y1'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            callbacks: {
                                label: function(context) {
                                    let label = context.dataset.label || '';
                                    if (label) {
                                        label += ': ';
                                    }
                                    if (context.dataset.yAxisID === 'y1') {
                                        label += new Intl.NumberFormat('id-ID').format(context.parsed.y);
                                    } else {
                                        label += 'Rp ' + new Intl.NumberFormat('id-ID').format(context.parsed.y);
                                    }
                                    return label;
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return 'Rp ' + new Intl.NumberFormat('id-ID').format(value);
                                }
                            }
                        },
                        y1: {
                            beginAtZero: true,
                            position: 'right',
                            grid: {
                                drawOnChartArea: false
                            },
                            ticks: {
                                callback: function(value) {
                                    return new Intl.NumberFormat('id-ID').format(value);
                                }
                            }
                        }
                    }
                }
            });
            
            // Category Chart
            const categoryCtx = document.getElementById('categoryChart').getContext('2d');
            new Chart(categoryCtx, {
                type: 'doughnut',
                data: {
                    labels: <?= json_encode(array_column($kategori_data, 'group_name')) ?>,
                    datasets: [{
                        data: <?= json_encode(array_column($kategori_data, 'total_penjualan')) ?>,
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.7)',
                            'rgba(54, 162, 235, 0.7)',
                            'rgba(255, 206, 86, 0.7)',
                            'rgba(75, 192, 192, 0.7)',
                            'rgba(153, 102, 255, 0.7)',
                            'rgba(255, 159, 64, 0.7)',
                            'rgba(199, 199, 199, 0.7)',
                            'rgba(83, 102, 255, 0.7)',
                            'rgba(40, 159, 64, 0.7)',
                            'rgba(210, 99, 132, 0.7)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'right',
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    let label = context.label || '';
                                    if (label) {
                                        label += ': ';
                                    }
                                    label += 'Rp ' + new Intl.NumberFormat('id-ID').format(context.parsed);
                                    return label;
                                }
                            }
                        }
                    }
                }
            });
            
            // Daily Chart
            const dailyCtx = document.getElementById('dailyChart').getContext('2d');
            new Chart(dailyCtx, {
                type: 'bar',
                data: {
                    labels: <?= json_encode(array_column($hari_data, 'hari')) ?>,
                    datasets: [{
                        label: 'Total Penjualan (Rp)',
                        data: <?= json_encode(array_column($hari_data, 'total_penjualan')) ?>,
                        backgroundColor: 'rgba(255, 159, 64, 0.7)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return 'Rp ' + new Intl.NumberFormat('id-ID').format(value);
                                }
                            }
                        }
                    }
                }
            });
        });
    </script>
</body>
</html>