<?php
// bendahara/laporan/index.php
$pageTitle = 'Laporan Keuangan';
require_once '../../includes/config.php';
require_once '../../includes/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/auth.php';

// Mulai session jika belum dimulai
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Cek apakah user sudah login dan role-nya bendahara
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'bendahara') {
    // Redirect ke halaman login jika belum login atau bukan bendahara
    setFlash('login_required', 'Anda harus login sebagai bendahara untuk mengakses halaman ini', 'danger');
    header('Location: ' . SITE_URL . '/auth/login.php');
    exit;
}

// Koneksi database
$db = dbConnect();

// Filter laporan
$month = isset($_GET['month']) ? $_GET['month'] : date('m');
$year = isset($_GET['year']) ? $_GET['year'] : date('Y');
$kampanye_id = isset($_GET['kampanye_id']) ? (int)$_GET['kampanye_id'] : 0;

// Query untuk laporan berdasarkan filter
$query_params = [];
$query_where = " WHERE d.status = 'diverifikasi'";

if ($kampanye_id > 0) {
    $query_where .= " AND d.kampanye_id = :kampanye_id";
    $query_params[':kampanye_id'] = $kampanye_id;
}

if ($month && $year) {
    $date_start = "$year-$month-01";
    $date_end = date('Y-m-t', strtotime($date_start));
    $query_where .= " AND d.created_at BETWEEN :date_start AND :date_end";
    $query_params[':date_start'] = $date_start;
    $query_params[':date_end'] = $date_end;
}

// Query untuk mendapatkan data laporan donasi
$query = "SELECT d.*, k.judul as kampanye_judul, u.nama_lengkap as donatur_nama 
          FROM donasi d 
          JOIN kampanye k ON d.kampanye_id = k.id 
          JOIN users u ON d.user_id = u.id" . $query_where . 
          " ORDER BY d.created_at DESC";

$db->query($query);
foreach ($query_params as $param => $value) {
    $db->bind($param, $value);
}
$donasi_list = $db->resultSet();

// Hitung total donasi
$total_donasi = 0;
foreach ($donasi_list as $donasi) {
    $total_donasi += $donasi->jumlah;
}

// Ambil daftar kampanye untuk filter
$db->query("SELECT id, judul FROM kampanye WHERE status = 'aktif' OR status = 'selesai' ORDER BY judul");
$kampanye_list = $db->resultSet();

