<?php
// admin/donasi/index.php
$pageTitle = 'Manajemen Donasi';
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 admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'admin') {
    // Redirect ke halaman login jika belum login atau bukan admin
    setFlash('login_required', 'Anda harus login sebagai admin 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'] : '';
$kampanye_filter = isset($_GET['kampanye_id']) ? $_GET['kampanye_id'] : '';
$search = isset($_GET['search']) ? $_GET['search'] : '';
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : '';

// Query untuk menghitung total donasi
$query_count = "SELECT COUNT(*) as total FROM donasi d
                JOIN users u ON d.user_id = u.id
                JOIN kampanye k ON d.kampanye_id = k.id
                WHERE 1=1";
$query_params = [];

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

if (!empty($kampanye_filter)) {
    $query_count .= " AND d.kampanye_id = :kampanye_id";
    $query_params[':kampanye_id'] = $kampanye_filter;
}

if (!empty($search)) {
    $query_count .= " AND (u.nama_lengkap LIKE :search OR u.email LIKE :search OR k.judul LIKE :search)";
    $query_params[':search'] = "%$search%";
}

if (!empty($start_date)) {
    $query_count .= " AND DATE(d.created_at) >= :start_date";
    $query_params[':start_date'] = $start_date;
}

if (!empty($end_date)) {
    $query_count .= " AND DATE(d.created_at) <= :end_date";
    $query_params[':end_date'] = $end_date;
}

$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 donasi
$query = "SELECT d.*, u.nama_lengkap as donatur_nama, k.judul as kampanye_judul 
         FROM donasi d
         JOIN users u ON d.user_id = u.id
         JOIN kampanye k ON d.kampanye_id = k.id
         WHERE 1=1";

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

if (!empty($kampanye_filter)) {
    $query .= " AND d.kampanye_id = :kampanye_id";
}

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

if (!empty($start_date)) {
    $query .= " AND DATE(d.created_at) >= :start_date";
}

if (!empty($end_date)) {
    $query .= " AND DATE(d.created_at) <= :end_date";
}

$query .= " ORDER BY d.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);
$donasi_list = $db->resultSet();

// Ambil daftar kampanye untuk filter
$db->query("SELECT id, judul FROM kampanye ORDER BY judul ASC");
$kampanye_options = $db->resultSet();

// Total donasi berdasarkan filter
$query_total = "SELECT SUM(d.jumlah) as total_amount FROM donasi d 
               JOIN users u ON d.user_id = u.id
               JOIN kampanye k ON d.kampanye_id = k.id
               WHERE d.status = 'diverifikasi'";

$query_params_total = [];

if (!empty($kampanye_filter)) {
    $query_total .= " AND d.kampanye_id = :kampanye_id";
    $query_params_total[':kampanye_id'] = $kampanye_filter;
}

if (!empty($search)) {
    $query_total .= " AND (u.nama_lengkap LIKE :search OR u.email LIKE :search OR k.judul LIKE :search)";
    $query_params_total[':search'] = "%$search%";
}

if (!empty($start_date)) {
    $query_total .= " AND DATE(d.created_at) >= :start_date";
    $query_params_total[':start_date'] = $start_date;
}

if (!empty($end_date)) {
    $query_total .= " AND DATE(d.created_at) <= :end_date";
    $query_params_total[':end_date'] = $end_date;
}

$db->query($query_total);
foreach ($query_params_total as $param => $value) {
    $db->bind($param, $value);
}
$total_donasi_filtered = $db->single();
$total_donasi_amount = $total_donasi_filtered->total_amount ?? 0;

// Include header admin
require_once '../../includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar Admin -->
        <?php require_once '../../includes/sidebar-admin.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 Donasi</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <div class="btn-group me-2">
                        <a href="<?= SITE_URL ?>/admin/donasi/laporan.php" class="btn btn-sm btn-outline-secondary">
                            <i class="fas fa-file-pdf me-1"></i> Laporan
                        </a>
                    </div>
                </div>
            </div>

            <?php flash(); ?>

            <!-- Summary Card -->
            <div class="card mb-4 bg-light">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 text-center">
                            <h5 class="mb-0">Total Donasi (Terverifikasi)</h5>
                            <h3 class="text-success"><?= rupiah($total_donasi_amount) ?></h3>
                        </div>
                        <div class="col-md-4 text-center border-start border-end">
                            <h5 class="mb-0">Jumlah Transaksi</h5>
                            <h3><?= number_format($total_rows) ?></h3>
                        </div>
                        <div class="col-md-4 text-center">
                            <?php
                            // Hitung total menunggu verifikasi
                            $db->query("SELECT COUNT(*) as count FROM donasi WHERE status = 'menunggu'");
                            $menunggu = $db->single()->count;
                            ?>
                            <h5 class="mb-0">Menunggu Verifikasi</h5>
                            <h3 class="text-warning"><?= number_format($menunggu) ?></h3>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Filter & Search -->
            <div class="card mb-4">
                <div class="card-body">
                    <form action="" method="get" class="row g-3">
                        <div class="col-md-3">
                            <label for="search" class="form-label">Cari</label>
                            <input type="text" class="form-control" id="search" name="search" placeholder="Cari donatur atau kampanye..." value="<?= $search ?>">
                        </div>
                        <div class="col-md-3">
                            <label for="kampanye_id" class="form-label">Kampanye</label>
                            <select class="form-select" id="kampanye_id" name="kampanye_id">
                                <option value="">Semua Kampanye</option>
                                <?php foreach ($kampanye_options as $kampanye): ?>
                                    <option value="<?= $kampanye->id ?>" <?= $kampanye_filter == $kampanye->id ? 'selected' : '' ?>><?= $kampanye->judul ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-select" id="status" name="status">
                                <option value="">Semua Status</option>
                                <option value="menunggu" <?= $status_filter == 'menunggu' ? 'selected' : '' ?>>Menunggu</option>
                                <option value="diverifikasi" <?= $status_filter == 'diverifikasi' ? 'selected' : '' ?>>Diverifikasi</option>
                                <option value="ditolak" <?= $status_filter == 'ditolak' ? 'selected' : '' ?>>Ditolak</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="start_date" class="form-label">Dari Tanggal</label>
                            <input type="date" class="form-control" id="start_date" name="start_date" value="<?= $start_date ?>">
                        </div>
                        <div class="col-md-2">
                            <label for="end_date" class="form-label">Sampai Tanggal</label>
                            <input type="date" class="form-control" id="end_date" name="end_date" value="<?= $end_date ?>">
                        </div>
                        <div class="col-md-12">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search me-1"></i> Filter
                            </button>
                            <a href="<?= SITE_URL ?>/admin/donasi/index.php" class="btn btn-secondary">
                                <i class="fas fa-sync-alt me-1"></i> Reset
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Tabel Donasi -->
            <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%">Donatur</th>
                                    <th scope="col" width="20%">Kampanye</th>
                                    <th scope="col" width="15%">Jumlah</th>
                                    <th scope="col" width="10%">Metode</th>
                                    <th scope="col" width="10%">Status</th>
                                    <th scope="col" width="15%">Tanggal</th>
                                    <th scope="col" width="10%">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($donasi_list)): ?>
                                    <tr>
                                        <td colspan="8" class="text-center py-4">Tidak ada data donasi</td>
                                    </tr>
                                <?php else: ?>
                                    <?php $no = $offset + 1; ?>
                                    <?php foreach ($donasi_list as $donasi): ?>
                                        <tr>
                                            <th scope="row"><?= $no++ ?></th>
                                            <td>
                                                <?= $donasi->is_anonim ? '<span class="badge bg-secondary">Anonim</span>' : $donasi->donatur_nama ?>
                                            </td>
                                            <td><?= $donasi->kampanye_judul ?></td>
                                            <td><?= rupiah($donasi->jumlah) ?></td>
                                            <td><?= ucfirst($donasi->metode_pembayaran) ?></td>
                                            <td>
                                                <?php if ($donasi->status == 'menunggu'): ?>
                                                    <span class="badge bg-warning text-dark">Menunggu</span>
                                                <?php elseif ($donasi->status == 'diverifikasi'): ?>
                                                    <span class="badge bg-success">Diverifikasi</span>
                                                <?php else: ?>
                                                    <span class="badge bg-danger">Ditolak</span>
                                                <?php endif; ?>
                                            </td>
                                            <td><?= date('d/m/Y H:i', strtotime($donasi->created_at)) ?></td>
                                            <td>
                                                <a href="<?= SITE_URL ?>/admin/donasi/detail.php?id=<?= $donasi->id ?>" class="btn btn-sm btn-primary w-100">
                                                    <i class="fas fa-eye"></i> Detail
                                                </a>
                                            </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 ?>/admin/donasi/index.php?page=<?= (int)$current_page - 1 ?>
