<?php
/**
 * Tabungan Siswa Reports Module
 * Koperasi Management System
 */

require_once __DIR__ . '/../config/database.php';
$db = getDB();

$type = $_GET['type'] ?? 'harian';
$date = $_GET['date'] ?? date('Y-m-d');
$month = $_GET['month'] ?? date('n');
$year = $_GET['year'] ?? date('Y');

$pageTitle = 'Laporan Tabungan Siswa';
if ($type === 'harian') {
    $pageSubtitle = 'Laporan harian per tanggal ' . formatTanggal($date);
} elseif ($type === 'tahunan') {
    $pageSubtitle = 'Rekap tahunan ' . $year;
} else {
    $pageSubtitle = 'Laporan bulanan per ' . formatBulan($month) . ' ' . $year;
}

// Helper to format month name
if (!function_exists('formatBulan')) {
    function formatBulan($m) {
        $bulan = [
            1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
            5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
            9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
        ];
        return $bulan[(int)$m] ?? '';
    }
}

// Prepare Query based on type
if ($type === 'harian') {
    $stmt = $db->prepare("
        SELECT ts.*, s.nama as nama_siswa, s.kelas, u.username as admin_name 
        FROM tabungan_siswa ts 
        JOIN siswa s ON ts.siswa_id = s.id 
        LEFT JOIN users u ON ts.created_by = u.id 
        WHERE ts.tanggal = ? 
        ORDER BY ts.created_at ASC
    ");
    $stmt->execute([$date]);
} elseif ($type === 'tahunan') {
    $stmt = $db->prepare("
        SELECT ts.*, s.nama as nama_siswa, s.kelas, u.username as admin_name 
        FROM tabungan_siswa ts 
        JOIN siswa s ON ts.siswa_id = s.id 
        LEFT JOIN users u ON ts.created_by = u.id 
        WHERE YEAR(ts.tanggal) = ? 
        ORDER BY ts.tanggal ASC, ts.created_at ASC
    ");
    $stmt->execute([$year]);
} else {
    $stmt = $db->prepare("
        SELECT ts.*, s.nama as nama_siswa, s.kelas, u.username as admin_name 
        FROM tabungan_siswa ts 
        JOIN siswa s ON ts.siswa_id = s.id 
        LEFT JOIN users u ON ts.created_by = u.id 
        WHERE MONTH(ts.tanggal) = ? AND YEAR(ts.tanggal) = ? 
        ORDER BY ts.tanggal ASC, ts.created_at ASC
    ");
    $stmt->execute([$month, $year]);
}

$laporanData = $stmt->fetchAll();

// Calculate Starting Balance (Saldo Awal) before this period
if ($type === 'harian') {
    $stmtSaldo = $db->prepare("SELECT SUM(CASE WHEN tipe='setoran' THEN jumlah ELSE -jumlah END) FROM tabungan_siswa WHERE tanggal < ?");
    $stmtSaldo->execute([$date]);
} elseif ($type === 'tahunan') {
    $stmtSaldo = $db->prepare("SELECT SUM(CASE WHEN tipe='setoran' THEN jumlah ELSE -jumlah END) FROM tabungan_siswa WHERE YEAR(tanggal) < ?");
    $stmtSaldo->execute([$year]);
} else {
    $stmtSaldo = $db->prepare("SELECT SUM(CASE WHEN tipe='setoran' THEN jumlah ELSE -jumlah END) FROM tabungan_siswa WHERE tanggal < ?");
    $stmtSaldo->execute(["$year-$month-01"]);
}
$saldoAwal = (float)($stmtSaldo->fetchColumn() ?: 0);

// Calculate Totals and Running Balance
$totalSetoran = 0;
$totalPenarikan = 0;
$runningBalance = $saldoAwal;
foreach ($laporanData as &$row) {
    if ($row['tipe'] === 'setoran') {
        $totalSetoran += $row['jumlah'];
        $runningBalance += $row['jumlah'];
    } else {
        $totalPenarikan += $row['jumlah'];
        $runningBalance -= $row['jumlah'];
    }
    $row['saldo_akhir'] = $runningBalance;
}
unset($row);
$saldoBersih = $totalSetoran - $totalPenarikan;

include __DIR__ . '/../includes/header.php';
?>

<style>
/* Dashboard Premium Styles */
.report-card {
    border-radius: 20px;
    border: none;
    box-shadow: 0 4px 20px rgba(0,0,0,0.05);
    background: white;
}

.report-filter-bar {
    background: white;
    padding: 24px;
    border-radius: 20px;
}

.pro-badge {
    padding: 6px 12px;
    border-radius: 8px;
    font-size: 0.7rem;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.badge-deposit { background: #ecfdf5; color: #059669; }
.badge-withdraw { background: #fff1f2; color: #e11d48; }

/* Summary Grid */
.summary-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    margin-bottom: 30px;
}

.summary-card-pro {
    padding: 24px;
    border-radius: 24px;
    border: 1px solid transparent;
    transition: transform 0.2s;
}

.summary-card-pro:hover { transform: translateY(-5px); }

.summary-card-pro.deposit { background: #f0fdf4; border-color: #dcfce7; }
.summary-card-pro.withdraw { background: #fff1f2; border-color: #ffe4e6; }
.summary-card-pro.balance { background: #eff6ff; border-color: #dbeafe; }

.summary-label {
    font-size: 0.75rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.1em;
    margin-bottom: 8px;
    display: block;
}

.summary-value {
    font-size: 1.75rem;
    font-weight: 900;
    font-family: 'Inter', sans-serif;
    line-height: 1;
}

.deposit .summary-label { color: #166534; }
.deposit .summary-value { color: #15803d; }
.withdraw .summary-label { color: #991b1b; }
.withdraw .summary-value { color: #b91c1c; }
.balance .summary-label { color: #1e40af; }
.balance .summary-value { color: #1d4ed8; }

/* Modern Table */
.table-pro {
    width: 100%;
    border-collapse: collapse;
}

.table-pro thead th {
    background: #f8fafc;
    color: #64748b;
    font-size: 0.7rem;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 0.1em;
    padding: 16px 20px;
    border-bottom: 2px solid #f1f5f9;
}

.table-pro tbody td {
    padding: 18px 20px;
    border-bottom: 1px solid #f1f5f9;
    vertical-align: middle;
    color: #334155;
    font-size: 0.9rem;
}

.table-pro tr:last-child td { border-bottom: none; }
.table-pro tr:hover td { background: #fbfcfe; }

.siswa-info { font-weight: 700; color: #1e293b; }
.kelas-info { color: #94a3b8; font-size: 0.8rem; }

.input-pro-group {
    position: relative;
    display: flex;
    align-items: center;
}

.input-pro-group i {
    position: absolute;
    left: 14px;
    color: #94a3b8;
}

.input-pro {
    padding-left: 40px !important;
    border-radius: 12px !important;
    border: 1.5px solid #e2e8f0 !important;
    height: 45px !important;
}

.empty-state-container {
    padding: 80px 0;
    text-align: center;
}

.empty-state-icon {
    font-size: 4rem;
    color: #e2e8f0;
    margin-bottom: 20px;
}
<style>
/* ... existing styles ... */

@media print {
    .no-print, .report-filter-bar, .main-sidebar, .topbar { display: none !important; }
    .content-wrapper { margin: 0 !important; padding: 0 !important; }
    .report-card, .summary-grid { box-shadow: none !important; border: 1px solid #eee !important; }
    .summary-card-pro { transform: none !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    body { background: white !important; }
}

.btn-export {
    height: 45px;
    padding: 0 15px;
    border-radius: 12px;
    font-weight: 700;
    font-size: 0.85rem;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s;
}

.btn-excel { background: #107c41; color: white; border: none; }
.btn-excel:hover { background: #0e6a37; transform: translateY(-2px); color: white; }

.btn-pdf { background: #e11d48; color: white; border: none; }
.btn-pdf:hover { background: #be123c; transform: translateY(-2px); color: white; }
</style>

<div class="row no-print">
    <div class="col-md-12">
        <div class="report-filter-bar mb-4">
            <form method="GET" class="row align-items-end g-3" id="filterForm">
                <div class="col-md-3">
                    <label class="summary-label" style="color: #64748b; margin-bottom: 8px;">Tipe Laporan</label>
                    <div class="input-pro-group">
                        <i class="fas fa-layer-group"></i>
                        <select name="type" class="form-control input-pro" onchange="this.form.submit()">
                            <option value="harian" <?= $type === 'harian' ? 'selected' : '' ?>>Laporan Harian</option>
                            <option value="bulanan" <?= $type === 'bulanan' ? 'selected' : '' ?>>Rekap Bulanan</option>
                            <option value="tahunan" <?= $type === 'tahunan' ? 'selected' : '' ?>>Rekap Tahunan</option>
                        </select>
                    </div>
                </div>

                <?php if ($type === 'harian'): ?>
                <div class="col-md-3">
                    <label class="summary-label" style="color: #64748b; margin-bottom: 8px;">Pilih Tanggal</label>
                    <div class="input-pro-group">
                        <i class="fas fa-calendar-day"></i>
                        <input type="date" name="date" class="form-control input-pro" value="<?= $date ?>">
                    </div>
                </div>
                <?php elseif ($type === 'bulanan'): ?>
                <div class="col-md-2">
                    <label class="summary-label" style="color: #64748b; margin-bottom: 8px;">Bulan</label>
                    <div class="input-pro-group">
                        <i class="fas fa-calendar-alt"></i>
                        <select name="month" class="form-control input-pro">
                            <?php for($m=1; $m<=12; $m++): ?>
                                <option value="<?= $m ?>" <?= $month == $m ? 'selected' : '' ?>><?= formatBulan($m) ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-2">
                    <label class="summary-label" style="color: #64748b; margin-bottom: 8px;">Tahun</label>
                    <div class="input-pro-group">
                        <i class="fas fa-clock"></i>
                        <select name="year" class="form-control input-pro">
                            <?php 
                            $currYear = date('Y');
                            for($y=$currYear-2; $y<=$currYear+1; $y++): 
                            ?>
                                <option value="<?= $y ?>" <?= $year == $y ? 'selected' : '' ?>><?= $y ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                </div>
                <?php elseif ($type === 'tahunan'): ?>
                <div class="col-md-2">
                    <label class="summary-label" style="color: #64748b; margin-bottom: 8px;">Pilih Tahun</label>
                    <div class="input-pro-group">
                        <i class="fas fa-clock"></i>
                        <select name="year" class="form-control input-pro" onchange="this.form.submit()">
                            <?php 
                            $currYear = date('Y');
                            for($y=$currYear-2; $y<=$currYear+1; $y++): 
                            ?>
                                <option value="<?= $y ?>" <?= $year == $y ? 'selected' : '' ?>><?= $y ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                </div>
                <?php endif; ?>

                <div class="col-md-auto ml-auto d-flex" style="gap: 10px;">
                    <button type="submit" class="btn btn-primary" style="height: 45px; padding: 0 20px; border-radius: 12px; font-weight: 800;">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                    
                    <div class="d-flex" style="background: var(--gray-50); padding: 5px; border-radius: 14px; gap: 5px; border: 1px solid var(--gray-200);">
                        <a href="export_excel.php?<?= http_build_query($_GET) ?>" class="btn-export btn-excel">
                            <i class="fas fa-file-excel"></i> Excel
                        </a>
                        <a href="print.php?<?= http_build_query($_GET) ?>" target="_blank" class="btn-export btn-pdf">
                            <i class="fas fa-file-pdf"></i> PDF
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="summary-grid">
    <div class="summary-card-pro deposit">
        <span class="summary-label">Total Setoran</span>
        <div class="summary-value"><?= formatRupiah($totalSetoran) ?></div>
    </div>
    <div class="summary-card-pro withdraw">
        <span class="summary-label">Total Penarikan</span>
        <div class="summary-value"><?= formatRupiah($totalPenarikan) ?></div>
    </div>
    <div class="summary-card-pro balance">
        <span class="summary-label">Saldo Bersih</span>
        <div class="summary-value"><?= formatRupiah($saldoBersih) ?></div>
    </div>
</div>

<div class="report-card">
    <div class="card-header d-flex justify-content-between align-items-center" style="background: transparent; padding: 25px 30px; border-bottom: 1px solid #f1f5f9;">
        <h3 style="font-weight: 900; font-size: 1.1rem; color: #1e293b; margin: 0;">
            <i class="fas fa-receipt mr-2 text-primary"></i> Rincian Transaksi
        </h3>
        <span class="text-muted small fw-bold uppercase letter-spacing-1"><?= count($laporanData) ?> Transaksi Terdeteksi</span>
    </div>
    <div class="table-responsive">
        <table class="table-pro">
            <thead>
                <tr>
                    <th class="text-center" width="60">NO</th>
                    <th width="120">TANGGAL</th>
                    <th>SISWA & KELAS</th>
                    <th class="text-center" width="120">TIPE</th>
                    <th class="text-right" width="160">JUMLAH</th>
                    <th class="text-right" width="160">SALDO AKHIR</th>
                    <th>KETERANGAN</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $no = 1;
                foreach ($laporanData as $row): ?>
                <tr>
                    <td class="text-center text-muted col-no"><?= $no++ ?></td>
                    <td class="fw-bold" style="color: #64748b; font-size: 0.85rem;"><?= date('d M Y', strtotime($row['tanggal'])) ?></td>
                    <td>
                        <div class="siswa-info"><?= htmlspecialchars($row['nama_siswa']) ?></div>
                        <div class="kelas-info">Kelas: <?= htmlspecialchars($row['kelas']) ?></div>
                    </td>
                    <td class="text-center">
                        <span class="pro-badge <?= $row['tipe'] === 'setoran' ? 'badge-deposit' : 'badge-withdraw' ?>">
                            <?= $row['tipe'] ?>
                        </span>
                    </td>
                    <td class="text-right fw-bold <?= $row['tipe'] === 'setoran' ? 'text-success' : 'text-danger' ?>" style="font-family: 'Inter', sans-serif; font-size: 0.95rem;">
                        <?= formatRupiah($row['jumlah']) ?>
                    </td>
                    <td class="text-right fw-bold" style="font-family: 'Inter', sans-serif; font-size: 0.95rem; color: #1e293b;">
                        <?= formatRupiah($row['saldo_akhir']) ?>
                    </td>
                    <td class="text-muted italic small"><?= htmlspecialchars($row['keterangan'] ?: '-') ?></td>
                </tr>
                <?php endforeach; ?>
                
                <?php if (empty($laporanData)): ?>
                <tr>
                    <td colspan="6">
                        <div class="empty-state-container">
                            <i class="fas fa-folder-open empty-state-icon"></i>
                            <h4 style="font-weight: 800; color: #94a3b8;">Belum ada transaksi</h4>
                            <p class="text-muted">Tidak ditemukan data transaksi tabungan siswa pada periode ini.</p>
                        </div>
                    </td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
