<?php
// bendahara/laporan/generate.php
$pageTitle = 'Buat 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();

// Proses form jika disubmit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Ambil data dari form
    $title = sanitize($_POST['title']);
    $description = sanitize($_POST['description']);
    $period_start = $_POST['period_start'];
    $period_end = $_POST['period_end'];
    $kampanye_id = isset($_POST['kampanye_id']) ? (int)$_POST['kampanye_id'] : 0;
    
    // Validasi data
    $errors = [];
    
    if (empty($title)) {
        $errors[] = 'Judul laporan wajib diisi';
    }
    
    if (empty($period_start) || empty($period_end)) {
        $errors[] = 'Periode laporan wajib diisi';
    }
    
    if ($period_start > $period_end) {
        $errors[] = 'Tanggal mulai tidak boleh lebih besar dari tanggal selesai';
    }
    
    // Jika tidak ada error, proses pembuatan laporan
    if (empty($errors)) {
        try {
            // Mulai transaksi
            $db->beginTransaction();
            
            // Hitung total donasi 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 ($period_start && $period_end) {
                $query_where .= " AND d.created_at BETWEEN :date_start AND :date_end";
                $query_params[':date_start'] = $period_start . ' 00:00:00';
                $query_params[':date_end'] = $period_end . ' 23:59:59';
            }
            
            $query = "SELECT SUM(d.jumlah) as total_income 
                     FROM donasi d " . $query_where;
            
            $db->query($query);
            foreach ($query_params as $param => $value) {
                $db->bind($param, $value);
            }
            $result = $db->single();
            $total_income = $result->total_income ?? 0;
            
            // Upload file laporan jika ada
            $file_path = null;
            if (isset($_FILES['report_file']) && $_FILES['report_file']['error'] == 0) {
                $upload_dir = UPLOAD_DIR . 'reports/';
                
                // Pastikan direktori ada
                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                
                // Proses upload
                $file_name = uniqid() . '_' . $_FILES['report_file']['name'];
                $file_tmp = $_FILES['report_file']['tmp_name'];
                
                if (move_uploaded_file($file_tmp, $upload_dir . $file_name)) {
                    $file_path = $file_name;
                } else {
                    throw new Exception('Gagal mengupload file laporan');
                }
            }
            
            // Simpan data laporan ke database
            $db->query("INSERT INTO financial_reports (title, description, period_start, period_end, total_income, file_path, created_by) 
                       VALUES (:title, :description, :period_start, :period_end, :total_income, :file_path, :created_by)");
            $db->bind(':title', $title);
            $db->bind(':description', $description);
            $db->bind(':period_start', $period_start);
            $db->bind(':period_end', $period_end);
            $db->bind(':total_income', $total_income);
            $db->bind(':file_path', $file_path);
            $db->bind(':created_by', $_SESSION['user_id']);
            $db->execute();
            
            $report_id = $db->lastInsertId();
            
            // Log aktivitas
            logActivity('Membuat laporan keuangan', 'financial_reports', $report_id, 'Bendahara membuat laporan keuangan: ' . $title);
            
            // Kirim notifikasi ke ketua
            $db->query("SELECT id FROM users WHERE role = 'ketua'");
            $ketua_list = $db->resultSet();
            foreach ($ketua_list as $ketua) {
                createNotification(
                    $ketua->id,
                    'Laporan Keuangan Baru',
                    'Laporan keuangan baru "' . $title . '" telah dibuat oleh Bendahara. Silakan review.',
                    SITE_URL . '/ketua/laporan/detail.php?id=' . $report_id
                );
            }
            
            // Kirim notifikasi ke pengawas
            $db->query("SELECT id FROM users WHERE role = 'pengawas'");
            $pengawas_list = $db->resultSet();
            foreach ($pengawas_list as $pengawas) {
                createNotification(
                    $pengawas->id,
                    'Laporan Keuangan Baru',
                    'Laporan keuangan baru "' . $title . '" telah dibuat oleh Bendahara. Silakan review.',
                    SITE_URL . '/pengawas/laporan/detail.php?id=' . $report_id
                );
            }
            
            // Commit transaksi
            $db->endTransaction();
            
            setFlash('laporan', 'Laporan keuangan berhasil dibuat', 'success');
            header('Location: ' . SITE_URL . '/bendahara/laporan/detail.php?id=' . $report_id);
            exit;
        } catch (Exception $e) {
            // Rollback transaksi jika terjadi error
            $db->cancelTransaction();
            
            setFlash('error', 'Gagal membuat laporan: ' . $e->getMessage(), 'danger');
        }
    }
}

// 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();

// 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">Buat Laporan Keuangan</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/bendahara/laporan/index.php" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-arrow-left me-1"></i> Kembali
                    </a>
                </div>
            </div>
            
            <?php flash(); ?>
            
            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                            <li><?= $error ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>
            
            <div class="card">
                <div class="card-body">
                    <form action="" method="post" enctype="multipart/form-data">
                        <div class="mb-3">
                            <label for="title" class="form-label">Judul Laporan <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="title" name="title" required value="<?= $_POST['title'] ?? 'Laporan Keuangan Periode ' . date('F Y') ?>">
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="period_start" class="form-label">Tanggal Mulai <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="period_start" name="period_start" required value="<?= $_POST['period_start'] ?? date('Y-m-01') ?>">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="period_end" class="form-label">Tanggal Selesai <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="period_end" name="period_end" required value="<?= $_POST['period_end'] ?? date('Y-m-t') ?>">
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="kampanye_id" class="form-label">Kampanye (opsional)</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 ?>" <?= (isset($_POST['kampanye_id']) && $_POST['kampanye_id'] == $kampanye->id) ? 'selected' : '' ?>>
                                        <?= $kampanye->judul ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="form-text">Jika dipilih, laporan hanya akan berisi donasi untuk kampanye yang dipilih</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="description" class="form-label">Deskripsi Laporan</label>
                            <textarea class="form-control" id="description" name="description" rows="3"><?= $_POST['description'] ?? '' ?></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="report_file" class="form-label">File Laporan (opsional)</label>
                            <input type="file" class="form-control" id="report_file" name="report_file">
                            <div class="form-text">Upload file untuk laporan tambahan (format: PDF, DOCX, XLSX)</div>
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i> Laporan akan dibuat berdasarkan data donasi yang terverifikasi sesuai dengan periode yang dipilih. Laporan ini akan dikirimkan ke Ketua Yayasan dan Pengawas untuk review.
                        </div>
                        
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <a href="<?= SITE_URL ?>/bendahara/laporan/index.php" class="btn btn-secondary me-md-2">Batal</a>
                            <button type="submit" class="btn btn-primary">Buat Laporan</button>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>
</div>

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