<?php 

include 'sesi.php';
require_once 'fungsi/fungsi.php';
$modul = (isset($_GET['s']))?$_GET['s']:"awal";
$nama_app = " | Web Kasir";

// Excel Export (CSV with BOM for UTF-8 Excel compat)
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    global $koneksi;

    $where = [];
    if (isset($_GET['start_date']) && $_GET['start_date'] != '') {
        $start = mysqli_real_escape_string($koneksi, $_GET['start_date']);
        $where[] = "tanggal >= '$start'";
    }
    if (isset($_GET['end_date']) && $_GET['end_date'] != '') {
        $end = mysqli_real_escape_string($koneksi, $_GET['end_date']);
        $where[] = "tanggal <= '$end'";
    }
    $where_clause = count($where) > 0 ? ' WHERE ' . implode(' AND ', $where) : '';

    $q = mysqli_query($koneksi, "SELECT * FROM laporan_penjualan$where_clause ORDER BY id DESC");

    header("Content-Type: text/csv; charset=UTF-8");
    header("Content-Disposition: attachment; filename=Laporan_Penjualan_" . date('Ymd') . ".csv");

    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); // UTF-8 BOM

    fputcsv($output, ['No', 'Kode Barang', 'Nama Barang', 'Kategori', 'Jumlah Beli', 'Total (Rp)', 'Tanggal', 'Jam', 'Kasir'], ';');

    $no = 1;
    $grand_total = 0;
    $grand_qty = 0;
    while ($row = mysqli_fetch_array($q)) {
        fputcsv($output, [
            $no++,
            $row['kdbarang'],
            $row['nm_barang'],
            $row['kategori'],
            $row['jumlah_beli'],
            $row['total'],
            $row['tanggal'],
            $row['jam'],
            $row['kasir']
        ], ';');
        $grand_total += $row['total'];
        $grand_qty += $row['jumlah_beli'];
    }

    fputcsv($output, [], ';');
    fputcsv($output, ['', '', '', '', 'Grand Total', $grand_total, '', '', ''], ';');

    fclose($output);
    exit;
}

switch ($modul) {
	case 'title': default: $judul = "Menu Laporan Penjualan $nama_app"; include 'title.php'; break;
	
}


?>

