<?php
// ketua/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 ketua
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'ketua') {
    // Redirect ke halaman login jika belum login atau bukan ketua
    setFlash('login_required', 'Anda harus login sebagai ketua yayasan untuk mengakses halaman ini', 'danger');
    header('Location: ' . SITE_URL . '/auth/login.php');
    exit;
}

// Koneksi database
$db = dbConnect();

// Pagination
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($current_page - 1) * $limit;

// Filter
$periode = isset($_GET['periode']) ? $_GET['periode'] : '';
$search = isset($_GET['search']) ? $_GET['search'] : '';

// Query untuk menghitung total laporan
$query_count = "SELECT COUNT(*) as total FROM financial_reports WHERE 1=1";
$query_params = [];

if (!empty($periode)) {
    $periode_parts = explode(' - ', $periode);
    if (count($periode_parts) == 2) {
        $start_date = date('Y-m-d', strtotime($periode_parts[0]));
        $end_date = date('Y-m-d', strtotime($periode_parts[1]));
        
        $query_count .= " AND (period_start BETWEEN :start_date AND :end_date OR period_end BETWEEN :start_date2 AND :end_date2)";
        $query_params[':start_date'] = $start_date;
        $query_params[':end_date'] = $end_date;
        $query_params[':start_date2'] = $start_date;
        $query_params[':end_date2'] = $end_date;
    }
}

if (!empty($search)) {
    $query_count .= " AND (title LIKE :search OR description LIKE :search)";
    $query_params[':search'] = "%$search%";
}

$db->query($query_count);
foreach ($query_params as $param => $value) {
    $db->bind($param, $value);
}
$total_rows = $db->single()->total;
$total_pages = ceil($total_rows / $limit);

// Query untuk mengambil data laporan keuangan
$query = "SELECT f.*, 
          c1.nama_lengkap as created_by_name, 
          c2.nama_lengkap as approved_by_name
          FROM financial_reports f
          LEFT JOIN users c1 ON f.created_by = c1.id
          LEFT JOIN users c2 ON f.approved_by = c2.id
          WHERE 1=1";

if (!empty($periode)) {
    $periode_parts = explode(' - ', $periode);
    if (count($periode_parts) == 2) {
        $query .= " AND (f.period_start BETWEEN :start_date AND :end_date OR f.period_end BETWEEN :start_date2 AND :end_date2)";
    }
}

if (!empty($search)) {
    $query .= " AND (f.title LIKE :search OR f.description LIKE :search)";
}

$query .= " ORDER BY f.created_at DESC LIMIT :offset, :limit";

