<?php
// user/donasi/upload-bukti.php
$pageTitle = 'Upload Bukti Transfer';
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();

// Cek apakah ada ID donasi
if (!isset($_GET['id']) || empty($_GET['id'])) {
    setFlash('donasi', 'ID donasi tidak valid', 'danger');
    header('Location: ' . SITE_URL . '/user/donasi/index.php');
    exit;
}

$id = $_GET['id'];

// Ambil data donasi
$db->query("SELECT d.*, k.judul as kampanye_judul 
           FROM donasi d 
           JOIN kampanye k ON d.kampanye_id = k.id 
           WHERE d.id = :id AND d.user_id = :user_id");
$db->bind(':id', $id);
$db->bind(':user_id', $user_id);
$donasi = $db->single();

if (!$donasi) {
    setFlash('donasi', 'Donasi tidak ditemukan atau bukan milik Anda', 'danger');
    header('Location: ' . SITE_URL . '/user/donasi/index.php');
    exit;
}

// Jika donasi sudah diverifikasi atau ditolak, tidak bisa upload bukti lagi
if ($donasi->status != 'menunggu') {
    setFlash('donasi', 'Donasi ini sudah diverifikasi atau ditolak, tidak bisa upload bukti lagi', 'danger');
    header('Location: ' . SITE_URL . '/user/donasi/index.php');
    exit;
}

// Proses upload bukti transfer
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Cek apakah ada file yang diupload
    if (isset($_FILES['bukti_transfer']) && $_FILES['bukti_transfer']['error'] == 0) {
        // Direktori untuk menyimpan bukti transfer
        $upload_dir = UPLOAD_DIR . 'bukti_transfer/';
        
        // Pastikan folder ada
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        // Upload file
        $file = $_FILES['bukti_transfer'];
        $file_name = $file['name'];
        $file_tmp = $file['tmp_name'];
        $file_size = $file['size'];
        $file_error = $file['error'];
        
        // Cek ekstensi file
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $allowed_ext = ['jpg', 'jpeg', 'png', 'pdf'];
        
        if (in_array($file_ext, $allowed_ext)) {
            // Cek ukuran file (maks 2MB)
            if ($file_size <= 2097152) {
                // Generate nama file baru untuk menghindari duplikasi
                $new_file_name = 'bukti_transfer_' . $id . '_' . time() . '.' . $file_ext;
                $destination = $upload_dir . $new_file_name;
                
                // Cek jika ada bukti transfer lama, hapus file
                if (!empty($donasi->bukti_transfer)) {
                    $old_file = $upload_dir . $donasi->bukti_transfer;
                    if (file_exists($old_file)) {
                        unlink($old_file);
                    }
                }
                
                // Upload file
                if (move_uploaded_file($file_tmp, $destination)) {
                    // Update database
                    $db->query("UPDATE donasi SET bukti_transfer = :bukti_transfer WHERE id = :id");
                    $db->bind(':bukti_transfer', $new_file_name);
                    $db->bind(':id', $id);
                    
                    if ($db->execute()) {
                        // Log aktivitas
                        // logActivity('Upload bukti transfer', 'donasi', $id, 'User mengupload bukti transfer untuk donasi: ' . $donasi->kampanye_judul);
                        
                        // Buat notifikasi untuk bendahara
                        // $db->query("SELECT id FROM users WHERE role = 'bendahara'");
                        // $bendahara = $db->resultSet();
                        // foreach ($bendahara as $user) {
                            // createNotification(
                                // $user->id,
                                // 'Bukti Transfer Baru',
                                // 'Ada bukti transfer baru untuk donasi sebesar ' . rupiah($donasi->jumlah) . ' pada kampanye "' . $donasi->kampanye_judul . '"',
                                // SITE_URL . '/bendahara/donasi/detail.php?id=' . $id
                            // );
                        // }
                        
                        setFlash('donasi', 'Bukti transfer berhasil diupload. Donasi Anda akan segera diverifikasi oleh admin.', 'success');
                        header('Location: ' . SITE_URL . '/user/donasi/detail.php?id=' . $id);
                        exit;
                    } else {
                        setFlash('donasi', 'Gagal update database', 'danger');
                    }
                } else {
                    setFlash('donasi', 'Gagal upload file', 'danger');
                }
            } else {
                setFlash('donasi', 'Ukuran file terlalu besar (maks 2MB)', 'danger');
            }
        } else {
            setFlash('donasi', 'Ekstensi file tidak diizinkan (hanya jpg, jpeg, png, pdf)', 'danger');
        }
    } else {
        setFlash('donasi', 'Silakan pilih file bukti transfer', 'danger');
    }
}

