<?php
/**
 * PDF Preview and Printing for Student Savings Report
 * 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');

// 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] ?? '';
    }
}

// Fetch Data
if ($type === 'harian') {
    $stmt = $db->prepare("
        SELECT ts.*, s.nama as nama_siswa, s.kelas 
        FROM tabungan_siswa ts 
        JOIN siswa s ON ts.siswa_id = s.id 
        WHERE ts.tanggal = ? 
        ORDER BY ts.created_at ASC
    ");
    $stmt->execute([$date]);
    $periodLabel = "Tanggal: " . date('d/m/Y', strtotime($date));
} elseif ($type === 'tahunan') {
    $stmt = $db->prepare("
        SELECT ts.*, s.nama as nama_siswa, s.kelas 
        FROM tabungan_siswa ts 
        JOIN siswa s ON ts.siswa_id = s.id 
        WHERE YEAR(ts.tanggal) = ? 
        ORDER BY ts.tanggal ASC, ts.created_at ASC
    ");
    $stmt->execute([$year]);
    $periodLabel = "Periode: " . $year;
} else {
    $stmt = $db->prepare("
        SELECT ts.*, s.nama as nama_siswa, s.kelas 
        FROM tabungan_siswa ts 
        JOIN siswa s ON ts.siswa_id = s.id 
        WHERE MONTH(ts.tanggal) = ? AND YEAR(ts.tanggal) = ? 
        ORDER BY ts.tanggal ASC, ts.created_at ASC
    ");
    $stmt->execute([$month, $year]);
    $periodLabel = "Periode: " . formatBulan($month) . " " . $year;
}

$data = $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 ($data 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);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Cetak Laporan Tabungan Siswa</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap');
        
        body {
            font-family: 'Inter', sans-serif;
            color: #1e293b;
            background: #f1f5f9;
            margin: 0;
            padding: 20px;
        }

        .preview-controls {
            max-width: 800px;
            margin: 0 auto 20px auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: white;
            padding: 15px 25px;
            border-radius: 12px;
            box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);
        }

        .btn {
            padding: 10px 20px;
            border-radius: 8px;
            font-weight: 700;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            border: none;
            font-size: 14px;
        }

        .btn-print { background: #4f46e5; color: white; }
        .btn-back { background: #f1f5f9; color: #475569; }

        .print-area {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 50px;
            min-height: 1000px;
            box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1);
        }

        /* Report Header Style (KOP Surat) */
        .report-header {
            text-align: center;
            border-bottom: 3px solid #000;
            padding-bottom: 20px;
            margin-bottom: 30px;
        }

        .report-header h1 {
            margin: 0;
            font-size: 24px;
            font-weight: 800;
            text-transform: uppercase;
        }

        .report-header p {
            margin: 5px 0;
            font-size: 14px;
            color: #475569;
        }

        .report-title {
            text-align: center;
            margin-bottom: 30px;
        }

        .report-title h2 {
            margin: 0;
            font-size: 18px;
            text-decoration: underline;
        }

        .summary-boxes {
            display: flex;
            justify-content: space-between;
            gap: 15px;
            margin-bottom: 30px;
        }

        .summary-box {
            flex: 1;
            padding: 15px;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            text-align: right;
        }

        .summary-box .label {
            font-size: 10px;
            text-transform: uppercase;
            font-weight: 700;
            color: #64748b;
            margin-bottom: 5px;
            display: block;
        }

        .summary-box .value {
            font-size: 16px;
            font-weight: 800;
        }

        .table-print {
            width: 100%;
            border-collapse: collapse;
        }

        .table-print th {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            padding: 12px;
            font-size: 10px;
            text-transform: uppercase;
            text-align: left;
        }

        .table-print td {
            border: 1px solid #e2e8f0;
            padding: 12px;
            font-size: 12px;
        }

        .text-right { text-align: right !important; }
        .text-center { text-align: center !important; }
        .fw-bold { font-weight: 700; }
        .text-success { color: #15803d; }
        .text-danger { color: #b91c1c; }

        @media print {
            body { background: white; padding: 0; }
            .preview-controls { display: none !important; }
            .print-area { box-shadow: none; margin: 0; width: 100%; }
        }
    </style>
</head>
<body>

<div class="preview-controls">
    <a href="laporan.php?type=<?= $type ?>&date=<?= $date ?>&month=<?= $month ?>&year=<?= $year ?>" class="btn btn-back">
        <i class="fas fa-arrow-left"></i> Kembali
    </a>
    <div style="font-weight: 700;">Preview Cetak Laporan</div>
    <button onclick="window.print()" class="btn btn-print">
        <i class="fas fa-print"></i> Cetak ke PDF
    </button>
</div>

<div class="print-area">
    <div class="report-header">
        <h1>KOPERASI TSUROYYA</h1>
        <p style="font-size: 18px; font-weight: 700; color: #1e293b; margin-bottom: 5px;">MA Darul Mutaqien</p>
        <p>Bolong, Ngaditirto, Selpampang, Temanggung</p>
    </div>

    <div class="report-title">
        <h2>LAPORAN TABUNGAN SISWA</h2>
        <p style="margin-top: 5px; font-weight: 600;"><?= strtoupper($periodLabel) ?></p>
    </div>

    <div class="summary-boxes">
        <div class="summary-box">
            <span class="label">Total Setoran</span>
            <div class="summary-value text-success"><?= formatRupiah($totalSetoran) ?></div>
        </div>
        <div class="summary-box">
            <span class="label">Total Penarikan</span>
            <div class="summary-value text-danger"><?= formatRupiah($totalPenarikan) ?></div>
        </div>
        <div class="summary-box" style="background: #f8fafc;">
            <span class="label">Saldo Bersih</span>
            <div class="summary-value" style="color: #4f46e5; border-top: 1px solid #e2e8f0; padding-top: 5px; margin-top: 5px;">
                <?= formatRupiah($totalSetoran - $totalPenarikan) ?>
            </div>
        </div>
    </div>

    <table class="table-print">
        <thead>
            <tr>
                <th class="text-center" width="30">NO</th>
                <th width="80">TANGGAL</th>
                <th>NAMA SISWA</th>
                <th width="70">KELAS</th>
                <th class="text-center" width="80">TIPE</th>
                <th class="text-right" width="100">JUMLAH</th>
                <th class="text-right" width="110">SALDO AKHIR</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $no = 1;
            foreach ($data as $row): ?>
            <tr>
                <td class="text-center"><?= $no++ ?></td>
                <td><?= date('d/m/Y', strtotime($row['tanggal'])) ?></td>
                <td class="fw-bold"><?= htmlspecialchars($row['nama_siswa']) ?></td>
                <td><?= htmlspecialchars($row['kelas']) ?></td>
                <td class="text-center" style="text-transform: uppercase; font-size: 10px; font-weight: 700;">
                    <?= $row['tipe'] ?>
                </td>
                <td class="text-right fw-bold <?= $row['tipe'] === 'setoran' ? 'text-success' : 'text-danger' ?>" style="font-size: 11px;">
                    <?= number_format($row['jumlah'], 0, ',', '.') ?>
                </td>
                <td class="text-right fw-bold" style="font-size: 11px;">
                    <?= number_format($row['saldo_akhir'], 0, ',', '.') ?>
                </td>
            </tr>
            <?php endforeach; ?>
            
            <?php if (empty($data)): ?>
            <tr>
                <td colspan="6" class="text-center" style="padding: 40px; color: #94a3b8;">Tidak ada data transaksi ditemukan</td>
            </tr>
            <?php endif; ?>
        </tbody>
    </table>

    <div style="margin-top: 50px; display: flex; justify-content: flex-end;">
        <div style="text-align: center; width: 200px;">
            <p>Dicetak pada: <?= date('d/m/Y H:i') ?></p>
            <p style="margin-top: 60px; border-top: 1px solid #000; padding-top: 5px;">
                Administrator
            </p>
        </div>
    </div>
</div>

<script src="https://kit.fontawesome.com/your-code.js" crossorigin="anonymous"></script>
</body>
</html>