$db->query($query);
foreach ($query_params as $param => $value) {
    $db->bind($param, $value);
}
$db->bind(':offset', $offset, PDO::PARAM_INT);
$db->bind(':limit', $limit, PDO::PARAM_INT);
$laporan_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 ?>/ketua/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 ?>/ketua/kampanye/index.php">
                            <i class="fas fa-hand-holding-heart me-2"></i>
                            Persetujuan Kampanye
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="<?= SITE_URL ?>/ketua/laporan/index.php">
                            <i class="fas fa-chart-line me-2"></i>
                            Laporan Keuangan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/kegiatan/index.php">
                            <i class="fas fa-newspaper me-2"></i>
                            Kegiatan Yayasan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/staff/index.php">
                            <i class="fas fa-users-cog me-2"></i>
                            Manajemen Staff
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/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 ?>/ketua/dashboard.php" class="btn btn-sm btn-outline-secondary me-2">
                        <i class="fas fa-arrow-left me-1"></i> Kembali
                    </a>
                </div>
            </div>

            <?php flash(); ?>

            <!-- <!-- Filter & Search --> 
            <!-- <div class="card mb-4"> -->
                <!-- <div class="card-body"> -->
                    <!-- <form action="" method="get" class="row g-3"> -->
                        <!-- <div class="col-md-5"> -->
                            <!-- <label for="search" class="form-label">Cari</label> -->
                            <!-- <input type="text" class="form-control" id="search" name="search" placeholder="Cari judul laporan..." value="<?= $search ?>"> -->
                        <!-- </div> -->
                        <!-- <div class="col-md-4"> -->
                            <!-- <label for="periode" class="form-label">Periode</label> -->
                            <!-- <input type="text" class="form-control" id="periode" name="periode" placeholder="Pilih periode" value="<?= $periode ?>"> -->
                        <!-- </div> -->
                        <!-- <div class="col-md-3 d-flex align-items-end"> -->
                            <!-- <button type="submit" class="btn btn-primary me-2">Filter</button> -->
                            <!-- <a href="< ?= SITE_URL ? >/ketua/laporan/index.php" class="btn btn-secondary">Reset</a> -->
                        <!-- </div> -->
                    <!-- </form> -->
                <!-- </div> -->
            <!-- </div> -->

            <!-- Tabel Laporan Keuangan -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th scope="col" width="5%">#</th>
                                    <th scope="col" width="25%">Judul Laporan</th>
                                    <th scope="col" width="15%">Periode</th>
                                    <th scope="col" width="15%">Pemasukan</th>
                                    <th scope="col" width="15%">Pengeluaran</th>
                                    <th scope="col" width="10%">Status</th>
                                    <th scope="col" width="15%">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($laporan_list)): ?>
                                    <tr>
                                        <td colspan="7" class="text-center py-4">Tidak ada data laporan</td>
                                    </tr>
                                <?php else: ?>
                                    <?php $no = $offset + 1; ?>
                                    <?php foreach ($laporan_list as $laporan): ?>
                                        <tr>
                                            <th scope="row"><?= $no++ ?></th>
                                            <td>
                                                <strong><?= $laporan->title ?></strong>
                                                <div class="small text-muted">
                                                    Oleh: <?= $laporan->created_by_name ?>
                                                </div>
                                            </td>
                                            <td>
                                                <?= date('d/m/Y', strtotime($laporan->period_start)) ?> - <?= date('d/m/Y', strtotime($laporan->period_end)) ?>
                                            </td>
                                            <td class="text-success"><?= rupiah($laporan->total_income) ?></td>
                                            <td class="text-danger"><?= rupiah($laporan->total_expense) ?></td>
                                            <td>
                                                <?php if ($laporan->approved_by): ?>
                                                    <span class="badge bg-success">Disetujui</span>
                                                <?php else: ?>
                                                    <span class="badge bg-warning text-dark">Menunggu</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <a href="<?= SITE_URL ?>/ketua/laporan/detail.php?id=<?= $laporan->id ?>" class="btn btn-sm btn-primary mb-1 w-100">
                                                    <i class="fas fa-eye"></i> Detail
                                                </a>
                                                
                                                <?php if (!$laporan->approved_by): ?>
                                                    <a href="<?= SITE_URL ?>/ketua/laporan/approve.php?id=<?= $laporan->id ?>" class="btn btn-sm btn-success w-100" onclick="return confirm('Apakah Anda yakin ingin menyetujui laporan ini?')">
                                                        <i class="fas fa-check"></i> Setujui
                                                    </a>
                                                <?php else: ?>
                                                    <?php if ($laporan->file_path): ?>
                                                        <a href="<?= SITE_URL ?>/assets/uploads/laporan/<?= $laporan->file_path ?>" class="btn btn-sm btn-outline-primary w-100" target="_blank">
                                                            <i class="fas fa-file-pdf"></i> Unduh
                                                        </a>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center">
                                <li class="page-item <?= ($current_page <= 1) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="<?= SITE_URL ?>/ketua/laporan/index.php?page=<?= $current_page - 1 ?><?= !empty($periode) ? '&periode=' . $periode : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>">Previous</a>
                                </li>
                                
                                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                    <li class="page-item <?= ($current_page == $i) ? 'active' : '' ?>">
                                        <a class="page-link" href="<?= SITE_URL ?>/ketua/laporan/index.php?page=<?= $i ?><?= !empty($periode) ? '&periode=' . $periode : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>"><?= $i ?></a>
                                    </li>
                                <?php endfor; ?>
                                
                                <li class="page-item <?= ($current_page >= $total_pages) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="<?= SITE_URL ?>/ketua/laporan/index.php?page=<?= $current_page + 1 ?><?= !empty($periode) ? '&periode=' . $periode : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>">Next</a>
                                </li>
                            </ul>
                        </nav>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Ringkasan Keuangan -->
            <div class="row mt-4">
                <div class="col-md-6 mb-4">
                    <div class="card">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Ringkasan Keuangan</h5>
                        </div>
                        <div class="card-body">
                            <?php
                            // Ambil ringkasan keuangan
                            $db->query("SELECT 
                                        SUM(total_income) as total_pemasukan,
                                        SUM(total_expense) as total_pengeluaran
                                        FROM financial_reports");
                            $ringkasan = $db->single();
                            
                            $total_pemasukan = $ringkasan->total_pemasukan ?? 0;
                            $total_pengeluaran = $ringkasan->total_pengeluaran ?? 0;
                            $saldo = $total_pemasukan - $total_pengeluaran;
                            ?>
                            
                            <div class="table-responsive">
                                <table class="table table-bordered">
                                    <tr>
                                        <th class="table-light">Total Pemasukan</th>
                                        <td class="text-success fw-bold"><?= rupiah($total_pemasukan) ?></td>
                                    </tr>
                                    <tr>
                                        <th class="table-light">Total Pengeluaran</th>
                                        <td class="text-danger fw-bold"><?= rupiah($total_pengeluaran) ?></td>
                                    </tr>
                                    <tr>
                                        <th class="table-light">Saldo</th>
                                        <td class="fw-bold <?= $saldo >= 0 ? 'text-success' : 'text-danger' ?>"><?= rupiah($saldo) ?></td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- <div class="col-md-6 mb-4"> -->
                    <!-- <div class="card h-100"> -->
                        <!-- <div class="card-header bg-light"> -->
                            <!-- <h5 class="mb-0">Statistik Keuangan Tahunan</h5> -->
                        <!-- </div> -->
                        <!-- <div class="card-body"> -->
                            <!-- <canvas id="chartKeuangan" height="250"></canvas> -->
                        <!-- </div> -->
                    <!-- </div> -->
                <!-- </div> -->
            </div>
        </main>
    </div>
</div>

<!-- Date Range Picker -->
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
$(function() {
    // Date Range Picker
    $('#periode').daterangepicker({
        locale: {
            format: 'DD/MM/YYYY',
            separator: ' - ',
            applyLabel: 'Pilih',
            cancelLabel: 'Batal',
            fromLabel: 'Dari',
            toLabel: 'Sampai',
            customRangeLabel: 'Custom',
            weekLabel: 'W',
            daysOfWeek: ['Mn', 'Sn', 'Sl', 'Rb', 'Km', 'Jm', 'Sb'],
            monthNames: ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'],
            firstDay: 1
        },
        opens: 'left',
        autoUpdateInput: false
    });
    
    $('#periode').on('apply.daterangepicker', function(ev, picker) {
        $(this).val(picker.startDate.format('DD/MM/YYYY') + ' - ' + picker.endDate.format('DD/MM/YYYY'));
    });
    
    $('#periode').on('cancel.daterangepicker', function(ev, picker) {
        $(this).val('');
    });
    
    // Chart Keuangan
    var ctx = document.getElementById('chartKeuangan').getContext('2d');
    var chartKeuangan = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'],
            datasets: [
                {
                    label: 'Pemasukan',
                    data: [
                        <?php
                        // Data keuangan per bulan pada tahun ini
                        $tahun_ini = date('Y');
                        for($bulan = 1; $bulan <= 12; $bulan++) {
                            $db->query("SELECT SUM(total_income) as total FROM financial_reports 
                                        WHERE YEAR(period_start) = :tahun AND MONTH(period_start) = :bulan");
                            $db->bind(':tahun', $tahun_ini);
                            $db->bind(':bulan', $bulan);
                            $result = $db->single();
                            echo ($result->total ?? 0) . ',';
                        }
                        ?>
                    ],
                    backgroundColor: 'rgba(40, 167, 69, 0.2)',
                    borderColor: 'rgba(40, 167, 69, 1)',
                    borderWidth: 1
                },
                {
                    label: 'Pengeluaran',
                    data: [
                        <?php
                        // Data keuangan per bulan pada tahun ini
                        for($bulan = 1; $bulan <= 12; $bulan++) {
                            $db->query("SELECT SUM(total_expense) as total FROM financial_reports 
                                        WHERE YEAR(period_start) = :tahun AND MONTH(period_start) = :bulan");
                            $db->bind(':tahun', $tahun_ini);
                            $db->bind(':bulan', $bulan);
                            $result = $db->single();
                            echo ($result->total ?? 0) . ',';
                        }
                        ?>
                    ],
                    backgroundColor: 'rgba(220, 53, 69, 0.2)',
                    borderColor: 'rgba(220, 53, 69, 1)',
                    borderWidth: 1
                }
            ]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'top',
                },
                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);
                        }
                    }
                }
            }
        }
    });
});
</script>

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