<?php
// ketua/kampanye/index.php
$pageTitle = 'Persetujuan 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 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']) ? $_GET['page'] : 1;
$limit = 10;
$offset = ($current_page - 1) * $limit;

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

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

if (!empty($status_filter)) {
    $query_count .= " AND status = :status";
    $query_params[':status'] = $status_filter;
}

if (!empty($search)) {
    $query_count .= " AND (judul LIKE :search_count OR deskripsi LIKE :search_count)"; // Menggunakan nama yang berbeda
    $query_params[':search_count'] = "%$search%";
}

// 1. Build query count
$query_count = "SELECT COUNT(*) as total FROM kampanye k WHERE 1=1";
$query_count_params = [];

if (!empty($status_filter)) {
    $query_count .= " AND k.status = :status";
    $query_count_params[':status'] = $status_filter;
}

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

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

// 3. Reset dan build ulang query data
$query_params = $query_count_params;

$query = "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";

if (!empty($status_filter)) {
    $query .= " AND k.status = :status";
}

if (!empty($search)) {
    $query .= " AND (k.judul LIKE :search_list OR k.deskripsi LIKE :search_list)";
}

$query .= " ORDER BY k.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);

$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 ?>/ketua/dashboard.php">
                            <i class="fas fa-tachometer-alt me-2"></i>
                            Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" 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" 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">Persetujuan Kampanye</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/ketua/dashboard.php" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-arrow-left me-1"></i> Kembali ke Dashboard
                    </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 atau deskripsi..." value="<?= $search ?>"> -->
                        <!-- </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="menunggu_persetujuan" < ?= $status_filter == 'menunggu_persetujuan' ? 'selected' : '' ?>>Menunggu Persetujuan</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> -->
                            <!-- </select> -->
                        <!-- </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 ?>/ketua/kampanye/index.php" class="btn btn-secondary">Reset</a> -->
                        <!-- </div> -->
                    <!-- </form> -->
                <!-- </div> -->
            <!-- </div> -->

            <!-- Tabel Kampanye -->
            <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="15%">Gambar</th>
                                    <th scope="col" width="20%">Judul</th>
                                    <th scope="col" width="15%">Target/Terkumpul</th>
                                    <th scope="col" width="15%">Periode</th>
                                    <th scope="col" width="10%">Status</th>
                                    <th scope="col" width="10%">Oleh</th>
                                    <th scope="col" width="10%">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($kampanye_list)): ?>
                                    <tr>
                                        <td colspan="8" class="text-center py-4">Tidak ada data kampanye</td>
                                    </tr>
                                <?php else: ?>
                                    <?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>
                                            <th scope="row"><?= $no++ ?></th>
                                            <td>
                                                <img src="<?= SITE_URL ?>/assets/uploads/kampanye/<?= $kampanye->gambar ?? 'default.jpg' ?>" 
                                                     class="img-thumbnail" alt="<?= $kampanye->judul ?>" 
                                                     style="width: 100px; height: 60px; object-fit: cover;">
                                            </td>
                                            <td>
                                                <strong><?= $kampanye->judul ?></strong>
                                                <div class="small text-muted">
                                                    Dibuat: <?= date('d/m/Y', strtotime($kampanye->created_at)) ?>
                                                </div>
                                            </td>
                                            <td>
                                                <div>Target: <?= rupiah($kampanye->target_donasi) ?></div>
                                                <div>Terkumpul: <?= rupiah($total_donasi) ?></div>
                                                <div class="progress mt-1" 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>
                                            </td>
                                            <td>
                                                <div>Mulai: <?= date('d/m/Y', strtotime($kampanye->tanggal_mulai)) ?></div>
                                                <div>Akhir: <?= date('d/m/Y', strtotime($kampanye->tanggal_selesai)) ?></div>
                                            </td>
                                            <td>
                                                <?= getKampanyeStatusBadge($kampanye->status) ?>
                                            </td>
                                            <td><?= $kampanye->created_by_name ?></td>
                                            <td>
                                                <a href="<?= SITE_URL ?>/ketua/kampanye/detail.php?id=<?= $kampanye->id ?>" 
                                                   class="btn btn-sm btn-primary w-100 mb-1">
                                                    <i class="fas fa-eye"></i> Detail
                                                </a>
                                                
                                                <?php if ($kampanye->status == 'menunggu_persetujuan'): ?>
                                                    <a href="<?= SITE_URL ?>/ketua/kampanye/detail.php?id=<?= $kampanye->id ?>&action=review" 
                                                       class="btn btn-sm btn-success w-100">
                                                        <i class="fas fa-check"></i> Review
                                                    </a>
                                                <?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/kampanye/index.php?page=<?= $current_page - 1 ?><?= !empty($status_filter) ? '&status=' . $status_filter : '' ?><?= !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/kampanye/index.php?page=<?= $i ?><?= !empty($status_filter) ? '&status=' . $status_filter : '' ?><?= !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/kampanye/index.php?page=<?= $current_page + 1 ?><?= !empty($status_filter) ? '&status=' . $status_filter : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>">Next</a>
                                </li>
                            </ul>
                        </nav>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

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