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

// Koneksi database
$db = dbConnect();

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

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

// Query untuk menghitung total laporan
$query_count = "SELECT COUNT(*) as total FROM financial_reports fr
                JOIN users creator ON fr.created_by = creator.id
                LEFT JOIN users approver ON fr.approved_by = approver.id
                WHERE 1=1";

$query_params = [];

if (!empty($period)) {
    list($period_start, $period_end) = explode(' - ', $period);
    $query_count .= " AND (fr.period_start >= :period_start AND fr.period_end <= :period_end)";
    $query_params[':period_start'] = date('Y-m-d', strtotime($period_start));
    $query_params[':period_end'] = date('Y-m-d', strtotime($period_end));
}

if (!empty($status)) {
    if ($status == 'approved') {
        $query_count .= " AND fr.approved_by IS NOT NULL";
    } else {
        $query_count .= " AND fr.approved_by IS NULL";
    }
}

if (!empty($search)) {
    $query_count .= " AND (fr.title LIKE :search OR fr.description LIKE :search OR creator.nama_lengkap 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
$query = "SELECT fr.*, 
          creator.nama_lengkap as created_by_name,
          approver.nama_lengkap as approved_by_name
          FROM financial_reports fr
          JOIN users creator ON fr.created_by = creator.id
          LEFT JOIN users approver ON fr.approved_by = approver.id
          WHERE 1=1";

if (!empty($period)) {
    list($period_start, $period_end) = explode(' - ', $period);
    $query .= " AND (fr.period_start >= :period_start AND fr.period_end <= :period_end)";
}

if (!empty($status)) {
    if ($status == 'approved') {
        $query .= " AND fr.approved_by IS NOT NULL";
    } else {
        $query .= " AND fr.approved_by IS NULL";
    }
}

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

$query .= " ORDER BY fr.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 ?>/pengawas/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 ?>/pengawas/audit/index.php"> -->
                            <!-- <i class="fas fa-search-dollar me-2"></i> -->
                            <!-- Audit Transaksi -->
                        <!-- </a> -->
                    <!-- </li> -->
                    <li class="nav-item">
                        <a class="nav-link active" href="<?= SITE_URL ?>/pengawas/laporan/index.php">
                            <i class="fas fa-file-alt me-2"></i>
                            Laporan Keuangan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/pengawas/logs/index.php">
                            <i class="fas fa-history me-2"></i>
                            Log Aktivitas
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link " href="<?= SITE_URL ?>/pengawas/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">
                    <div class="dropdown">
                        <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fas fa-file-export me-1"></i> Export
                        </button>
                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                            <li><a class="dropdown-item" href="<?= SITE_URL ?>/pengawas/laporan/export.php?type=pdf<?= !empty($period) ? '&period=' . $period : '' ?><?= !empty($status) ? '&status=' . $status : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>">PDF</a></li>
                            <li><a class="dropdown-item" href="<?= SITE_URL ?>/pengawas/laporan/export.php?type=excel<?= !empty($period) ? '&period=' . $period : '' ?><?= !empty($status) ? '&status=' . $status : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>">Excel</a></li>
                        </ul>
                    </div>
                </div>
            </div>

            <?php flash(); ?>

            <!-- Filter -->
            <div class="card mb-4">
                <div class="card-body">
                    <form action="" method="get" class="row g-3">
                        <div class="col-md-4">
                            <label for="period" class="form-label">Periode</label>
                            <input type="text" class="form-control" id="period" name="period" placeholder="Pilih periode" value="<?= $period ?>">
                        </div>
                        <div class="col-md-3">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-select" id="status" name="status">
                                <option value="">Semua Status</option>
                                <option value="pending" <?= $status == 'pending' ? 'selected' : '' ?>>Menunggu Persetujuan</option>
                                <option value="approved" <?= $status == 'approved' ? 'selected' : '' ?>>Disetujui</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="search" class="form-label">Pencarian</label>
                            <input type="text" class="form-control" id="search" name="search" placeholder="Cari..." value="<?= $search ?>">
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-filter me-1"></i> Filter
                            </button>
                        </div>
                        <div class="col-12">
                            <a href="<?= SITE_URL ?>/pengawas/laporan/index.php" class="btn btn-secondary">
                                <i class="fas fa-sync-alt me-1"></i> Reset
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Tabel Laporan -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Judul</th>
                                    <th>Periode</th>
                                    <th>Pemasukan</th>
                                    <th>Pengeluaran</th>
                                    <th>Saldo</th>
                                    <th>Dibuat Oleh</th>
                                    <th>Status</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($laporan_list)): ?>
                                    <tr>
                                        <td colspan="9" class="text-center py-4">Tidak ada data laporan</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($laporan_list as $laporan): ?>
                                        <tr>
                                            <td><?= $laporan->id ?></td>
                                            <td><?= $laporan->title ?></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 class="<?= $laporan->total_income - $laporan->total_expense >= 0 ? 'text-success' : 'text-danger' ?>">
                                                <?= rupiah($laporan->total_income - $laporan->total_expense) ?>
                                            </td>
                                            <td><?= $laporan->created_by_name ?></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 ?>/pengawas/laporan/detail.php?id=<?= $laporan->id ?>" class="btn btn-sm btn-primary">
                                                    <i class="fas fa-search me-1"></i> Detail
                                                </a>
                                            </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 ?>/pengawas/laporan/index.php?page=<?= $current_page - 1 ?><?= !empty($period) ? '&period=' . $period : '' ?><?= !empty($status) ? '&status=' . $status : '' ?><?= !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 ?>/pengawas/laporan/index.php?page=<?= $i ?><?= !empty($period) ? '&period=' . $period : '' ?><?= !empty($status) ? '&status=' . $status : '' ?><?= !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 ?>/pengawas/laporan/index.php?page=<?= $current_page + 1 ?><?= !empty($period) ? '&period=' . $period : '' ?><?= !empty($status) ? '&status=' . $status : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>">Next</a>
                                </li>
                            </ul>
                        </nav>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Script untuk 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>
$(function() {
    $('#period').daterangepicker({
        opens: 'left',
        autoUpdateInput: false,
        locale: {
            format: 'DD/MM/YYYY',
            cancelLabel: 'Clear'
        }
    });

    $('#period').on('apply.daterangepicker', function(ev, picker) {
        $(this).val(picker.startDate.format('DD/MM/YYYY') + ' - ' + picker.endDate.format('DD/MM/YYYY'));
    });

    $('#period').on('cancel.daterangepicker', function(ev, picker) {
        $(this).val('');
    });
    
    // Set nilai awal jika ada
    if ('<?= $period ?>') {
        $('#period').val('<?= $period ?>');
    }
});
</script>

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