<?php
// bendahara/kampanye/index.php
$pageTitle = 'Data Kampanye';
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 filter dan search
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$search = isset($_GET['search']) ? $_GET['search'] : '';

// Query dasar
$query_base = "SELECT k.*, u.nama_lengkap as created_by_name,
               (SELECT SUM(d.jumlah) FROM donasi d WHERE d.kampanye_id = k.id AND d.status = 'diverifikasi') as total_donasi,
               (SELECT COUNT(d.id) FROM donasi d WHERE d.kampanye_id = k.id AND d.status = 'diverifikasi') as jumlah_donatur
               FROM kampanye k
               LEFT JOIN users u ON k.created_by = u.id
               WHERE 1=1";
$params = [];

// Tambahkan filter
if (!empty($status_filter)) {
    $query_base .= " AND k.status = :status";
    $params[':status'] = $status_filter;
}

if (!empty($search)) {
    $query_base .= " AND (k.judul LIKE :search OR k.deskripsi LIKE :search)";
    $params[':search'] = "%$search%";
}

// Hitung total untuk pagination
$query_count = "SELECT COUNT(*) as total FROM ($query_base) as t";
$db->query($query_count);
foreach ($params as $param => $value) {
    $db->bind($param, $value);
}
$total_rows = $db->single()->total;

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

// Query final dengan order dan limit
$query_final = $query_base . " ORDER BY k.created_at DESC LIMIT :offset, :per_page";
$db->query($query_final);
foreach ($params as $param => $value) {
    $db->bind($param, $value);
}
$db->bind(':offset', $offset, PDO::PARAM_INT);
$db->bind(':per_page', $per_page, PDO::PARAM_INT);
$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" 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 active" 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">Data Kampanye</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <div class="btn-group me-2">
                        <a href="<?= SITE_URL ?>/bendahara/laporan/kampanye.php" class="btn btn-sm btn-outline-secondary">
                            <i class="fas fa-file-pdf me-1"></i> Download Laporan
                        </a>
                    </div>
                </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-4">
                            <label for="status" class="form-label">Status Kampanye</label>
                            <select class="form-select" id="status" name="status">
                                <option value="">Semua Status</option>
                                <option value="aktif" <?= $status_filter == 'aktif' ? 'selected' : '' ?>>Aktif</option>
                                <option value="selesai" <?= $status_filter == 'selesai' ? 'selected' : '' ?>>Selesai</option>
                                <option value="dibatalkan" <?= $status_filter == 'dibatalkan' ? 'selected' : '' ?>>Dibatalkan</option>
                                <option value="menunggu_persetujuan" <?= $status_filter == 'menunggu_persetujuan' ? 'selected' : '' ?>>Menunggu Persetujuan</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="search" class="form-label">Pencarian</label>
                            <input type="text" class="form-control" id="search" name="search" placeholder="Cari judul atau deskripsi..." value="<?= $search ?>">
                        </div>
                        <div class="col-md-4 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2">Filter</button>
                            <a href="<?= SITE_URL ?>/bendahara/kampanye/index.php" class="btn btn-secondary">Reset</a>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- Daftar Kampanye -->
            <div class="card">
                <div class="card-body">
                    <?php if (empty($kampanye_list)): ?>
                        <div class="alert alert-info">
                            Tidak ada data kampanye yang ditemukan.
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Gambar</th>
                                        <th>Judul</th>
                                        <th>Target</th>
                                        <th>Terkumpul</th>
                                        <th>Progress</th>
                                        <th>Status</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $no = $offset + 1; ?>
                                    <?php foreach ($kampanye_list as $kampanye): ?>
                                        <?php 
                                        $total_donasi = $kampanye->total_donasi ?? 0;
                                        $persentase = hitungPersentase($total_donasi, $kampanye->target_donasi);
                                        ?>
                                        <tr>
                                            <td><?= $no++ ?></td>
                                            <td>
                                                <img src="<?= SITE_URL ?>/assets/uploads/kampanye/<?= $kampanye->gambar ?? 'default.jpg' ?>" alt="<?= $kampanye->judul ?>" class="img-thumbnail" style="width: 80px; height: 50px; object-fit: cover;">
                                            </td>
                                            <td>
                                                <strong><?= $kampanye->judul ?></strong>
                                                <div class="small text-muted">
                                                    Dibuat oleh: <?= $kampanye->created_by_name ?>
                                                </div>
                                            </td>
                                            <td><?= rupiah($kampanye->target_donasi) ?></td>
                                            <td><?= rupiah($total_donasi) ?></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"><?= $persentase ?>%</span>
                                            </td>
                                            <td><?= getKampanyeStatusBadge($kampanye->status) ?></td>
                                            <td>
                                                <a href="<?= SITE_URL ?>/bendahara/kampanye/detail.php?id=<?= $kampanye->id ?>" class="btn btn-sm btn-info mb-1">
                                                    <i class="fas fa-eye"></i> Detail
                                                </a>
                                                
                                                <a href="<?= SITE_URL ?>/bendahara/donasi/index.php?kampanye_id=<?= $kampanye->id ?>" class="btn btn-sm btn-primary">
                                                    <i class="fas fa-donate"></i> Lihat Donasi
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                            <nav aria-label="Page navigation" class="mt-4">
                                <ul class="pagination justify-content-center">
                                    <?php if ($current_page > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?= $current_page - 1 ?>&status=<?= $status_filter ?>&search=<?= $search ?>">
                                                &laquo; Sebelumnya
                                            </a>
                                        </li>
                                    <?php else: ?>
                                        <li class="page-item disabled">
                                            <span class="page-link">&laquo; Sebelumnya</span>
                                        </li>
                                    <?php endif; ?>
                                    
                                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                        <li class="page-item <?= $i == $current_page ? 'active' : '' ?>">
                                            <a class="page-link" href="?page=<?= $i ?>&status=<?= $status_filter ?>&search=<?= $search ?>">
                                                <?= $i ?>
                                            </a>
                                        </li>
                                    <?php endfor; ?>
                                    
                                    <?php if ($current_page < $total_pages): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?= $current_page + 1 ?>&status=<?= $status_filter ?>&search=<?= $search ?>">
                                                Selanjutnya &raquo;
                                            </a>
                                        </li>
                                    <?php else: ?>
                                        <li class="page-item disabled">
                                            <span class="page-link">Selanjutnya &raquo;</span>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

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