<?php
session_start();
require_once '../config/database.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    jsonResponse(false, 'Unauthorized');
}

requireAdmin();

$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'get_laporan_summary':
        getLaporanSummary();
        break;
    
    case 'get_chart_data':
        getChartData();
        break;
    
    case 'export_excel':
        exportExcel();
        break;
    
    case 'export_pdf':
        exportPDF();
        break;
    
    default:
        jsonResponse(false, 'Invalid action');
}

function getLaporanSummary() {
    try {
        $periode = clean($_GET['periode'] ?? 'harian'); // harian, mingguan, bulanan
        $tanggal = clean($_GET['tanggal'] ?? ''); // untuk harian
        $minggu_dari = clean($_GET['minggu_dari'] ?? ''); // untuk mingguan
        $minggu_sampai = clean($_GET['minggu_sampai'] ?? ''); // untuk mingguan
        $bulan = clean($_GET['bulan'] ?? ''); // untuk bulanan (format: YYYY-MM)
        
        // Tentukan range tanggal berdasarkan periode
        $dari = '';
        $sampai = '';
        
        if ($periode == 'harian') {
            $dari = $tanggal;
            $sampai = $tanggal;
        } elseif ($periode == 'mingguan') {
            $dari = $minggu_dari;
            $sampai = $minggu_sampai;
        } elseif ($periode == 'bulanan') {
            $dari = $bulan . '-01';
            $lastDay = date('t', strtotime($dari));
            $sampai = $bulan . '-' . $lastDay;
        }
        
        if (empty($dari) || empty($sampai)) {
            jsonResponse(false, 'Parameter periode tidak lengkap');
        }
        
        $sql_sum_pengunjung = "SELECT SUM(quantity) AS jumlahPengunjung FROM transaksi_detail WHERE id_layanan=4 AND DATE(created_at) BETWEEN ? AND ?";
        $result_sum_pengunjung = query($sql_sum_pengunjung, [$dari, $sampai], 'ss');
        $sum_pengunjung = $result_sum_pengunjung->fetch_assoc();
        $jumlah_pengunjung = intval($sum_pengunjung['jumlahPengunjung']);

        // 1. Pendapatan Struk (transaksi)
        $sql_struk = "SELECT COUNT(*) as jumlah, COALESCE(SUM(total), 0) as total 
                      FROM transaksi 
                      WHERE DATE(created_at) BETWEEN ? AND ?";
        $result_struk = query($sql_struk, [$dari, $sampai], 'ss');
        $pendapatan_struk = $result_struk->fetch_assoc();
        
        // average transaction
        $sql_average_transaction = "SELECT AVG(total) as rata_rata 
                      FROM transaksi 
                      WHERE DATE(created_at) BETWEEN ? AND ?";
        $result_average_transaction = query($sql_average_transaction, [$dari, $sampai], 'ss');
        $average_transaction = $result_average_transaction->fetch_assoc();

        // 2. Pendapatan Booking DP (dibayar saat booking dibuat)
        $sql_booking_dp = "SELECT COALESCE(SUM(dp), 0) as total 
                          FROM booking 
                          WHERE DATE(created_at) BETWEEN ? AND ? AND dp > 0";
        $result_booking_dp = query($sql_booking_dp, [$dari, $sampai], 'ss');
        $pendapatan_booking_dp = $result_booking_dp->fetch_assoc();
        
        // 3. Pendapatan Booking Lunas (sisa dibayar saat kedatangan)
        $sql_booking_lunas = "SELECT COALESCE(SUM(sisa), 0) as total 
                              FROM booking 
                              WHERE tanggal_kedatangan BETWEEN ? AND ? AND sisa > 0";
        $result_booking_lunas = query($sql_booking_lunas, [$dari, $sampai], 'ss');
        $pendapatan_booking_lunas = $result_booking_lunas->fetch_assoc();
        
        // 4. Hitung jumlah booking UNIK dalam periode (untuk jumlah transaksi)
        // Booking dihitung jika created_at atau tanggal_kedatangan ada di periode
        $sql_booking_count = "SELECT COUNT(DISTINCT id) as jumlah 
                             FROM booking 
                             WHERE (DATE(created_at) BETWEEN ? AND ?) 
                                OR (tanggal_kedatangan BETWEEN ? AND ?)";
        $result_booking_count = query($sql_booking_count, [$dari, $sampai, $dari, $sampai], 'ssss');
        $booking_count = $result_booking_count->fetch_assoc();
        
        // 5. Total Pengeluaran
        $sql_pengeluaran = "SELECT COUNT(*) as jumlah, COALESCE(SUM(nominal), 0) as total 
                           FROM pengeluaran 
                           WHERE DATE(created_at) BETWEEN ? AND ?";
        $result_pengeluaran = query($sql_pengeluaran, [$dari, $sampai], 'ss');
        $pengeluaran_total = $result_pengeluaran->fetch_assoc();
        
        // 6. Breakdown pengeluaran per kategori
        $sql_pengeluaran_kategori = "SELECT kategori, COALESCE(SUM(nominal), 0) as total 
                                     FROM pengeluaran 
                                     WHERE DATE(created_at) BETWEEN ? AND ?
                                     GROUP BY kategori
                                     ORDER BY total DESC";
        $result_kategori = query($sql_pengeluaran_kategori, [$dari, $sampai], 'ss');
        $pengeluaran_per_kategori = [];
        while ($row = $result_kategori->fetch_assoc()) {
            $pengeluaran_per_kategori[] = $row;
        }
        
        // Hitung total pendapatan dan laba/rugi
        $total_pendapatan = floatval($pendapatan_struk['total']) + 
                           floatval($pendapatan_booking_dp['total']) + 
                           floatval($pendapatan_booking_lunas['total']);
        
        $total_pengeluaran_nominal = floatval($pengeluaran_total['total']);
        
        $laba_rugi = $total_pendapatan - $total_pengeluaran_nominal;
        
        // Hitung total transaksi: struk + booking unik (1 booking = 1 transaksi)
        $jumlah_transaksi = intval($pendapatan_struk['jumlah']) + 
                           intval($booking_count['jumlah']);
        
        $summary = [
            'periode' => $periode,
            'dari' => $dari,
            'sampai' => $sampai,
            'rata_rata_transaksi' => floatval($average_transaction['rata_rata']),
            'jumlah_pengunjung' => intval($sum_pengunjung['jumlahPengunjung']),
            'pendapatan' => [
                'struk' => [
                    'jumlah' => intval($pendapatan_struk['jumlah']),
                    'total' => floatval($pendapatan_struk['total'])
                ],
                'booking' => [
                    'jumlah' => intval($booking_count['jumlah']),
                    'total' => floatval($pendapatan_booking_dp['total']) + floatval($pendapatan_booking_lunas['total'])
                ],
                'booking_dp' => [
                    'total' => floatval($pendapatan_booking_dp['total'])
                ],
                'booking_lunas' => [
                    'total' => floatval($pendapatan_booking_lunas['total'])
                ],
                'total' => $total_pendapatan
            ],
            'pengeluaran' => [
                'jumlah' => intval($pengeluaran_total['jumlah']),
                'total' => $total_pengeluaran_nominal,
                'per_kategori' => $pengeluaran_per_kategori
            ],
            'laba_rugi' => $laba_rugi,
            'jumlah_transaksi' => $jumlah_transaksi
        ];
        
        jsonResponse(true, 'Success', $summary);
        
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function getChartData() {
    try {
        $periode = clean($_GET['periode'] ?? 'harian');
        $tanggal = clean($_GET['tanggal'] ?? '');
        $minggu_dari = clean($_GET['minggu_dari'] ?? '');
        $minggu_sampai = clean($_GET['minggu_sampai'] ?? '');
        $bulan = clean($_GET['bulan'] ?? '');
        
        // Tentukan range tanggal
        $dari = '';
        $sampai = '';
        
        if ($periode == 'harian') {
            $dari = $tanggal;
            $sampai = $tanggal;
        } elseif ($periode == 'mingguan') {
            $dari = $minggu_dari;
            $sampai = $minggu_sampai;
        } elseif ($periode == 'bulanan') {
            $dari = $bulan . '-01';
            $lastDay = date('t', strtotime($dari));
            $sampai = $bulan . '-' . $lastDay;
        }
        
        $labels = [];
        $pendapatan_data = [];
        $pengeluaran_data = [];
        
        if ($periode == 'harian') {
            // Untuk harian, hanya 1 data point
            $labels[] = date('d M Y', strtotime($dari));
            
            // Pendapatan
            $sql_pendapatan = "SELECT 
                (SELECT COALESCE(SUM(total), 0) FROM transaksi WHERE DATE(created_at) = ?) +
                (SELECT COALESCE(SUM(dp), 0) FROM booking WHERE DATE(created_at) = ? AND dp > 0) +
                (SELECT COALESCE(SUM(sisa), 0) FROM booking WHERE tanggal_kedatangan = ? AND sisa > 0)
                as total";
            $result = query($sql_pendapatan, [$dari, $dari, $dari], 'sss');
            $row = $result->fetch_assoc();
            $pendapatan_data[] = floatval($row['total']);
            
            // Pengeluaran
            $sql_pengeluaran = "SELECT COALESCE(SUM(nominal), 0) as total FROM pengeluaran WHERE DATE(created_at) = ?";
            $result = query($sql_pengeluaran, [$dari], 's');
            $row = $result->fetch_assoc();
            $pengeluaran_data[] = floatval($row['total']);
            
        } elseif ($periode == 'mingguan') {
            // Untuk mingguan, group by tanggal
            $current = strtotime($dari);
            $end = strtotime($sampai);
            
            while ($current <= $end) {
                $date = date('Y-m-d', $current);
                $labels[] = date('d M', $current);
                
                // Pendapatan
                $sql_pendapatan = "SELECT 
                    (SELECT COALESCE(SUM(total), 0) FROM transaksi WHERE DATE(created_at) = ?) +
                    (SELECT COALESCE(SUM(dp), 0) FROM booking WHERE DATE(created_at) = ? AND dp > 0) +
                    (SELECT COALESCE(SUM(sisa), 0) FROM booking WHERE tanggal_kedatangan = ? AND sisa > 0)
                    as total";
                $result = query($sql_pendapatan, [$date, $date, $date], 'sss');
                $row = $result->fetch_assoc();
                $pendapatan_data[] = floatval($row['total']);
                
                // Pengeluaran
                $sql_pengeluaran = "SELECT COALESCE(SUM(nominal), 0) as total FROM pengeluaran WHERE DATE(created_at) = ?";
                $result = query($sql_pengeluaran, [$date], 's');
                $row = $result->fetch_assoc();
                $pengeluaran_data[] = floatval($row['total']);
                
                $current = strtotime('+1 day', $current);
            }
            
        } elseif ($periode == 'bulanan') {
            // Untuk bulanan, group by tanggal dalam bulan tersebut
            $current = strtotime($dari);
            $end = strtotime($sampai);
            
            while ($current <= $end) {
                $date = date('Y-m-d', $current);
                $labels[] = date('d', $current);
                
                // Pendapatan
                $sql_pendapatan = "SELECT 
                    (SELECT COALESCE(SUM(total), 0) FROM transaksi WHERE DATE(created_at) = ?) +
                    (SELECT COALESCE(SUM(dp), 0) FROM booking WHERE DATE(created_at) = ? AND dp > 0) +
                    (SELECT COALESCE(SUM(sisa), 0) FROM booking WHERE tanggal_kedatangan = ? AND sisa > 0)
                    as total";
                $result = query($sql_pendapatan, [$date, $date, $date], 'sss');
                $row = $result->fetch_assoc();
                $pendapatan_data[] = floatval($row['total']);
                
                // Pengeluaran
                $sql_pengeluaran = "SELECT COALESCE(SUM(nominal), 0) as total FROM pengeluaran WHERE DATE(created_at) = ?";
                $result = query($sql_pengeluaran, [$date], 's');
                $row = $result->fetch_assoc();
                $pengeluaran_data[] = floatval($row['total']);
                
                $current = strtotime('+1 day', $current);
            }
        }
        
        $chartData = [
            'labels' => $labels,
            'datasets' => [
                [
                    'label' => 'Pendapatan',
                    'data' => $pendapatan_data,
                    'backgroundColor' => 'rgba(34, 197, 94, 0.5)',
                    'borderColor' => 'rgba(34, 197, 94, 1)',
                    'borderWidth' => 2
                ],
                [
                    'label' => 'Pengeluaran',
                    'data' => $pengeluaran_data,
                    'backgroundColor' => 'rgba(239, 68, 68, 0.5)',
                    'borderColor' => 'rgba(239, 68, 68, 1)',
                    'borderWidth' => 2
                ]
            ]
        ];
        
        jsonResponse(true, 'Success', $chartData);
        
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function exportExcel() {
    try {
        require_once __DIR__ . '/../vendor/autoload.php';
        
        $periode = clean($_GET['periode'] ?? 'harian');
        $tanggal = clean($_GET['tanggal'] ?? '');
        $minggu_dari = clean($_GET['minggu_dari'] ?? '');
        $minggu_sampai = clean($_GET['minggu_sampai'] ?? '');
        $bulan = clean($_GET['bulan'] ?? '');
        
        // Tentukan range tanggal
        $dari = '';
        $sampai = '';
        $periodeText = '';
        
        if ($periode == 'harian') {
            $dari = $tanggal;
            $sampai = $tanggal;
            $periodeText = 'Harian - ' . date('d/m/Y', strtotime($tanggal));
        } elseif ($periode == 'mingguan') {
            $dari = $minggu_dari;
            $sampai = $minggu_sampai;
            $periodeText = 'Mingguan - ' . date('d/m/Y', strtotime($dari)) . ' s/d ' . date('d/m/Y', strtotime($sampai));
        } elseif ($periode == 'bulanan') {
            $dari = $bulan . '-01';
            $lastDay = date('t', strtotime($dari));
            $sampai = $bulan . '-' . $lastDay;
            $periodeText = 'Bulanan - ' . date('F Y', strtotime($dari));
        }
        
        // Get data summary
        $sql_struk = "SELECT COUNT(*) as jumlah, COALESCE(SUM(total), 0) as total FROM transaksi WHERE DATE(created_at) BETWEEN ? AND ?";
        $result_struk = query($sql_struk, [$dari, $sampai], 'ss');
        $pendapatan_struk = $result_struk->fetch_assoc();
        
        $sql_booking_dp = "SELECT COALESCE(SUM(dp), 0) as total FROM booking WHERE DATE(created_at) BETWEEN ? AND ? AND dp > 0";
        $result_booking_dp = query($sql_booking_dp, [$dari, $sampai], 'ss');
        $pendapatan_booking_dp = $result_booking_dp->fetch_assoc();
        
        $sql_booking_lunas = "SELECT COALESCE(SUM(sisa), 0) as total FROM booking WHERE tanggal_kedatangan BETWEEN ? AND ? AND sisa > 0";
        $result_booking_lunas = query($sql_booking_lunas, [$dari, $sampai], 'ss');
        $pendapatan_booking_lunas = $result_booking_lunas->fetch_assoc();
        
        $sql_booking_count = "SELECT COUNT(DISTINCT id) as jumlah FROM booking WHERE (DATE(created_at) BETWEEN ? AND ?) OR (tanggal_kedatangan BETWEEN ? AND ?)";
        $result_booking_count = query($sql_booking_count, [$dari, $sampai, $dari, $sampai], 'ssss');
        $booking_count = $result_booking_count->fetch_assoc();
        
        $sql_pengeluaran = "SELECT COUNT(*) as jumlah, COALESCE(SUM(nominal), 0) as total FROM pengeluaran WHERE DATE(created_at) BETWEEN ? AND ?";
        $result_pengeluaran = query($sql_pengeluaran, [$dari, $sampai], 'ss');
        $pengeluaran_total = $result_pengeluaran->fetch_assoc();
        
        $total_pendapatan = floatval($pendapatan_struk['total']) + floatval($pendapatan_booking_dp['total']) + floatval($pendapatan_booking_lunas['total']);
        $total_booking = floatval($pendapatan_booking_dp['total']) + floatval($pendapatan_booking_lunas['total']);
        $total_pengeluaran_nominal = floatval($pengeluaran_total['total']);
        $laba_rugi = $total_pendapatan - $total_pengeluaran_nominal;
        
        // Create Excel
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        
        // Header
        $sheet->setCellValue('A1', 'LAPORAN KEUANGAN');
        $sheet->setCellValue('A2', 'UMBUL Sungsang');
        $sheet->setCellValue('A3', 'Aryaguna Nusantara');
        $sheet->setCellValue('A4', 'Periode: ' . $periodeText);
        
        // Styling header
        $sheet->mergeCells('A1:D1');
        $sheet->mergeCells('A2:D2');
        $sheet->mergeCells('A3:D3');
        $sheet->mergeCells('A4:D4');
        $sheet->getStyle('A1:A4')->getFont()->setBold(true);
        $sheet->getStyle('A1')->getFont()->setSize(16);
        
        // Summary
        $row = 6;
        $sheet->setCellValue('A' . $row, 'RINGKASAN');
        $sheet->getStyle('A' . $row)->getFont()->setBold(true);
        
        $row++;
        $sheet->setCellValue('A' . $row, 'Total Pendapatan');
        $sheet->setCellValue('B' . $row, $total_pendapatan);
        $sheet->getStyle('B' . $row)->getNumberFormat()->setFormatCode('#,##0');
        
        $row++;
        $sheet->setCellValue('A' . $row, 'Total Pengeluaran');
        $sheet->setCellValue('B' . $row, $total_pengeluaran_nominal);
        $sheet->getStyle('B' . $row)->getNumberFormat()->setFormatCode('#,##0');
        
        $row++;
        $sheet->setCellValue('A' . $row, 'Laba/Rugi');
        $sheet->setCellValue('B' . $row, $laba_rugi);
        $sheet->getStyle('B' . $row)->getNumberFormat()->setFormatCode('#,##0');
        $sheet->getStyle('A' . $row . ':B' . $row)->getFont()->setBold(true);
        
        // Detail Pendapatan
        $row += 2;
        $sheet->setCellValue('A' . $row, 'DETAIL PENDAPATAN');
        $sheet->getStyle('A' . $row)->getFont()->setBold(true);
        
        $row++;
        $sheet->setCellValue('A' . $row, 'Sumber');
        $sheet->setCellValue('B' . $row, 'Jumlah');
        $sheet->setCellValue('C' . $row, 'Total');
        $sheet->getStyle('A' . $row . ':C' . $row)->getFont()->setBold(true);
        
        $row++;
        $sheet->setCellValue('A' . $row, 'Struk');
        $sheet->setCellValue('B' . $row, $pendapatan_struk['jumlah']);
        $sheet->setCellValue('C' . $row, $pendapatan_struk['total']);
        $sheet->getStyle('C' . $row)->getNumberFormat()->setFormatCode('#,##0');
        
        $row++;
        $sheet->setCellValue('A' . $row, 'Booking');
        $sheet->setCellValue('B' . $row, $booking_count['jumlah']);
        $sheet->setCellValue('C' . $row, $total_booking);
        $sheet->getStyle('C' . $row)->getNumberFormat()->setFormatCode('#,##0');
        
        $row++;
        $sheet->setCellValue('A' . $row, '  • DP (saat booking)');
        $sheet->setCellValue('B' . $row, '');
        $sheet->setCellValue('C' . $row, $pendapatan_booking_dp['total']);
        $sheet->getStyle('C' . $row)->getNumberFormat()->setFormatCode('#,##0');
        
        $row++;
        $sheet->setCellValue('A' . $row, '  • Lunas (saat kedatangan)');
        $sheet->setCellValue('B' . $row, '');
        $sheet->setCellValue('C' . $row, $pendapatan_booking_lunas['total']);
        $sheet->getStyle('C' . $row)->getNumberFormat()->setFormatCode('#,##0');
        
        // Auto size columns
        foreach(range('A','C') as $col) {
            $sheet->getColumnDimension($col)->setAutoSize(true);
        }
        
        // Output
        $filename = 'Laporan_' . $periode . '_' . date('YmdHis') . '.xlsx';
        
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
        
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function exportPDF() {
    try {
        require_once __DIR__ . '/../vendor/autoload.php';
        
        $periode = clean($_GET['periode'] ?? 'harian');
        $tanggal = clean($_GET['tanggal'] ?? '');
        $minggu_dari = clean($_GET['minggu_dari'] ?? '');
        $minggu_sampai = clean($_GET['minggu_sampai'] ?? '');
        $bulan = clean($_GET['bulan'] ?? '');
        
        // Tentukan range tanggal
        $dari = '';
        $sampai = '';
        $periodeText = '';
        
        if ($periode == 'harian') {
            $dari = $tanggal;
            $sampai = $tanggal;
            $periodeText = 'Harian - ' . date('d/m/Y', strtotime($tanggal));
        } elseif ($periode == 'mingguan') {
            $dari = $minggu_dari;
            $sampai = $minggu_sampai;
            $periodeText = 'Mingguan - ' . date('d/m/Y', strtotime($dari)) . ' s/d ' . date('d/m/Y', strtotime($sampai));
        } elseif ($periode == 'bulanan') {
            $dari = $bulan . '-01';
            $lastDay = date('t', strtotime($dari));
            $sampai = $bulan . '-' . $lastDay;
            $periodeText = 'Bulanan - ' . date('F Y', strtotime($dari));
        }
        
        // Get data
        $sql_struk = "SELECT COUNT(*) as jumlah, COALESCE(SUM(total), 0) as total FROM transaksi WHERE DATE(created_at) BETWEEN ? AND ?";
        $result_struk = query($sql_struk, [$dari, $sampai], 'ss');
        $pendapatan_struk = $result_struk->fetch_assoc();
        
        $sql_booking_dp = "SELECT COALESCE(SUM(dp), 0) as total FROM booking WHERE DATE(created_at) BETWEEN ? AND ? AND dp > 0";
        $result_booking_dp = query($sql_booking_dp, [$dari, $sampai], 'ss');
        $pendapatan_booking_dp = $result_booking_dp->fetch_assoc();
        
        $sql_booking_lunas = "SELECT COALESCE(SUM(sisa), 0) as total FROM booking WHERE tanggal_kedatangan BETWEEN ? AND ? AND sisa > 0";
        $result_booking_lunas = query($sql_booking_lunas, [$dari, $sampai], 'ss');
        $pendapatan_booking_lunas = $result_booking_lunas->fetch_assoc();
        
        $sql_booking_count = "SELECT COUNT(DISTINCT id) as jumlah FROM booking WHERE (DATE(created_at) BETWEEN ? AND ?) OR (tanggal_kedatangan BETWEEN ? AND ?)";
        $result_booking_count = query($sql_booking_count, [$dari, $sampai, $dari, $sampai], 'ssss');
        $booking_count = $result_booking_count->fetch_assoc();
        
        $sql_pengeluaran = "SELECT COUNT(*) as jumlah, COALESCE(SUM(nominal), 0) as total FROM pengeluaran WHERE DATE(created_at) BETWEEN ? AND ?";
        $result_pengeluaran = query($sql_pengeluaran, [$dari, $sampai], 'ss');
        $pengeluaran_total = $result_pengeluaran->fetch_assoc();
        
        $sql_pengeluaran_kategori = "SELECT kategori, COALESCE(SUM(nominal), 0) as total FROM pengeluaran WHERE DATE(created_at) BETWEEN ? AND ? GROUP BY kategori ORDER BY total DESC";
        $result_kategori = query($sql_pengeluaran_kategori, [$dari, $sampai], 'ss');
        $pengeluaran_per_kategori = [];
        while ($row = $result_kategori->fetch_assoc()) {
            $pengeluaran_per_kategori[] = $row;
        }
        
        $total_pendapatan = floatval($pendapatan_struk['total']) + floatval($pendapatan_booking_dp['total']) + floatval($pendapatan_booking_lunas['total']);
        $total_booking = floatval($pendapatan_booking_dp['total']) + floatval($pendapatan_booking_lunas['total']);
        $total_pengeluaran_nominal = floatval($pengeluaran_total['total']);
        $laba_rugi = $total_pendapatan - $total_pengeluaran_nominal;
        
        // Create PDF
        $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
        
        // Set document information
        $pdf->SetCreator('Umbul Sungsang V2');
        $pdf->SetAuthor('Aryaguna Nusantara');
        $pdf->SetTitle('Laporan Keuangan ' . $periodeText);
        
        // Remove default header/footer
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        
        // Add page
        $pdf->AddPage();
        
        // Set font
        $pdf->SetFont('helvetica', '', 10);
        
        // Header
        $pdf->SetFont('helvetica', 'B', 16);
        $pdf->Cell(0, 10, 'LAPORAN KEUANGAN', 0, 1, 'C');
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 8, 'UMBUL Sungsang', 0, 1, 'C');
        $pdf->SetFont('helvetica', '', 10);
        $pdf->Cell(0, 6, 'Aryaguna Nusantara', 0, 1, 'C');
        $pdf->Cell(0, 6, 'Pengging, Boyolali, Jawa Tengah', 0, 1, 'C');
        $pdf->Ln(5);
        
        $pdf->SetFont('helvetica', 'B', 11);
        $pdf->Cell(0, 6, 'Periode: ' . $periodeText, 0, 1, 'C');
        $pdf->Ln(5);
        
        // Summary
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 8, 'RINGKASAN', 0, 1, 'L');
        $pdf->SetFont('helvetica', '', 10);
        
        $html = '<table border="1" cellpadding="5">
            <tr style="background-color: #f3f4f6;">
                <th width="50%">Keterangan</th>
                <th width="50%" align="right">Jumlah (Rp)</th>
            </tr>
            <tr>
                <td>Total Pendapatan</td>
                <td align="right">' . number_format($total_pendapatan, 0, ',', '.') . '</td>
            </tr>
            <tr>
                <td>Total Pengeluaran</td>
                <td align="right">' . number_format($total_pengeluaran_nominal, 0, ',', '.') . '</td>
            </tr>
            <tr style="background-color: #f9fafb; font-weight: bold;">
                <td>Laba/Rugi</td>
                <td align="right" style="color: ' . ($laba_rugi >= 0 ? 'green' : 'red') . ';">' . number_format($laba_rugi, 0, ',', '.') . '</td>
            </tr>
        </table>';
        
        $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->Ln(5);
        
        // Detail Pendapatan
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 8, 'DETAIL PENDAPATAN', 0, 1, 'L');
        $pdf->SetFont('helvetica', '', 10);
        
        $html = '<table border="1" cellpadding="5">
            <tr style="background-color: #f3f4f6;">
                <th width="50%">Sumber</th>
                <th width="20%" align="center">Jumlah</th>
                <th width="30%" align="right">Total (Rp)</th>
            </tr>
            <tr>
                <td>Pendapatan Struk</td>
                <td align="center">' . $pendapatan_struk['jumlah'] . '</td>
                <td align="right">' . number_format($pendapatan_struk['total'], 0, ',', '.') . '</td>
            </tr>
            <tr>
                <td>Pendapatan Booking</td>
                <td align="center">' . $booking_count['jumlah'] . '</td>
                <td align="right">' . number_format($total_booking, 0, ',', '.') . '</td>
            </tr>
            <tr>
                <td>&nbsp;&nbsp;• DP (saat booking)</td>
                <td align="center">-</td>
                <td align="right">' . number_format($pendapatan_booking_dp['total'], 0, ',', '.') . '</td>
            </tr>
            <tr>
                <td>&nbsp;&nbsp;• Lunas (saat kedatangan)</td>
                <td align="center">-</td>
                <td align="right">' . number_format($pendapatan_booking_lunas['total'], 0, ',', '.') . '</td>
            </tr>
            <tr style="background-color: #f9fafb; font-weight: bold;">
                <td colspan="2">TOTAL PENDAPATAN</td>
                <td align="right">' . number_format($total_pendapatan, 0, ',', '.') . '</td>
            </tr>
        </table>';
        
        $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->Ln(5);
        
        // Detail Pengeluaran
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 8, 'DETAIL PENGELUARAN', 0, 1, 'L');
        $pdf->SetFont('helvetica', '', 10);
        
        $pengeluaran_html = '<table border="1" cellpadding="5">
            <tr style="background-color: #f3f4f6;">
                <th width="70%">Kategori</th>
                <th width="30%" align="right">Total (Rp)</th>
            </tr>';
        
        foreach ($pengeluaran_per_kategori as $item) {
            $pengeluaran_html .= '<tr>
                <td>' . htmlspecialchars($item['kategori']) . '</td>
                <td align="right">' . number_format($item['total'], 0, ',', '.') . '</td>
            </tr>';
        }
        
        $pengeluaran_html .= '<tr style="background-color: #f9fafb; font-weight: bold;">
                <td>TOTAL PENGELUARAN</td>
                <td align="right">' . number_format($total_pengeluaran_nominal, 0, ',', '.') . '</td>
            </tr>
        </table>';
        
        $pdf->writeHTML($pengeluaran_html, true, false, true, false, '');
        
        // Footer
        $pdf->Ln(10);
        $pdf->SetFont('helvetica', 'I', 8);
        $pdf->Cell(0, 6, 'Dicetak pada: ' . date('d/m/Y H:i:s'), 0, 1, 'C');
        
        // Output
        $filename = 'Laporan_' . $periode . '_' . date('YmdHis') . '.pdf';
        $pdf->Output($filename, 'D');
        exit;
        
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}
?>
