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

$user_id = $_SESSION['user_id'];
$db = dbConnect();

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

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

// Hitung total donasi user
$query_count = "SELECT COUNT(*) as total FROM donasi d JOIN kampanye k ON d.kampanye_id = k.id WHERE d.user_id = :user_id";
$params = [':user_id' => $user_id];

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

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

$db->query($query_count);
foreach ($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.*, k.judul as kampanye_judul 
          FROM donasi d 
          JOIN kampanye k ON d.kampanye_id = k.id 
          WHERE d.user_id = :user_id";

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

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

$query .= " ORDER BY d.created_at DESC LIMIT :offset, :limit";

$db->query($query);
foreach ($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();

// Statistik donasi
$db->query("SELECT 
            SUM(CASE WHEN status = 'diverifikasi' THEN jumlah ELSE 0 END) as total_diverifikasi,
            SUM(CASE WHEN status = 'menunggu' THEN jumlah ELSE 0 END) as total_menunggu,
            COUNT(CASE WHEN status = 'diverifikasi' THEN 1 END) as count_diverifikasi,
            COUNT(CASE WHEN status = 'menunggu' THEN 1 END) as count_menunggu,
            COUNT(CASE WHEN status = 'ditolak' THEN 1 END) as count_ditolak
            FROM donasi 
            WHERE user_id = :user_id");
$db->bind(':user_id', $user_id);
$stats = $db->single();

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

<!-- Sidebar & Content -->
<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 ?>/user/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 ?>/user/donasi/index.php">
                            <i class="fas fa-donate me-2"></i>
                            Donasi Saya
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/user/donasi/buat.php">
                            <i class="fas fa-hand-holding-heart me-2"></i>
                            Buat Donasi
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/user/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">Donasi Saya</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/user/donasi/buat.php" class="btn btn-sm btn-success">
                        <i class="fas fa-plus me-1"></i> Donasi Baru
                    </a>
                </div>
            </div>

            <?php flash(); ?>

            <!-- Statistik Donasi -->
            <div class="row dashboard-stats mb-4">
                <div class="col-md-4 mb-4">
                    <div class="card h-100">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center me-3">
                                    <i class="fas fa-check-circle"></i>
                                </div>
                                <div>
                                    <h5 class="card-title">Donasi Terverifikasi</h5>
                                    <h3 class="mb-0"><?= rupiah($stats->total_diverifikasi ?? 0) ?></h3>
                                    <small class="text-muted"><?= $stats->count_diverifikasi ?? 0 ?> donasi</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 mb-4">
                    <div class="card h-100">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center me-3">
                                    <i class="fas fa-clock"></i>
                                </div>
                                <div>
                                    <h5 class="card-title">Donasi Menunggu</h5>
                                    <h3 class="mb-0"><?= rupiah($stats->total_menunggu ?? 0) ?></h3>
                                    <small class="text-muted"><?= $stats->count_menunggu ?? 0 ?> donasi</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 mb-4">
                    <div class="card h-100">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center me-3">
                                    <i class="fas fa-times-circle"></i>
                                </div>
                                <div>
                                    <h5 class="card-title">Donasi Ditolak</h5>
                                    <h3 class="mb-0"><?= $stats->count_ditolak ?? 0 ?></h3>
                                    <small class="text-muted">donasi</small>
                                </div>
                            </div>
                        </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-6">
                            <label for="search" class="form-label">Cari</label>
                            <input type="text" class="form-control" id="search" name="search" placeholder="Cari kampanye atau keterangan..." 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="diverifikasi" <?= $status_filter == 'diverifikasi' ? 'selected' : '' ?>>Diverifikasi</option>
                                <option value="menunggu" <?= $status_filter == 'menunggu' ? 'selected' : '' ?>>Menunggu</option>
                                <option value="ditolak" <?= $status_filter == 'ditolak' ? 'selected' : '' ?>>Ditolak</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 ?>/user/donasi/index.php" class="btn btn-secondary">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="25%">Kampanye</th>
                                    <th scope="col" width="15%">Jumlah</th>
                                    <th scope="col" width="15%">Metode Pembayaran</th>
                                    <th scope="col" width="15%">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="7" class="text-center py-4">Belum ada riwayat donasi</td>
                                    </tr>
                                <?php else: ?>
                                    <?php $no = $offset + 1; ?>
                                    <?php foreach ($donasi_list as $donasi): ?>
                                        <tr>
                                            <th scope="row"><?= $no++ ?></th>
                                            <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>
                                                <small><?= date('d/m/Y H:i', strtotime($donasi->created_at)) ?></small>
                                            </td>
                                            <td>
                                                <a href="<?= SITE_URL ?>/user/donasi/detail.php?id=<?= $donasi->id ?>" class="btn btn-sm btn-primary mb-1 w-100" data-bs-toggle="tooltip" data-bs-placement="top" title="Detail">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                <?php if ($donasi->status == 'menunggu' && empty($donasi->bukti_transfer)): ?>
                                                    <a href="<?= SITE_URL ?>/user/donasi/upload-bukti.php?id=<?= $donasi->id ?>" class="btn btn-sm btn-warning w-100" data-bs-toggle="tooltip" data-bs-placement="top" title="Upload Bukti Transfer">
                                                        <i class="fas fa-upload"></i>
                                                    </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 ?>/user/donasi/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 ?>/user/donasi/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 ?>/user/donasi/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'; ?>