<?php
session_start();
// Fix path karena di folder pages
require_once '../vendor/autoload.php'; 
include '../config/database.php';

use Dompdf\Dompdf;
use Dompdf\Options;

// Cek login + role bendahara
if(!isset($_SESSION['user_id']) || $_SESSION['role']!= 'bendahara'){
    header("Location:../login.php");
    exit;
}

$db = new Database();
$conn = $db->getConnection();

$gereja_id = $_SESSION['gereja_id'];
$nama_user = $_SESSION['nama'];
$nama_gereja = $_SESSION['nama_gereja'];
$foto_user = $_SESSION['foto']?: 'default.png';

// Default filter: bulan & tahun ini
$bulan = isset($_GET['bulan']) ? $_GET['bulan'] : date('m');
$tahun = isset($_GET['tahun']) ? $_GET['tahun'] : date('Y');

// Query data detail
$q_data = $conn->prepare("SELECT * FROM keuangan WHERE gereja_id = ? AND MONTH(tanggal) = ? AND YEAR(tanggal) = ? ORDER BY tanggal ASC, id ASC");
$q_data->execute([$gereja_id, $bulan, $tahun]);
$data_laporan = $q_data->fetchAll(PDO::FETCH_ASSOC);

// Rekap total
$q_total_masuk = $conn->prepare("SELECT COALESCE(SUM(jumlah),0) FROM keuangan WHERE gereja_id = ? AND tipe='Pemasukan' AND MONTH(tanggal) = ? AND YEAR(tanggal) = ?");
$q_total_masuk->execute([$gereja_id, $bulan, $tahun]);
$total_pemasukan = $q_total_masuk->fetchColumn();

$q_total_keluar = $conn->prepare("SELECT COALESCE(SUM(jumlah),0) FROM keuangan WHERE gereja_id = ? AND tipe='Pengeluaran' AND MONTH(tanggal) = ? AND YEAR(tanggal) = ?");
$q_total_keluar->execute([$gereja_id, $bulan, $tahun]);
$total_pengeluaran = $q_total_keluar->fetchColumn();

$saldo_akhir = $total_pemasukan - $total_pengeluaran;

