<?php
require_once __DIR__ . '/../includes/db.php';

// Cek apakah admin sudah login (wajib sebelum mengekspor atau melihat)
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit();
}

// Set tanggal default (awal bulan ini s/d hari ini)
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');

// --- FITUR EKSPOR CSV ---
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    // Bersihkan buffer output agar tidak mengotori file CSV
    if (ob_get_level()) {
        ob_end_clean();
    }
    
    // Ambil data pesanan completed berdasarkan filter tanggal
    $stmt = $db->prepare("
        SELECT id, customer_name, customer_phone, total_price, created_at, status 
        FROM orders 
        WHERE status = 'completed' 
          AND DATE(created_at) >= ? 
          AND DATE(created_at) <= ? 
        ORDER BY id ASC
    ");
    $stmt->execute([$start_date, $end_date]);
    $orders_csv = $stmt->fetchAll();
    
    // Set headers untuk download file CSV
    $filename = "Laporan_Penjualan_Edelys_" . $start_date . "_to_" . $end_date . ".csv";
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    // Buka standard output stream
    $output = fopen('php://output', 'w');
    
    // Tulis BOM UTF-8 agar file bisa dibaca dengan Excel tanpa masalah karakter khusus/symbol
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
    
    // Tulis baris header
    fputcsv($output, ['No. Invoice', 'Tanggal Transaksi', 'Nama Pelanggan', 'Nomor HP', 'Total Pembayaran (Rp)', 'Status']);
    
    foreach ($orders_csv as $ord) {
        $inv_num = "INV-" . str_pad($ord['id'], 6, '0', STR_PAD_LEFT);
        $date_formatted = date('d/m/Y H:i', strtotime($ord['created_at']));
        fputcsv($output, [
            $inv_num,
            $date_formatted,
            $ord['customer_name'],
            "'" . $ord['customer_phone'], // Menambahkan kutipan ' di Excel agar no telp tidak dianggap scientific number
            $ord['total_price'],
            'Selesai (Completed)'
        ]);
    }
    
    fclose($output);
    exit();
}

// --- TAMPILAN VIEW NORMAL ---
$page_title = "Laporan Penjualan";
$header_title = "Penarikan Laporan Penjualan";
require_once __DIR__ . '/../includes/admin_header.php';

// Ambil list transaksi selesai (completed) berdasarkan tanggal
$stmt = $db->prepare("
    SELECT * FROM orders 
    WHERE status = 'completed' 
      AND DATE(created_at) >= ? 
      AND DATE(created_at) <= ? 
    ORDER BY id DESC
");
$stmt->execute([$start_date, $end_date]);
$orders = $stmt->fetchAll();

// Hitung Ringkasan Statistik
$total_revenue = 0;
$total_transactions = count($orders);

foreach ($orders as $ord) {
    $total_revenue += $ord['total_price'];
}

// Ambil produk terlaris di periode tersebut
$top_stmt = $db->prepare("
    SELECT p.name, SUM(oi.quantity) as total_qty 
    FROM order_items oi
    JOIN orders o ON oi.order_id = o.id
    JOIN products p ON oi.product_id = p.id
    WHERE o.status = 'completed' 
      AND DATE(o.created_at) >= ? 
      AND DATE(o.created_at) <= ?
    GROUP BY oi.product_id
    ORDER BY total_qty DESC
    LIMIT 1
");
$top_stmt->execute([$start_date, $end_date]);
$top_product = $top_stmt->fetch();
?>

<!-- Filter Card -->
<div class="panel">
    <div class="panel-header" style="border-bottom: 1px solid var(--border-color); padding-bottom: 1rem; margin-bottom: 1.5rem;">
        <h2 class="panel-title"><i class="fa-solid fa-filter"></i> Filter Periode Laporan</h2>
    </div>
    
    <form action="reports.php" method="GET" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)) auto; gap: 1.5rem; align-items: end;">
        <div class="form-group" style="margin-bottom: 0;">
            <label for="start_date">Tanggal Mulai</label>
            <input type="date" name="start_date" id="start_date" class="form-control" value="<?php echo htmlspecialchars($start_date); ?>" required>
        </div>
        
        <div class="form-group" style="margin-bottom: 0;">
            <label for="end_date">Tanggal Akhir</label>
            <input type="date" name="end_date" id="end_date" class="form-control" value="<?php echo htmlspecialchars($end_date); ?>" required>
        </div>
        
        <div style="display: flex; gap: 0.5rem; height: 42px;">
            <button type="submit" class="btn-admin btn-admin-primary" style="height: 100%;">
                <i class="fa-solid fa-sync"></i> Tampilkan
            </button>
            <a href="reports.php?export=csv&start_date=<?php echo urlencode($start_date); ?>&end_date=<?php echo urlencode($end_date); ?>" class="btn-admin btn-admin-success" style="height: 100%; text-decoration: none;">
                <i class="fa-solid fa-file-excel"></i> Ekspor CSV / Excel
            </a>
        </div>
    </form>
