<?php
// ketua/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 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;
}

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

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

// Ambil detail laporan
$db->query("SELECT f.*, 
           c1.nama_lengkap as created_by_name, 
           c1.email as created_by_email,
           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 f.id = :id");
$db->bind(':id', $id);
$laporan = $db->single();

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

// Proses persetujuan laporan
if (isset($_POST['approve'])) {
    $db->query("UPDATE financial_reports SET approved_by = :user_id, updated_at = NOW() WHERE id = :id");
    $db->bind(':user_id', $_SESSION['user_id']);
    $db->bind(':id', $id);
    
    if ($db->execute()) {
        // Log aktivitas
        logActivity('Menyetujui laporan keuangan', 'financial_reports', $id, 'Ketua menyetujui laporan keuangan: ' . $laporan->title);
        
        // Buat notifikasi untuk bendahara
        $db->query("SELECT id FROM users WHERE role = 'bendahara'");
        $bendahara = $db->resultSet();
        foreach ($bendahara as $user) {
            createNotification(
                $user->id,
                'Laporan Keuangan Disetujui',
                'Laporan "' . $laporan->title . '" telah disetujui oleh Ketua Yayasan',
                SITE_URL . '/bendahara/laporan/detail.php?id=' . $id
            );
        }
        
        // Buat notifikasi untuk pengawas
        $db->query("SELECT id FROM users WHERE role = 'pengawas'");
        $pengawas = $db->resultSet();
        foreach ($pengawas as $user) {
            createNotification(
                $user->id,
                'Laporan Keuangan Baru',
                'Laporan "' . $laporan->title . '" telah disetujui dan tersedia untuk audit',
                SITE_URL . '/pengawas/laporan/detail.php?id=' . $id
            );
        }
        
        setFlash('laporan', 'Laporan berhasil disetujui', 'success');
        header('Location: ' . SITE_URL . '/ketua/laporan/index.php');
        exit;
    } else {
        setFlash('laporan', 'Gagal menyetujui laporan', 'danger');
    }
}

// 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">Detail Laporan Keuangan</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/ketua/laporan/index.php" class="btn btn-sm btn-outline-secondary me-2">
                        <i class="fas fa-arrow-left me-1"></i> Kembali
                    </a>
                    
                    <?php if ($laporan->file_path): ?>
                        <a href="<?= SITE_URL ?>/assets/uploads/laporan/<?= $laporan->file_path ?>" class="btn btn-sm btn-outline-primary" target="_blank">
                            <i class="fas fa-file-pdf me-1"></i> Unduh Laporan
                        </a>
                    <?php endif; ?>
                </div>
            </div>

            <?php flash(); ?>

            <!-- Detail Laporan -->
            <div class="row">
                <div class="col-md-8">
                    <div class="card mb-4">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Informasi Laporan</h5>
                        </div>
                        <div class="card-body">
                            <table class="table table-borderless">
                                <tr>
                                    <th width="150">Judul Laporan</th>
                                    <td><strong><?= $laporan->title ?></strong></td>
                                </tr>
                                <tr>
                                    <th>Periode</th>
                                    <td><?= date('d/m/Y', strtotime($laporan->period_start)) ?> - <?= date('d/m/Y', strtotime($laporan->period_end)) ?></td>
                                </tr>
                                <tr>
                                    <th>Dibuat Oleh</th>
                                    <td><?= $laporan->created_by_name ?> <span class="text-muted">(<?= $laporan->created_by_email ?>)</span></td>
                                </tr>
                                <tr>
                                    <th>Tanggal Dibuat</th>
                                    <td><?= date('d/m/Y H:i', strtotime($laporan->created_at)) ?></td>
                                </tr>
                                <tr>
                                    <th>Status</th>
                                    <td>
                                        <?php if ($laporan->approved_by): ?>
                                            <span class="badge bg-success">Disetujui oleh <?= $laporan->approved_by_name ?> pada <?= date('d/m/Y H:i', strtotime($laporan->updated_at)) ?></span>
                                        <?php else: ?>
                                            <span class="badge bg-warning text-dark">Menunggu Persetujuan</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php if (!empty($laporan->description)): ?>
                                    <tr>
                                        <th>Deskripsi</th>
                                        <td><?= nl2br($laporan->description) ?></td>
                                    </tr>
                                <?php endif; ?>
                            </table>
                            
                            <!-- Table Ringkasan Keuangan -->
                            <h5 class="mt-4 mb-3">Ringkasan Keuangan</h5>
                            <div class="table-responsive">
                                <table class="table table-bordered">
                                    <tr class="table-light">
                                        <th>Total Pemasukan</th>
                                        <th>Total Pengeluaran</th>
                                        <th>Saldo</th>
                                    </tr>
                                    <tr>
                                        <td class="text-success fw-bold"><?= rupiah($laporan->total_income) ?></td>
                                        <td class="text-danger fw-bold"><?= rupiah($laporan->total_expense) ?></td>
                                        <td class="fw-bold <?= ($laporan->total_income - $laporan->total_expense) >= 0 ? 'text-success' : 'text-danger' ?>">
                                            <?= rupiah($laporan->total_income - $laporan->total_expense) ?>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                            
                            <!-- Detail Transaksi (Jika ada) -->
                            <?php
                            // Ambil detail transaksi jika ada
                            $db->query("SELECT * FROM financial_transactions WHERE report_id = :report_id ORDER BY transaction_date DESC");
                            $db->bind(':report_id', $laporan->id);
                            $transactions = $db->resultSet();
                            
                            if (!empty($transactions)):
                            ?>
                                <h5 class="mt-4 mb-3">Detail Transaksi</h5>
                                <div class="table-responsive">
                                    <table class="table table-striped table-bordered">
                                        <thead>
                                            <tr>
                                                <th width="15%">Tanggal</th>
                                                <th width="40%">Deskripsi</th>
                                                <th width="15%">Kategori</th>
                                                <th width="15%">Debit</th>
                                                <th width="15%">Kredit</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($transactions as $transaction): ?>
                                                <tr>
                                                    <td><?= date('d/m/Y', strtotime($transaction->transaction_date)) ?></td>
                                                    <td><?= $transaction->description ?></td>
                                                    <td><?= $transaction->category ?></td>
                                                    <td class="text-success">
                                                        <?= $transaction->type == 'income' ? rupiah($transaction->amount) : '' ?>
                                                    </td>
                                                    <td class="text-danger">
                                                        <?= $transaction->type == 'expense' ? rupiah($transaction->amount) : '' ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <!-- Status dan Approval -->
                    <div class="card mb-4">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Tindakan</h5>
                        </div>
                        <div class="card-body">
                            <?php if (!$laporan->approved_by): ?>
                                <div class="alert alert-warning">
                                    <h5 class="alert-heading"><i class="fas fa-exclamation-triangle me-2"></i> Menunggu Persetujuan</h5>
                                    <p>Laporan ini menunggu persetujuan Anda sebagai Ketua Yayasan.</p>
                                </div>
                                
                                <form action="" method="post" onsubmit="return confirm('Apakah Anda yakin ingin menyetujui laporan ini?')">
                                    <div class="d-grid">
                                        <button type="submit" name="approve" class="btn btn-success">
                                            <i class="fas fa-check me-1"></i> Setujui Laporan
                                        </button>
                                    </div>
                                </form>
                            <?php else: ?>
                                <div class="alert alert-success">
                                    <h5 class="alert-heading"><i class="fas fa-check-circle me-2"></i> Laporan Disetujui</h5>
                                    <p>Laporan ini telah disetujui pada <?= date('d/m/Y H:i', strtotime($laporan->updated_at)) ?></p>
                                    <p class="mb-0">Disetujui oleh: <?= $laporan->approved_by_name ?></p>
                                </div>
                            <?php endif; ?>
                            
                            <!-- Aktivitas Laporan -->
                            <h5 class="mt-4 mb-3">Riwayat Aktivitas</h5>
                            <?php
                            // Ambil riwayat aktivitas laporan
                            $db->query("SELECT l.*, u.nama_lengkap, u.role 
                                       FROM logs l 
                                       JOIN users u ON l.user_id = u.id 
                                       WHERE l.entity_type = 'financial_reports' AND l.entity_id = :id
                                       ORDER BY l.created_at DESC 
                                       LIMIT 5");
                            $db->bind(':id', $id);
                            $logs = $db->resultSet();
                            
                            if (empty($logs)):
                            ?>
                                <p class="text-muted">Belum ada aktivitas untuk laporan ini.</p>
                            <?php else: ?>
                                <div class="list-group small">
                                    <?php foreach ($logs as $log): ?>
                                        <div class="list-group-item list-group-item-action">
                                            <div class="d-flex w-100 justify-content-between">
                                                <strong><?= $log->activity ?></strong>
                                                <small><?= date('d/m/Y H:i', strtotime($log->created_at)) ?></small>
                                            </div>
                                            <p class="mb-1"><?= $log->description ?></p>
                                            <small>Oleh: <?= $log->nama_lengkap ?> (<?= getRoleName($log->role) ?>)</small>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

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