// Ambil rekening bank yayasan
$db->query("SELECT rekening_bank FROM profil_yayasan LIMIT 1");
$yayasan = $db->single();
$rekening_bank = $yayasan ? nl2br($yayasan->rekening_bank) : 'Rekening bank belum tersedia';

// 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" 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">Upload Bukti Transfer</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/user/donasi/index.php" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-arrow-left me-1"></i> Kembali
                    </a>
                </div>
            </div>

            <?php flash(); ?>

            <div class="row">
                <!-- Form Upload -->
                <div class="col-md-7 mb-4">
                    <div class="card">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Form Upload Bukti Transfer</h5>
                        </div>
                        <div class="card-body">
                            <div class="alert alert-info mb-4">
                                <p class="mb-0"><i class="fas fa-info-circle me-2"></i> Silakan upload bukti transfer untuk melakukan verifikasi donasi Anda.</p>
                            </div>
                            
                            <form action="" method="post" enctype="multipart/form-data">
                                <div class="mb-3">
                                    <label for="bukti_transfer" class="form-label">Upload Bukti Transfer</label>
                                    <input type="file" class="form-control" id="bukti_transfer" name="bukti_transfer" accept=".jpg, .jpeg, .png, .pdf" required>
                                    <small class="text-muted">Format: JPG, JPEG, PNG, PDF (maks 2MB)</small>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Preview</label>
                                    <div class="border p-3 rounded text-center">
                                        <img id="preview_image" src="<?= SITE_URL ?>/assets/img/no-image.jpg" alt="Preview" class="img-fluid" style="max-height: 300px;">
                                    </div>
                                </div>
                                
                                <button type="submit" class="btn btn-success">Upload Bukti Transfer</button>
                            </form>
                        </div>
                    </div>
                </div>
                
                <!-- Detail Donasi -->
                <div class="col-md-5 mb-4">
                    <div class="card mb-4">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Detail Donasi</h5>
                        </div>
                        <div class="card-body">
                            <table class="table table-borderless">
                                <tr>
                                    <td width="40%">Kampanye</td>
                                    <td width="60%"><strong><?= $donasi->kampanye_judul ?></strong></td>
                                </tr>
                                <tr>
                                    <td>Jumlah Donasi</td>
                                    <td><strong><?= rupiah($donasi->jumlah) ?></strong></td>
                                </tr>
                                <tr>
                                    <td>Metode Pembayaran</td>
                                    <td><strong><?= ucfirst($donasi->metode_pembayaran) ?></strong></td>
                                </tr>
                                <tr>
                                    <td>Status</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>
                                </tr>
                                <tr>
                                    <td>Tanggal Donasi</td>
                                    <td><strong><?= date('d/m/Y H:i', strtotime($donasi->created_at)) ?></strong></td>
                                </tr>
                                <?php if (!empty($donasi->keterangan)): ?>
                                <tr>
                                    <td>Keterangan</td>
                                    <td><strong><?= $donasi->keterangan ?></strong></td>
                                </tr>
                                <?php endif; ?>
                            </table>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Informasi Rekening</h5>
                        </div>
                        <div class="card-body">
                            <div class="alert alert-warning">
                                <p class="mb-0"><i class="fas fa-exclamation-triangle me-2"></i> Silakan transfer donasi Anda ke rekening berikut:</p>
                            </div>
                            
                            <div class="bg-light p-3 rounded">
                                <?= $rekening_bank ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Preview gambar saat dipilih
    const buktiTransfer = document.getElementById('bukti_transfer');
    const previewImage = document.getElementById('preview_image');
    
    if (buktiTransfer && previewImage) {
        buktiTransfer.addEventListener('change', function() {
            const file = this.files[0];
            if (file) {
                const reader = new FileReader();
                
                reader.addEventListener('load', function() {
                    previewImage.setAttribute('src', this.result);
                });
                
                reader.readAsDataURL(file);
            } else {
                previewImage.setAttribute('src', '<?= SITE_URL ?>/assets/img/no-image.jpg');
            }
        });
    }
});
</script>

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