<?php
// pages/laporan.php
if (session_status() === PHP_SESSION_NONE) session_start();
include "koneksi.php";

// Cek login
if (!isset($_SESSION['user_id'])) {
    echo "<div class='alert alert-warning'>Silakan <a href='login.php'>login</a> terlebih dahulu.</div>";
    return;
}

// Ambil filter
$tgl_awal  = $_GET['tgl_awal'] ?? '';
$tgl_akhir = $_GET['tgl_akhir'] ?? '';
$limit     = (int)($_GET['limit'] ?? 10);
$page_num  = (int)($_GET['page_num'] ?? 1);
$offset    = ($page_num - 1) * $limit;

// Hitung total data
$count_sql = "SELECT COUNT(*) as total_rows FROM tabel_transaksi t WHERE 1=1 ";
$params = [];
$types = '';
if ($tgl_awal !== '') { $count_sql .= " AND t.tanggal >= ? "; $params[] = $tgl_awal; $types .= 's'; }
if ($tgl_akhir !== '') { $count_sql .= " AND t.tanggal <= ? "; $params[] = $tgl_akhir; $types .= 's'; }

$stmt = $conn->prepare($count_sql);
if (!empty($params)) $stmt->bind_param($types, ...$params);
$stmt->execute();
$res_count = $stmt->get_result()->fetch_assoc();
$total_rows = $res_count['total_rows'];
$total_pages = ceil($total_rows / $limit);

// Query data transaksi
$sql = "SELECT t.id, t.no_transaksi, t.tanggal, c.nama AS customer, SUM(td.qty * td.harga) AS total
        FROM tabel_transaksi t
        LEFT JOIN tabel_pelanggan c ON t.id = c.id
        LEFT JOIN tabel_transaksi_detail td ON t.id = td.transaksi_id
        WHERE 1=1 ";
$params = [];
$types = '';
if ($tgl_awal !== '') { $sql .= " AND t.tanggal >= ? "; $params[] = $tgl_awal; $types .= 's'; }
if ($tgl_akhir !== '') { $sql .= " AND t.tanggal <= ? "; $params[] = $tgl_akhir; $types .= 's'; }

$sql .= " GROUP BY t.id ORDER BY t.tanggal DESC LIMIT ? OFFSET ? ";
$params[] = $limit;
$params[] = $offset;
$types .= 'ii';

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

// Simpan data
$transaksi = [];
$total_semua = 0;
while ($row = $result->fetch_assoc()) {
    $transaksi[] = $row;
    $total_semua += $row['total'];
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Laporan Transaksi</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://kit.fontawesome.com/a2d9d5c3d4.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="container mt-4">
    <div class="card shadow-sm mb-4">
        <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0">Laporan Transaksi</h5>
            <div class="no-print">
                <button class="btn btn-success btn-sm" onclick="exportTableToCSV('laporan_transaksi.csv')">
                    <i class="fas fa-file-csv me-1"></i> Export CSV
                </button>
                <button class="btn btn-secondary btn-sm" onclick="window.print()">
                    <i class="fas fa-print me-1"></i> Print
                </button>
            </div>
        </div>
        <div class="card-body no-print">
            <form method="get" class="row g-3 mb-3">
                <input type="hidden" name="page" value="laporan">
                <div class="col-md-3">
                    <label>Tanggal Awal</label>
                    <input type="date" name="tgl_awal" class="form-control" value="<?= htmlspecialchars($tgl_awal) ?>">
                </div>
                <div class="col-md-3">
                    <label>Tanggal Akhir</label>
                    <input type="date" name="tgl_akhir" class="form-control" value="<?= htmlspecialchars($tgl_akhir) ?>">
                </div>
                <div class="col-md-2">
                    <label>Limit</label>
                    <select name="limit" class="form-select">
                        <option value="10" <?= $limit==10?'selected':'' ?>>10</option>
                        <option value="20" <?= $limit==20?'selected':'' ?>>20</option>
                        <option value="50" <?= $limit==50?'selected':'' ?>>50</option>
                        <option value="100" <?= $limit==100?'selected':'' ?>>100</option>
                    </select>
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary me-2">Filter</button>
                </div>
            </form>
        </div>

        <!-- Div khusus print -->
        <div id="printArea">
            <div class="text-center mb-3">
                <h3>LAPORAN TRANSAKSI</h3>
                <p>Tanggal: <?= $tgl_awal ?> s/d <?= $tgl_akhir ?></p>
            </div>
            <div class="table-responsive">
                <table class="table table-bordered" id="laporanTable">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>No Transaksi</th>
                            <th>Tanggal</th>
                            <th>Customer</th>
                            <th>Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($transaksi)):
                            $no = $offset + 1;
                            foreach ($transaksi as $row): ?>
                                <tr>
                                    <td><?= $no++ ?></td>
                                    <td><?= htmlspecialchars($row['no_transaksi']) ?></td>
                                    <td><?= htmlspecialchars($row['tanggal']) ?></td>
                                    <td><?= htmlspecialchars($row['customer']) ?></td>
                                    <td>Rp <?= number_format($row['total'],0,',','.') ?></td>
                                </tr>
                        <?php endforeach; else: ?>
                            <tr><td colspan="5" class="text-center">Belum ada transaksi</td></tr>
                        <?php endif; ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <th colspan="4" class="text-end">Total Semua</th>
                            <th>Rp <?= number_format($total_semua,0,',','.') ?></th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>

        <div class="no-print">
            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <nav>
                <ul class="pagination justify-content-center mt-3">
                    <?php for($i=1;$i<=$total_pages;$i++): ?>
                        <li class="page-item <?= $i==$page_num?'active':'' ?>">
                            <a class="page-link" href="?page=laporan&tgl_awal=<?= $tgl_awal ?>&tgl_akhir=<?= $tgl_akhir ?>&limit=<?= $limit ?>&page_num=<?= $i ?>"><?= $i ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
function exportTableToCSV(filename) {
    var csv = [];
    var rows = document.querySelectorAll("#laporanTable tr");
    for (var i=0; i<rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll("td, th");
        for (var j=0; j<cols.length; j++)
            row.push(cols[j].innerText.replace(/,/g,""));
        csv.push(row.join(","));
    }
    var csvFile = new Blob([csv.join("\n")], {type:"text/csv"});
    var downloadLink = document.createElement("a");
    downloadLink.download = filename;
    downloadLink.href = window.URL.createObjectURL(csvFile);
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
    downloadLink.click();
}
</script>

<style>
@media print {
    body * { visibility: hidden; }
    #printArea, #printArea * { visibility: visible; }
    #printArea { position: absolute; left: 0; top: 0; width: 100%; }
    table th, table td { border: 1px solid #000; background: none !important; color: #000; padding: 5px; }
    th, td { text-align: left; }
}
</style>
</body>
</html>
