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

// Koneksi database
$db = dbConnect();

// Handle aksi delete jika ada
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = $_GET['id'];
    
    // Cek apakah kampanye memiliki donasi
    $db->query("SELECT COUNT(*) as jumlah FROM donasi WHERE kampanye_id = :id");
    $db->bind(':id', $id);
    $result = $db->single();
    
    if ($result->jumlah > 0) {
        setFlash('kampanye', 'Kampanye tidak dapat dihapus karena memiliki donasi', 'danger');
    } else {
        // Cek apakah kampanye masih menunggu persetujuan (hanya yang menunggu yang boleh dihapus)
        $db->query("SELECT status FROM kampanye WHERE id = :id");
        $db->bind(':id', $id);
        $kampanye = $db->single();
        
        if ($kampanye && $kampanye->status === 'menunggu_persetujuan') {
            // Ambil informasi gambar kampanye sebelum dihapus
            $db->query("SELECT gambar FROM kampanye WHERE id = :id");
            $db->bind(':id', $id);
            $gambar_info = $db->single();
            
            // Hapus kampanye dari database
            $db->query("DELETE FROM kampanye WHERE id = :id");
            $db->bind(':id', $id);
            
            if ($db->execute()) {
                // Hapus file gambar jika ada
                if ($gambar_info && $gambar_info->gambar && $gambar_info->gambar != 'default.jpg') {
                    $gambar_path = UPLOAD_DIR . 'kampanye/' . $gambar_info->gambar;
                    if (file_exists($gambar_path)) {
                        unlink($gambar_path);
                    }
                }
                
                // Log aktivitas
                logActivity('Menghapus kampanye', 'kampanye', $id, 'Sekretaris menghapus kampanye dengan id: ' . $id);
                
                setFlash('kampanye', 'Kampanye berhasil dihapus', 'success');
            } else {
                setFlash('kampanye', 'Kampanye gagal dihapus', 'danger');
            }
        } else {
            setFlash('kampanye', 'Hanya kampanye yang menunggu persetujuan yang dapat dihapus', 'danger');
        }
    }
    
    // Redirect ke halaman kampanye
    header('Location: ' . SITE_URL . '/sekretaris/kampanye/index.php');
    exit;
}

// 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 OR deskripsi 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 kampanye
$query = "SELECT k.*, 
          (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,
          u1.nama_lengkap as created_by_name,
          u2.nama_lengkap as approved_by_name
          FROM kampanye k
          LEFT JOIN users u1 ON k.created_by = u1.id
          LEFT JOIN users u2 ON k.approved_by = u2.id
          WHERE 1=1";

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

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

$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 -->
                <?php require_once '../../includes/sidebar-sekretaris.php'; ?>


        <!-- 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">Manajemen Kampanye</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/sekretaris/kampanye/tambah.php" class="btn btn-sm btn-success">
                        <i class="fas fa-plus me-1"></i> Tambah Kampanye
                    </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-4"> -->
                            <!-- <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="aktif" <?= $status_filter == 'aktif' ? 'selected' : '' ?>>Aktif</option>
                                <option value="menunggu_persetujuan" <?= $status_filter == 'menunggu_persetujuan' ? 'selected' : '' ?>>Menunggu Persetujuan</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-3 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2">Filter</button>
                            <a href="<?= SITE_URL ?>/sekretaris/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>
                                <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</th>
                                    <th scope="col" width="10%">Terkumpul</th>
                                    <th scope="col" width="10%">Status</th>
                                    <th scope="col" width="15%">Info</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 oleh: <?= $kampanye->created_by_name ?>
                                                </div>
                                            </td>
                                            <td><?= rupiah($kampanye->target_donasi) ?></td>
                                            <td>
                                                <?= rupiah($total_donasi) ?>
                                                <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>
                                                <div class="small mt-1">
                                                    <span class="text-muted"><?= $persentase ?>%</span>
                                                    <span class="float-end text-muted"><?= $kampanye->jumlah_donatur ?? 0 ?> donatur</span>
                                                </div>
                                            </td>
                                            <td>
                                                <?php if ($kampanye->status == 'aktif'): ?>
                                                    <span class="badge bg-success">Aktif</span>
                                                <?php elseif ($kampanye->status == 'menunggu_persetujuan'): ?>
                                                    <span class="badge bg-warning text-dark">Menunggu</span>
                                                <?php elseif ($kampanye->status == 'selesai'): ?>
                                                    <span class="badge bg-primary">Selesai</span>
                                                <?php else: ?>
                                                    <span class="badge bg-danger">Dibatalkan</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <div class="small">
                                                    <div>Mulai: <?= date('d/m/Y', strtotime($kampanye->tanggal_mulai)) ?></div>
                                                    <div>Selesai: <?= date('d/m/Y', strtotime($kampanye->tanggal_selesai)) ?></div>
                                                    <?php if ($kampanye->approved_by): ?>
                                                        <div class="text-<?= $kampanye->status == 'aktif' ? 'success' : 'danger' ?> mt-1">
                                                            <?= $kampanye->status == 'aktif' ? 'Disetujui' : 'Ditolak' ?> oleh: <?= $kampanye->approved_by_name ?>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                            <td>
                                                <a href="<?= SITE_URL ?>/sekretaris/kampanye/edit.php?id=<?= $kampanye->id ?>" class="btn btn-sm btn-primary mb-1 w-100">
                                                    <i class="fas fa-edit"></i> Edit
                                                </a>
                                                <?php if ($kampanye->status == 'menunggu_persetujuan'): ?>
                                                    <a href="<?= SITE_URL ?>/sekretaris/kampanye/index.php?action=delete&id=<?= $kampanye->id ?>" class="btn btn-sm btn-danger w-100" onclick="return confirm('Yakin ingin menghapus kampanye ini?')">
                                                        <i class="fas fa-trash"></i> Hapus
                                                    </a>
                                                <?php else: ?>
                                                    <button type="button" class="btn btn-sm btn-secondary w-100" disabled data-bs-toggle="tooltip" data-bs-placement="top" title="Tidak dapat dihapus karena sudah diproses">
                                                        <i class="fas fa-lock"></i> Hapus
                                                    </button>
                                                <?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 ?>/sekretaris/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 ?>/sekretaris/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 ?>/sekretaris/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>

<!-- Aktifkan tooltip -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});
</script>

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