// Ambil total donasi per kampanye untuk diagram
$db->query("SELECT k.id, k.judul, SUM(d.jumlah) as total 
           FROM donasi d 
           JOIN kampanye k ON d.kampanye_id = k.id 
           WHERE d.status = 'diverifikasi' 
           GROUP BY k.id 
           ORDER BY total DESC 
           LIMIT 5");
$kampanye_stats = $db->resultSet();

// Ambil daftar laporan yang sudah dibuat
$db->query("SELECT fr.*, u.nama_lengkap as created_by_name 
           FROM financial_reports fr 
           JOIN users u ON fr.created_by = u.id 
           ORDER BY fr.created_at DESC 
           LIMIT 10");
$report_list = $db->resultSet();

// Include header
require_once '../../includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
            <div class="position-sticky pt-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/bendahara/dashboard.php">
                            <i class="fas fa-tachometer-alt me-2"></i>
                            Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/bendahara/donasi/index.php">
                            <i class="fas fa-donate me-2"></i>
                            Verifikasi Donasi
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="<?= SITE_URL ?>/bendahara/laporan/index.php">
                            <i class="fas fa-chart-bar me-2"></i>
                            Laporan Keuangan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/bendahara/kampanye/index.php">
                            <i class="fas fa-hand-holding-heart me-2"></i>
                            Data Kampanye
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/bendahara/profil/index.php">
                            <i class="fas fa-user-circle me-2"></i>
                            Profil Saya
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/auth/logout.php">
                            <i class="fas fa-sign-out-alt me-2"></i>
                            Logout
                        </a>
                    </li>
                </ul>
                
                <h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
                    <span>Pintasan</span>
                </h6>
                <ul class="nav flex-column mb-2">
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>" target="_blank">
                            <i class="fas fa-external-link-alt me-2"></i>
                            Lihat Website
                        </a>
                    </li>
                </ul>
            </div>
        </nav>

        <!-- Content Area -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">Laporan Keuangan</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    
                    <a href="<?= SITE_URL ?>/bendahara/laporan/generate.php" class="btn btn-sm btn-primary">
                        <i class="fas fa-plus me-1"></i> Buat Laporan Baru
                    </a>
                </div>
            </div>
            
            <?php flash(); ?>
            
            <!-- Filter Laporan -->
            <div class="card mb-4">
                <div class="card-body">
                    <form action="" method="get" class="row g-3">
                        <div class="col-md-4">
                            <label for="month" class="form-label">Bulan</label>
                            <select class="form-select" id="month" name="month">
                                <option value="">Semua Bulan</option>
                                <?php for ($i = 1; $i <= 12; $i++): ?>
                                    <option value="<?= sprintf("%02d", $i) ?>" <?= $month == sprintf("%02d", $i) ? 'selected' : '' ?>>
                                        <?= date('F', mktime(0, 0, 0, $i, 1)) ?>
                                    </option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="year" class="form-label">Tahun</label>
                            <select class="form-select" id="year" name="year">
                                <option value="">Semua Tahun</option>
                                <?php for ($i = date('Y'); $i >= date('Y') - 3; $i--): ?>
                                    <option value="<?= $i ?>" <?= $year == $i ? 'selected' : '' ?>><?= $i ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="kampanye_id" class="form-label">Kampanye</label>
                            <select class="form-select" id="kampanye_id" name="kampanye_id">
                                <option value="">Semua Kampanye</option>
                                <?php foreach ($kampanye_list as $kampanye): ?>
                                    <option value="<?= $kampanye->id ?>" <?= $kampanye_id == $kampanye->id ? 'selected' : '' ?>><?= $kampanye->judul ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary">Filter</button>
                            <a href="<?= SITE_URL ?>/bendahara/laporan/index.php" class="btn btn-secondary">Reset</a>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- Ringkasan dan Diagram -->
            <div class="row mb-4">
                <!-- Ringkasan -->
                <div class="col-md-4">
                    <div class="card h-100">
                        <div class="card-header">
                            <h5 class="card-title mb-0">Ringkasan Laporan</h5>
                        </div>
                        <div class="card-body">
                            <h3 class="text-success mb-4"><?= rupiah($total_donasi) ?></h3>
                            
                            <div class="d-flex justify-content-between mb-3">
                                <span>Total Transaksi</span>
                                <span class="fw-bold"><?= count($donasi_list) ?></span>
                            </div>
                            
                            <div class="d-flex justify-content-between mb-3">
                                <span>Rata-rata Donasi</span>
                                <span class="fw-bold"><?= count($donasi_list) > 0 ? rupiah($total_donasi / count($donasi_list)) : rupiah(0) ?></span>
                            </div>
                            
                            <div class="d-flex justify-content-between mb-3">
                                <span>Periode</span>
                                <span class="fw-bold">
                                    <?php if ($month && $year): ?>
                                        <?= date('F Y', strtotime("$year-$month-01")) ?>
                                    <?php else: ?>
                                        Semua Waktu
                                    <?php endif; ?>
                                </span>
                            </div>
                            
                            <div class="d-flex justify-content-between mb-3">
                                <span>Kampanye</span>
                                <span class="fw-bold">
                                    <?php if ($kampanye_id): ?>
                                        <?php 
                                        $db->query("SELECT judul FROM kampanye WHERE id = :id");
                                        $db->bind(':id', $kampanye_id);
                                        $kampanye_judul = $db->single()->judul ?? 'Tidak ditemukan';
                                        echo $kampanye_judul;
                                        ?>
                                    <?php else: ?>
                                        Semua Kampanye
                                    <?php endif; ?>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Diagram -->
                <div class="col-md-8">
                    <div class="card h-100">
                        <div class="card-header">
                            <h5 class="card-title mb-0">Donasi Per Kampanye</h5>
                        </div>
                        <div class="card-body">
                            <canvas id="campaignChart" height="250"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Tab Laporan -->
            <div class="card mb-4">
                <div class="card-header">
                    <ul class="nav nav-tabs card-header-tabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="transaksi-tab" data-bs-toggle="tab" data-bs-target="#transaksi" type="button" role="tab" aria-controls="transaksi" aria-selected="true">Data Transaksi</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="laporan-tab" data-bs-toggle="tab" data-bs-target="#laporan" type="button" role="tab" aria-controls="laporan" aria-selected="false">Laporan Bulanan</button>
                        </li>
                    </ul>
                </div>
                <div class="card-body">
                    <div class="tab-content">
                        <!-- Tab Transaksi -->
                        <div class="tab-pane fade show active" id="transaksi" role="tabpanel" aria-labelledby="transaksi-tab">
                            <?php if (empty($donasi_list)): ?>
                                <div class="alert alert-info">
                                    Tidak ada data transaksi yang ditemukan untuk filter yang dipilih.
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Tanggal</th>
                                                <th>Donatur</th>
                                                <th>Kampanye</th>
                                                <th>Jumlah</th>
                                                <th>Metode</th>
                                                <th>Diverifikasi Oleh</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php $no = 1; ?>
                                            <?php foreach ($donasi_list as $donasi): ?>
                                                <tr>
                                                    <td><?= $no++ ?></td>
                                                    <td><?= date('d/m/Y H:i', strtotime($donasi->created_at)) ?></td>
                                                    <td><?= $donasi->is_anonim ? 'Anonim' : $donasi->donatur_nama ?></td>
                                                    <td><?= $donasi->kampanye_judul ?></td>
                                                    <td><?= rupiah($donasi->jumlah) ?></td>
                                                    <td><?= $donasi->metode_pembayaran ?></td>
                                                    <td>
                                                        <?php
                                                        if ($donasi->verified_by_bendahara) {
                                                            $db->query("SELECT nama_lengkap FROM users WHERE id = :id");
                                                            $db->bind(':id', $donasi->verified_by_bendahara);
                                                            $verifikator = $db->single();
                                                            echo $verifikator->nama_lengkap ?? 'Unknown';
                                                        } else {
                                                            echo '-';
                                                        }
                                                        ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                        <tfoot>
                                            <tr class="table-success">
                                                <th colspan="4" class="text-end">Total</th>
                                                <th><?= rupiah($total_donasi) ?></th>
                                                <th colspan="2"></th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Tab Laporan Bulanan -->
                        <div class="tab-pane fade" id="laporan" role="tabpanel" aria-labelledby="laporan-tab">
                            <?php if (empty($report_list)): ?>
                                <div class="alert alert-info">
                                    Belum ada laporan bulanan yang dibuat.
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Judul Laporan</th>
                                                <th>Periode</th>
                                                <th>Total Donasi</th>
                                                <th>Dibuat Oleh</th>
                                                <th>Tanggal Dibuat</th>
                                                <th>Status</th>
                                                <th>Aksi</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php $no = 1; ?>
                                            <?php foreach ($report_list as $report): ?>
                                                <tr>
                                                    <td><?= $no++ ?></td>
                                                    <td><?= $report->title ?></td>
                                                    <td><?= date('d/m/Y', strtotime($report->period_start)) ?> - <?= date('d/m/Y', strtotime($report->period_end)) ?></td>
                                                    <td><?= rupiah($report->total_income) ?></td>
                                                    <td><?= $report->created_by_name ?></td>
                                                    <td><?= date('d/m/Y H:i', strtotime($report->created_at)) ?></td>
                                                    <td>
                                                        <?php if ($report->approved_by): ?>
                                                            <span class="badge bg-success">Disetujui</span>
                                                        <?php else: ?>
                                                            <span class="badge bg-warning text-dark">Menunggu Persetujuan</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <a href="<?= SITE_URL ?>/bendahara/laporan/detail.php?id=<?= $report->id ?>" class="btn btn-sm btn-info">
                                                            <i class="fas fa-eye"></i> Detail
                                                        </a>
                                                        <?php if ($report->file_path): ?>
                                                            <a href="<?= SITE_URL ?>/assets/uploads/reports/<?= $report->file_path ?>" class="btn btn-sm btn-primary" target="_blank">
                                                                <i class="fas fa-download"></i> Download
                                                            </a>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Script untuk diagram -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Data untuk diagram donasi per kampanye
    const campaignData = {
        labels: [
            <?php foreach ($kampanye_stats as $kampanye): ?>
                '<?= $kampanye->judul ?>',
            <?php endforeach; ?>
        ],
        datasets: [{
            label: 'Total Donasi',
            data: [
                <?php foreach ($kampanye_stats as $kampanye): ?>
                    <?= $kampanye->total ?>,
                <?php endforeach; ?>
            ],
            backgroundColor: [
                'rgba(75, 192, 192, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(255, 99, 132, 0.2)',
                'rgba(153, 102, 255, 0.2)'
            ],
            borderColor: [
                'rgba(75, 192, 192, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(255, 99, 132, 1)',
                'rgba(153, 102, 255, 1)'
            ],
            borderWidth: 1
        }]
    };

    // Konfigurasi diagram
    const config = {
        type: 'bar',
        data: campaignData,
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'top',
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            let label = context.dataset.label || '';
                            if (label) {
                                label += ': ';
                            }
                            if (context.parsed.y !== null) {
                                label += new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR' }).format(context.parsed.y);
                            }
                            return label;
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value, index, values) {
                            return new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumSignificantDigits: 3 }).format(value);
                        }
                    }
                }
            }
        },
    };

    // Render diagram
    var campaignChart = new Chart(
        document.getElementById('campaignChart'),
        config
    );
});
</script>

<?php require_once '../../includes/footer.php'; ?>