<?= !empty($status_filter) ? '&status=' . $status_filter : '' ?><?= !empty($kampanye_filter) ? '&kampanye_id=' . $kampanye_filter : '' ?><?= !empty($search) ? '&search=' . $search : '' ?><?= !empty($start_date) ? '&start_date=' . $start_date : '' ?><?= !empty($end_date) ? '&end_date=' . $end_date : '' ?>">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 ?>/admin/donasi/index.php?page=<?= $i ?><?= !empty($status_filter) ? '&status=' . $status_filter : '' ?><?= !empty($kampanye_filter) ? '&kampanye_id=' . $kampanye_filter : '' ?><?= !empty($search) ? '&search=' . $search : '' ?><?= !empty($start_date) ? '&start_date=' . $start_date : '' ?><?= !empty($end_date) ? '&end_date=' . $end_date : '' ?>"><?= $i ?></a>
                                    </li>
                                <?php endfor; ?>
                                
                                <li class="page-item <?= ($current_page >= $total_pages) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="<?= SITE_URL ?>/admin/donasi/index.php?page=<?= (int)$current_page + 1 ?><?= !empty($status_filter) ? '&status=' . $status_filter : '' ?><?= !empty($kampanye_filter) ? '&kampanye_id=' . $kampanye_filter : '' ?><?= !empty($search) ? '&search=' . $search : '' ?><?= !empty($start_date) ? '&start_date=' . $start_date : '' ?><?= !empty($end_date) ? '&end_date=' . $end_date : '' ?>">Next</a>
                                </li>
                            </ul>
                        </nav>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

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