// Rekap per jenis
$q_rekap_jenis = $conn->prepare("SELECT jenis, tipe, SUM(jumlah) as total FROM keuangan 
                                WHERE gereja_id = ? AND MONTH(tanggal) = ? AND YEAR(tanggal) = ? 
                                GROUP BY jenis, tipe ORDER BY tipe DESC, total DESC");
$q_rekap_jenis->execute([$gereja_id, $bulan, $tahun]);
$rekap_jenis = $q_rekap_jenis->fetchAll(PDO::FETCH_ASSOC);

// Generate PDF
if(isset($_GET['export']) && $_GET['export'] == 'pdf'){
    $options = new Options();
    $options->set('isRemoteEnabled', true);
    $dompdf = new Dompdf($options);
    
    $nama_bulan = date('F', mktime(0, 0, 0, $bulan, 10));
    
    $html = '
    <style>
        body { font-family: Arial, sans-serif; font-size: 12px; }
        h2, h3 { text-align: center; margin: 5px 0; }
        .header { margin-bottom: 20px; border-bottom: 2px solid #000; padding-bottom: 10px; }
        .kop { text-align: center; font-weight: bold; font-size: 14px; }
        table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        th, td { border: 1px solid #333; padding: 6px; text-align: left; }
        th { background-color: #f2f2f2; }
        .text-right { text-align: right; }
        .text-center { text-align: center; }
        .total { font-weight: bold; background-color: #e8e8e8; }
        .footer { margin-top: 40px; width: 100%; }
        .ttd { float: right; text-align: center; width: 200px; }
    </style>
    <div class="header">
        <div class="kop">LAPORAN KEUANGAN</div>
        <div class="kop">'.strtoupper($nama_gereja).'</div>
        <div class="kop">Periode: '.$nama_bulan.' '.$tahun.'</div>
    </div>

    <h4>A. Rekapitulasi</h4>
    <table>
        <tr>
            <td width="70%">Total Pemasukan</td>
            <td class="text-right">Rp '.number_format($total_pemasukan,0,',','.').'</td>
        </tr>
        <tr>
            <td>Total Pengeluaran</td>
            <td class="text-right">Rp '.number_format($total_pengeluaran,0,',','.').'</td>
        </tr>
        <tr class="total">
            <td>Saldo Akhir</td>
            <td class="text-right">Rp '.number_format($saldo_akhir,0,',','.').'</td>
        </tr>
    </table>

    <h4 style="margin-top:20px;">B. Rincian Per Jenis</h4>
    <table>
        <thead>
            <tr>
                <th width="5%">No</th>
                <th>Jenis</th>
                <th>Tipe</th>
                <th class="text-right">Total</th>
            </tr>
        </thead>
        <tbody>';
        $no = 1;
        foreach($rekap_jenis as $rj){
            $html .= '<tr>
                <td class="text-center">'.$no++.'</td>
                <td>'.$rj['jenis'].'</td>
                <td>'.$rj['tipe'].'</td>
                <td class="text-right">Rp '.number_format($rj['total'],0,',','.').'</td>
            </tr>';
        }
        $html .= '</tbody>
    </table>

    <h4 style="margin-top:20px;">C. Detail Transaksi</h4>
    <table>
        <thead>
            <tr>
                <th width="5%">No</th>
                <th width="12%">Tanggal</th>
                <th width="15%">Tipe</th>
                <th width="20%">Jenis</th>
                <th>Keterangan</th>
                <th width="18%" class="text-right">Jumlah</th>
            </tr>
        </thead>
        <tbody>';
        $no = 1;
        if(empty($data_laporan)){
            $html .= '<tr><td colspan="6" class="text-center">Tidak ada data</td></tr>';
        } else {
            foreach($data_laporan as $dl){
                $html .= '<tr>
                    <td class="text-center">'.$no++.'</td>
                    <td>'.date('d/m/Y', strtotime($dl['tanggal'])).'</td>
                    <td>'.$dl['tipe'].'</td>
                    <td>'.$dl['jenis'].'</td>
                    <td>'.$dl['keterangan'].'</td>
                    <td class="text-right">Rp '.number_format($dl['jumlah'],0,',','.').'</td>
                </tr>';
            }
        }
        $html .= '</tbody>
    </table>

    <div class="footer">
        <div class="ttd">
            <p>Makassar, '.date('d F Y').'</p>
            <p>Bendahara,</p>
            <br><br><br>
            <p><u>'.$nama_user.'</u></p>
        </div>
    </div>
    ';

    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    $dompdf->stream("Laporan-Keuangan-".$nama_bulan."-".$tahun.".pdf", array("Attachment" => false));
    exit;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan Keuangan - Bendahara</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background-color: #f8fafc; }
      .sidebar {
            background: linear-gradient(180deg, #1e3a8a 0%, #1e40af 100%);
            min-height: 100vh;
            color: white;
        }
      .sidebar a {
            color: #cbd5e1;
            text-decoration: none;
            display: block;
            padding: 12px 20px;
            transition: all 0.3s;
        }
      .sidebar a:hover,.sidebar a.active {
            background: rgba(255,255,255,0.1);
            color: white;
            border-left: 3px solid #fff;
        }
      .card { border: none; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
      .img-profile { width: 36px; height: 36px; object-fit: cover; }
      .bg-hijau-muda { background-color: #d1fae5; border-left: 4px solid #10b981; }
      .bg-ungu-muda { background-color: #ede9fe; border-left: 4px solid #8b5cf6; }
      .bg-kuning-muda { background-color: #fef3c7; border-left: 4px solid #f59e0b; }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <div class="col-md-2 sidebar p-0">
            <div class="p-3 text-center border-bottom border-light border-opacity-25">
                <i class="fas fa-church fa-2x mb-2"></i>
                <h5 class="mb-0">KEUANGAN GEREJA</h5>
                <small class="text-light text-opacity-75">BENDAHARA</small>
            </div>
            <a href="../dashboard_bendahara.php"><i class="fas fa-tachometer-alt me-2"></i> Dashboard</a>
            <div class="px-3 mt-3 mb-2 text-light text-opacity-50"><small>KEUANGAN GEREJA</small></div>
            <a href="input_keuangan_bendahara.php"><i class="fas fa-wallet me-2"></i> Input Keuangan</a>
            <a href="laporan_keuangan_bendahara.php" class="active"><i class="fas fa-file-invoice-dollar me-2"></i> Laporan Keuangan</a>
            <div class="px-3 mt-4">
                <a href="../logout.php" class="btn btn-danger btn-sm w-100"><i class="fas fa-sign-out-alt me-2"></i> Logout</a>
            </div>
        </div>

        <!-- Konten -->
        <div class="col-md-10 p-4">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h3 class="fw-light">Laporan Keuangan - <?= htmlspecialchars($nama_gereja)?></h3>
                <div class="d-flex align-items-center">
                    <img src="../assets/img/jemaat/<?= $foto_user?>"
                         onerror="this.src='../assets/img/jemaat/default.png'"
                         class="img-profile rounded-circle me-2"
                         alt="Foto">
                    <div>
                        <span class="me-2 text-dark"><?= htmlspecialchars($nama_user)?></span>
                        <span class="badge bg-primary">Bendahara</span>
                    </div>
                </div>
            </div>

            <!-- Filter -->
            <div class="card mb-4">
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">Bulan</label>
                            <select name="bulan" class="form-select">
                                <?php for($i=1; $i<=12; $i++): ?>
                                    <option value="<?= sprintf('%02d', $i) ?>" <?= $bulan == sprintf('%02d', $i) ? 'selected' : '' ?>>
                                        <?= date('F', mktime(0, 0, 0, $i, 10)) ?>
                                    </option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Tahun</label>
                            <select name="tahun" class="form-select">
                                <?php for($i=2023; $i<=date('Y')+1; $i++): ?>
                                    <option value="<?= $i ?>" <?= $tahun == $i ? 'selected' : '' ?>><?= $i ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary w-100"><i class="fas fa-filter me-2"></i>Tampilkan</button>
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <a href="?bulan=<?= $bulan ?>&tahun=<?= $tahun ?>&export=pdf" target="_blank" class="btn btn-danger w-100">
                                <i class="fas fa-file-pdf me-2"></i>Export PDF
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Rekap -->
            <div class="row mb-4">
                <div class="col-md-4 mb-3">
                    <div class="card bg-hijau-muda">
                        <div class="card-body">
                            <h6 class="text-success">TOTAL PEMASUKAN</h6>
                            <h3>Rp <?= number_format($total_pemasukan,0,',','.') ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 mb-3">
                    <div class="card bg-ungu-muda">
                        <div class="card-body">
                            <h6 style="color: #8b5cf6">TOTAL PENGELUARAN</h6>
                            <h3>Rp <?= number_format($total_pengeluaran,0,',','.') ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 mb-3">
                    <div class="card bg-kuning-muda">
                        <div class="card-body">
                            <h6 style="color: #f59e0b">SALDO AKHIR</h6>
                            <h3>Rp <?= number_format($saldo_akhir,0,',','.') ?></h3>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Taruh di dalam card, di atas tabel -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-3">
                <label class="form-label">Bulan</label>
                <select name="bulan" class="form-select">
                    <?php for($i=1; $i<=12; $i++): ?>
                        <option value="<?= sprintf('%02d', $i) ?>" <?= (isset($_GET['bulan']) && $_GET['bulan'] == sprintf('%02d', $i)) ? 'selected' : '' ?>>
                            <?= date('F', mktime(0,0,0,$i,1)) ?>
                        </option>
                    <?php endfor; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">Tahun</label>
                <select name="tahun" class="form-select">
                    <?php for($i=date('Y'); $i>=2020; $i--): ?>
                        <option value="<?= $i ?>" <?= (isset($_GET['tahun']) && $_GET['tahun'] == $i) ? 'selected' : '' ?>><?= $i ?></option>
                    <?php endfor; ?>
                </select>
            </div>
            <div class="col-md-3 d-flex align-items-end">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="filter_tahun" value="1" id="filterTahun">
                    <label class="form-check-label" for="filterTahun">Laporan Tahunan</label>
                </div>
            </div>
            <div class="col-md-3 d-flex align-items-end gap-2">
                <button type="submit" class="btn btn-primary"><i class="fas fa-filter me-2"></i>Filter</button>
                <button type="submit" name="export" value="pdf" formaction="laporan_keuangan_pdf.php" formtarget="_blank" class="btn btn-danger">
                    <i class="fas fa-file-pdf me-2"></i>PDF
                </button>
            </div>
        </form>
    </div>
</div>

            <!-- Tabel Detail -->
            <div class="card">
                <div class="card-header bg-white py-3">
                    <h5 class="mb-0">Detail Transaksi <?= date('F Y', mktime(0,0,0,$bulan,1,$tahun)) ?></h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover table-bordered">
                            <thead class="table-light">
                                <tr>
                                    <th width="5%">No</th>
                                    <th width="12%">Tanggal</th>
                                    <th width="12%">Tipe</th>
                                    <th width="20%">Jenis</th>
                                    <th>Keterangan</th>
                                    <th width="18%" class="text-end">Jumlah</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(empty($data_laporan)):?>
                                    <tr><td colspan="6" class="text-center text-muted py-4">Tidak ada data pada periode ini</td></tr>
                                <?php else:?>
                                    <?php $no=1; foreach($data_laporan as $dl):?>
                                    <tr>
                                        <td class="text-center"><?= $no++?></td>
                                        <td><?= date('d/m/Y', strtotime($dl['tanggal']))?></td>
                                        <td>
                                            <?php if($dl['tipe'] == 'Pemasukan'):?>
                                                <span class="badge bg-success">Pemasukan</span>
                                            <?php else:?>
                                                <span class="badge" style="background:#8b5cf6">Pengeluaran</span>
                                            <?php endif;?>
                                        </td>
                                        <td><?= htmlspecialchars($dl['jenis'])?></td>
                                        <td><?= htmlspecialchars($dl['keterangan'])?></td>
                                        <td class="text-end fw-bold <?= $dl['tipe'] == 'Pemasukan'? 'text-success' : 'text-danger'?>">
                                            Rp <?= number_format($dl['jumlah'],0,',','.')?>
                                        </td>
                                    </tr>
                                    <?php endforeach;?>
                                <?php endif;?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>