<?php
// File: pages/kampanye-detail.php
// Halaman detail kampanye
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once '../includes/header.php';

// Cek ID kampanye
if (!isset($_GET['id']) || empty($_GET['id'])) {
    setFlash('error', 'ID kampanye tidak valid', 'danger');
    redirect(SITE_URL . '/pages/kampanye.php');
    exit;
}

$kampanye_id = (int)$_GET['id'];

// Ambil data kampanye
$db = dbConnect();
$db->query("SELECT k.*, u.nama_lengkap as creator_name, u.foto_profil as creator_photo
            FROM kampanye k 
            JOIN users u ON k.created_by = u.id
            WHERE k.id = :id");
$db->bind(':id', $kampanye_id);
$kampanye = $db->single();

// Jika kampanye tidak ditemukan
if (!$kampanye) {
    setFlash('error', 'Kampanye tidak ditemukan', 'danger');
    redirect(SITE_URL . '/pages/kampanye.php');
    exit;
}

// Ambil total donasi dan jumlah donatur
$db->query("SELECT SUM(jumlah) as total_donasi, COUNT(id) as jumlah_donatur 
            FROM donasi 
            WHERE kampanye_id = :kampanye_id AND status = 'diverifikasi'");
$db->bind(':kampanye_id', $kampanye_id);
$donasi_info = $db->single();

$total_donasi = $donasi_info->total_donasi ?? 0;
$jumlah_donatur = $donasi_info->jumlah_donatur ?? 0;
$persentase = hitungPersentase($total_donasi, $kampanye->target_donasi);

// Ambil donasi terbaru
$db->query("SELECT d.*, u.nama_lengkap, u.foto_profil
            FROM donasi d
            JOIN users u ON d.user_id = u.id
            WHERE d.kampanye_id = :kampanye_id AND d.status = 'diverifikasi'
            ORDER BY d.created_at DESC
            LIMIT 5");
$db->bind(':kampanye_id', $kampanye_id);
$donasi_terbaru = $db->resultSet();

// Set page title
$pageTitle = $kampanye->judul;
?>

<!-- Kampanye Detail -->
<section class="py-5">
    <div class="container">
        <div class="row">
            <!-- Kampanye Info -->
            <div class="col-lg-8 mb-4 mb-lg-0">
                <div class="card border-0 shadow-sm rounded-3 overflow-hidden">
                    <img src="<?= SITE_URL ?>/assets/uploads/kampanye/<?= $kampanye->gambar ?>" class="card-img-top campaign-detail-img" alt="<?= $kampanye->judul ?>">
                    <div class="card-body p-4">
                        <h2 class="card-title fw-bold mb-3"><?= $kampanye->judul ?></h2>
                        
                        <div class="d-flex align-items-center mb-4">
                            <img src="<?= SITE_URL ?>/assets/uploads/profiles/<?= $kampanye->creator_photo ?>" class="rounded-circle me-2" alt="Creator" width="40" height="40">
                            <div>
                                <p class="mb-0 fw-bold">Dibuat oleh <?= $kampanye->creator_name ?></p>
                                <small class="text-muted">Dimulai pada <?= tanggal_indo($kampanye->tanggal_mulai, true) ?></small>
                            </div>
                        </div>
                        
                        <div class="campaign-description mb-4">
                            <?= nl2br($kampanye->deskripsi) ?>
                        </div>
                        
                        <div class="campaign-info bg-light p-3 rounded mb-4">
                            <div class="row text-center">
                                <div class="col-md-4 mb-3 mb-md-0">
                                    <h5 class="fw-bold mb-0"><?= rupiah($total_donasi) ?></h5>
                                    <small class="text-muted">dari target <?= rupiah($kampanye->target_donasi) ?></small>
                                </div>
                                <div class="col-md-4 mb-3 mb-md-0">
                                    <h5 class="fw-bold mb-0"><?= $jumlah_donatur ?></h5>
                                    <small class="text-muted">Donatur</small>
                                </div>
                                <div class="col-md-4">
                                    <?php if ($kampanye->status == 'aktif'): ?>
                                        <h5 class="fw-bold mb-0" id="kampanye-countdown" data-end="<?= $kampanye->tanggal_selesai ?>">
                                            <?= tanggal_indo($kampanye->tanggal_selesai) ?>
                                        </h5>
                                        <small class="text-muted">Sisa waktu</small>
                                    <?php else: ?>
                                        <h5 class="fw-bold mb-0">Kampanye Selesai</h5>
                                        <small class="text-muted">pada <?= tanggal_indo($kampanye->tanggal_selesai) ?></small>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="progress mb-3">
                            <div class="progress-bar" role="progressbar" style="width: <?= $persentase ?>%;" aria-valuenow="<?= $persentase ?>" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                        <p class="text-center mb-4"><?= $persentase ?>% dari target telah tercapai</p>
                        
                        <?php if ($kampanye->status == 'aktif'): ?>
                            <div class="d-grid">
                                <a href="<?= SITE_URL ?>/pages/donasi.php?id=<?= $kampanye->id ?>" class="btn btn-success btn-lg">Donasi Sekarang</a>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-info text-center">
                                Kampanye ini telah selesai. Terima kasih atas partisipasi Anda.
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Sidebar -->
            <div class="col-lg-4">
                <!-- Donasi Form Card (hanya tampil jika kampanye aktif) -->
                <?php if ($kampanye->status == 'aktif'): ?>
                    <div class="card border-0 shadow-sm rounded-3 mb-4">
                        <div class="card-header bg-success text-white">
                            <h5 class="card-title mb-0">Donasi Cepat</h5>
                        </div>
                        <div class="card-body p-4">
                            <form action="<?= SITE_URL ?>/pages/donasi.php" method="get">
                                <input type="hidden" name="id" value="<?= $kampanye->id ?>">
                                
                                <div class="mb-3">
                                    <label for="jumlah_cepat" class="form-label">Pilih Jumlah</label>
                                    <div class="btn-group d-flex" role="group" aria-label="Jumlah donasi">
                                        <button type="button" class="btn btn-outline-success quick-amount" data-amount="50000">50rb</button>
                                        <button type="button" class="btn btn-outline-success quick-amount" data-amount="100000">100rb</button>
                                        <button type="button" class="btn btn-outline-success quick-amount" data-amount="500000">500rb</button>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="custom_amount" class="form-label">Atau Masukkan Jumlah</label>
                                    <div class="input-group">
                                        <span class="input-group-text">Rp</span>
                                        <input type="text" class="form-control rupiah-input" id="custom_amount" name="jumlah" placeholder="Nominal donasi">
                                    </div>
                                </div>
                                
                                <div class="d-grid">
                                    <button type="submit" class="btn btn-success">Lanjutkan Donasi</button>
                                </div>
                            </form>
                        </div>
                    </div>
                <?php endif; ?>
                
                <!-- Latest Donation Card -->
                <div class="card border-0 shadow-sm rounded-3">
                    <div class="card-header bg-light">
                        <h5 class="card-title mb-0">Donasi Terbaru</h5>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($donasi_terbaru)): ?>
                            <div class="text-center p-4">
                                <p class="mb-0">Belum ada donasi untuk kampanye ini.</p>
                                <?php if ($kampanye->status == 'aktif'): ?>
                                    <p>Jadilah yang pertama berdonasi!</p>
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                            <ul class="list-group list-group-flush">
                                <?php foreach ($donasi_terbaru as $donasi): ?>
                                    <li class="list-group-item">
                                        <div class="d-flex align-items-center">
                                            <?php if ($donasi->is_anonim): ?>
                                                <div class="flex-shrink-0">
                                                    <div class="bg-secondary rounded-circle text-white d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                        <i class="fas fa-user"></i>
                                                    </div>
                                                </div>
                                                <div class="flex-grow-1 ms-3">
                                                    <p class="mb-0 fw-bold">Anonim</p>
                                            <?php else: ?>
                                                <div class="flex-shrink-0">
                                                    <img src="<?= SITE_URL ?>/assets/uploads/profiles/<?= $donasi->foto_profil ?>" class="rounded-circle" alt="Donatur" width="40" height="40">
                                                </div>
                                                <div class="flex-grow-1 ms-3">
                                                    <p class="mb-0 fw-bold"><?= $donasi->nama_lengkap ?></p>
                                            <?php endif; ?>
                                                <p class="mb-0"><?= rupiah($donasi->jumlah) ?></p>
                                                <small class="text-muted"><?= tanggal_indo(date('Y-m-d', strtotime($donasi->created_at))) ?></small>
                                            </div>
                                        </div>
                                        <?php if (!empty($donasi->keterangan)): ?>
                                            <div class="mt-2">
                                                <p class="small mb-0 fst-italic">"<?= $donasi->keterangan ?>"</p>
                                            </div>
                                        <?php endif; ?>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Share Section -->
<section class="py-4 bg-light">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-8 text-center">
                <h4 class="mb-3">Bagikan Kampanye Ini</h4>
                <p class="text-muted mb-4">Ajak teman dan keluarga untuk ikut berdonasi</p>
                <div class="d-flex justify-content-center">
                    <a href="https://www.facebook.com/sharer/sharer.php?u=<?= urlencode(SITE_URL . '/pages/kampanye-detail.php?id=' . $kampanye->id) ?>" target="_blank" class="btn btn-outline-primary mx-2">
                        <i class="fab fa-facebook-f me-2"></i> Facebook
                    </a>
                    <a href="https://twitter.com/intent/tweet?url=<?= urlencode(SITE_URL . '/pages/kampanye-detail.php?id=' . $kampanye->id) ?>&text=<?= urlencode($kampanye->judul) ?>" target="_blank" class="btn btn-outline-info mx-2">
                        <i class="fab fa-twitter me-2"></i> Twitter
                    </a>
                    <a href="https://api.whatsapp.com/send?text=<?= urlencode($kampanye->judul . ' - ' . SITE_URL . '/pages/kampanye-detail.php?id=' . $kampanye->id) ?>" target="_blank" class="btn btn-outline-success mx-2">
                        <i class="fab fa-whatsapp me-2"></i> WhatsApp
                    </a>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
    // Quick Amount Buttons
    document.querySelectorAll('.quick-amount').forEach(button => {
        button.addEventListener('click', function() {
            const amount = this.dataset.amount;
            document.getElementById('custom_amount').value = parseInt(amount).toLocaleString('id-ID');
            
            // Remove active class from all buttons
            document.querySelectorAll('.quick-amount').forEach(btn => {
                btn.classList.remove('active');
                btn.classList.remove('btn-success');
                btn.classList.add('btn-outline-success');
            });
            
            // Add active class to clicked button
            this.classList.add('active');
            this.classList.remove('btn-outline-success');
            this.classList.add('btn-success');
        });
    });
    
    // Countdown Timer
    const countdownElement = document.getElementById('kampanye-countdown');
    if (countdownElement) {
        const endDate = new Date(countdownElement.dataset.end).getTime();
        
        // Update every second
        const timer = setInterval(function() {
            const now = new Date().getTime();
            const distance = endDate - now;
            
            // Calculate days, hours, minutes, seconds
            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
            const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);
            
            // Display result
            countdownElement.innerHTML = `${days} hari ${hours} jam ${minutes} menit ${seconds} detik`;
            
            // Clear when finished
            if (distance < 0) {
                clearInterval(timer);
                countdownElement.innerHTML = "Kampanye Berakhir";
            }
        }, 1000);
    }
</script>

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