<?php
// bendahara/laporan/detail.php
$pageTitle = 'Detail 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;
}

// Cek apakah ada ID laporan
if (!isset($_GET['id']) || empty($_GET['id'])) {
    setFlash('error', 'ID laporan tidak valid', 'danger');
    header('Location: ' . SITE_URL . '/bendahara/laporan/index.php');
    exit;
}

$id = (int)$_GET['id'];
$db = dbConnect();

// Ambil detail laporan
$db->query("SELECT fr.*, u.nama_lengkap as created_by_name 
           FROM financial_reports fr 
           JOIN users u ON fr.created_by = u.id 
           WHERE fr.id = :id");
$db->bind(':id', $id);
$report = $db->single();

if (!$report) {
    setFlash('error', 'Laporan tidak ditemukan', 'danger');
    header('Location: ' . SITE_URL . '/bendahara/laporan/index.php');
    exit;
}

// Ambil data ketua yang menyetujui laporan (jika ada)
$ketua_approver = null;
if ($report->approved_by) {
    $db->query("SELECT nama_lengkap FROM users WHERE id = :id");
    $db->bind(':id', $report->approved_by);
    $ketua_approver = $db->single();
}

// Ambil data donasi terkait laporan
$query_params = [];
$query_where = " WHERE d.status = 'diverifikasi'";

if (strtotime($report->period_start) && strtotime($report->period_end)) {
    $query_where .= " AND d.created_at BETWEEN :date_start AND :date_end";
    $query_params[':date_start'] = $report->period_start . ' 00:00:00';
    $query_params[':date_end'] = $report->period_end . ' 23:59:59';
}

$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;
}

// Hitung statistik donasi per kampanye
$kampanye_stats = [];
foreach ($donasi_list as $donasi) {
    if (!isset($kampanye_stats[$donasi->kampanye_id])) {
        $kampanye_stats[$donasi->kampanye_id] = [
            'judul' => $donasi->kampanye_judul,
            'total' => 0,
            'jumlah' => 0
        ];
    }
    
    $kampanye_stats[$donasi->kampanye_id]['total'] += $donasi->jumlah;
    $kampanye_stats[$donasi->kampanye_id]['jumlah']++;
}

// Sort kampanye stats by total
usort($kampanye_stats, function($a, $b) {
    return $b['total'] - $a['total'];
});

// 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">Detail Laporan Keuangan</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <div class="btn-group me-2">
                        <a href="<?= SITE_URL ?>/bendahara/laporan/export.php?id=<?= $id ?>&type=pdf" target="_blank" class="btn btn-sm btn-outline-secondary">
                            <i class="fas fa-file-pdf me-1"></i> Export PDF
                        </a>
                        <a href="<?= SITE_URL ?>/bendahara/laporan/export.php?id=<?= $id ?>&type=excel" class="btn btn-sm btn-outline-secondary">
                            <i class="fas fa-file-excel me-1"></i> Export Excel
                        </a>
                    </div>
                    <a href="<?= SITE_URL ?>/bendahara/laporan/index.php" class="btn btn-sm btn-outline-primary">
                        <i class="fas fa-arrow-left me-1"></i> Kembali
                    </a>
                </div>
            </div>
            
            <?php flash(); ?>
            
            <!-- Detail Laporan -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Informasi Laporan</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-borderless">
                                <tr>
                                    <td width="40%">Judul Laporan</td>
                                    <td width="60%"><strong><?= $report->title ?></strong></td>
                                </tr>
                                <tr>
                                    <td>Periode</td>
                                    <td><?= date('d/m/Y', strtotime($report->period_start)) ?> - <?= date('d/m/Y', strtotime($report->period_end)) ?></td>
                                </tr>
                                <tr>
                                    <td>Total Donasi</td>
                                    <td><strong class="text-success"><?= rupiah($report->total_income) ?></strong></td>
                                </tr>
                                <tr>
                                    <td>Dibuat Oleh</td>
                                    <td><?= $report->created_by_name ?></td>
                                </tr>
                                <tr>
                                    <td>Tanggal Dibuat</td>
                                    <td><?= date('d/m/Y H:i', strtotime($report->created_at)) ?></td>
                                </tr>
                                <tr>
                                    <td>Status</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>
                                </tr>
                                <?php if ($report->approved_by && $ketua_approver): ?>
                                    <tr>
                                        <td>Disetujui Oleh</td>
                                        <td><?= $ketua_approver->nama_lengkap ?></td>
                                    </tr>
                                <?php endif; ?>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <?php if ($report->description): ?>
                                <h6>Deskripsi</h6>
                                <p><?= nl2br($report->description) ?></p>
                            <?php endif; ?>
                            
                            <?php if ($report->file_path): ?>
                                <h6>File Laporan</h6>
                                <p>
                                    <a href="<?= SITE_URL ?>/assets/uploads/reports/<?= $report->file_path ?>" class="btn btn-sm btn-primary" target="_blank">
                                        <i class="fas fa-download me-1"></i> Download File Laporan
                                    </a>
                                </p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Diagram -->
            <div class="row mb-4">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">Donasi Per Kampanye</h5>
                        </div>
                        <div class="card-body">
                            <canvas id="campaignChart" height="200"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Detail Transaksi -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Detail Transaksi</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($donasi_list)): ?>
                        <div class="alert alert-info">
                            Tidak ada data transaksi yang ditemukan untuk periode laporan ini.
                        </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>
                                    </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>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr class="table-success">
                                        <th colspan="4" class="text-end">Total</th>
                                        <th><?= rupiah($total_donasi) ?></th>
                                        <th></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Statistik Kampanye -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Statistik Per Kampanye</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($kampanye_stats)): ?>
                        <div class="alert alert-info">
                            Tidak ada data statistik kampanye yang ditemukan.
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Kampanye</th>
                                        <th>Jumlah Donasi</th>
                                        <th>Total</th>
                                        <th>Persentase</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $no = 1; ?>
                                    <?php foreach ($kampanye_stats as $kampanye): ?>
                                        <?php $persentase = $total_donasi > 0 ? ($kampanye['total'] / $total_donasi) * 100 : 0; ?>
                                        <tr>
                                            <td><?= $no++ ?></td>
                                            <td><?= $kampanye['judul'] ?></td>
                                            <td><?= $kampanye['jumlah'] ?></td>
                                            <td><?= rupiah($kampanye['total']) ?></td>
                                            <td>
                                                <div class="progress" style="height: 6px;">
                                                    <div class="progress-bar bg-success" role="progressbar" style="width: <?= $persentase ?>%;" aria-valuenow="<?= $persentase ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                                </div>
                                                <span class="small"><?= number_format($persentase, 2) ?>%</span>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </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)',
                'rgba(255, 159, 64, 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)',
                'rgba(255, 159, 64, 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'; ?>