</div>

<!-- Laporan Metrik Ringkasan -->
<div class="metrics-grid">
    <div class="metric-card">
        <div class="metric-info">
            <h3>Total Omzet</h3>
            <div class="value">Rp <?php echo number_format($total_revenue, 0, ',', '.'); ?></div>
        </div>
        <div class="metric-icon green">
            <i class="fa-solid fa-wallet"></i>
        </div>
    </div>
    
    <div class="metric-card">
        <div class="metric-info">
            <h3>Total Transaksi</h3>
            <div class="value"><?php echo $total_transactions; ?> kali</div>
        </div>
        <div class="metric-icon blue">
            <i class="fa-solid fa-cart-shopping"></i>
        </div>
    </div>

    <div class="metric-card" style="grid-column: span 2;">
        <div class="metric-info">
            <h3>Kue Paling Laris</h3>
            <div class="value" style="font-size: 1.3rem; margin-top: 0.3rem;">
                <?php if ($top_product): ?>
                    <?php echo htmlspecialchars($top_product['name']); ?> 
                    <span style="font-size: 0.95rem; color: var(--text-muted); font-weight: normal;">
                        (Terjual <?php echo $top_product['total_qty']; ?> pcs)
                    </span>
                <?php else: ?>
                    <span style="color: var(--text-muted); font-weight: normal;">Belum ada penjualan</span>
                <?php endif; ?>
            </div>
        </div>
        <div class="metric-icon gold">
            <i class="fa-solid fa-crown"></i>
        </div>
    </div>
</div>

<!-- Daftar Rincian Transaksi Selesai -->
<div class="panel">
    <div class="panel-header">
        <h2 class="panel-title"><i class="fa-solid fa-receipt"></i> Rincian Transaksi Selesai</h2>
    </div>
    <div class="table-responsive">
        <table class="admin-table">
            <thead>
                <tr>
                    <th>Invoice</th>
                    <th>Tanggal</th>
                    <th>Nama Pelanggan</th>
                    <th>No. Telepon</th>
                    <th>Total Belanja</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php if (count($orders) > 0): ?>
                    <?php foreach ($orders as $ord): ?>
                        <tr>
                            <td style="font-family: monospace; font-weight: bold;">
                                INV-<?php echo str_pad($ord['id'], 6, '0', STR_PAD_LEFT); ?>
                            </td>
                            <td><?php echo date('d/m/Y H:i', strtotime($ord['created_at'])); ?></td>
                            <td><strong><?php echo htmlspecialchars($ord['customer_name']); ?></strong></td>
                            <td><?php echo htmlspecialchars($ord['customer_phone']); ?></td>
                            <td style="font-weight: 600; color: var(--text-dark);">
                                Rp <?php echo number_format($ord['total_price'], 0, ',', '.'); ?>
                            </td>
                            <td>
                                <span class="badge badge-completed">Selesai</span>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="6" style="text-align: center; color: var(--text-muted); padding: 3rem;">
                            Tidak ada data transaksi selesai pada rentang tanggal yang dipilih.
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/admin_footer.php'; ?>
