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

if (!isset($_SESSION['user_id'])) {
    header('Location: /auth/login.php');
    exit;
}
$user_id = $_SESSION['user_id'];
$order_id = $_GET['order_id'] ?? null;
if (!$order_id) {
    header('Location: /dashboard.php');
    exit;
}

$order_stmt = $pdo->prepare("SELECT o.*, c.title FROM orders o JOIN courses c ON o.course_id = c.id WHERE o.id = ? AND o.user_id = ?");
$order_stmt->execute([$order_id, $user_id]);
$order = $order_stmt->fetch();
if (!$order) {
    die("Pesanan tidak ditemukan atau Anda tidak memiliki akses.");
}

$message = '';
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf();
    if (isset($_FILES['payment_proof']) && $_FILES['payment_proof']['error'] === UPLOAD_ERR_OK) {
        try {
            $file_name = basename($_FILES['payment_proof']['name']);
            $upload_dir = '../uploads/proofs/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0775, true);
            }
            $unique_name = uniqid() . '-' . $file_name;
            $dest_path = $upload_dir . $unique_name;
            if (move_uploaded_file($_FILES['payment_proof']['tmp_name'], $dest_path)) {
                $proof_path = 'uploads/proofs/' . $unique_name;
                $update_stmt = $pdo->prepare("UPDATE orders SET payment_proof = ?, status = 'awaiting_confirmation' WHERE id = ?");
                $update_stmt->execute([$proof_path, $order_id]);
                $message = "Bukti transfer berhasil diunggah! Mohon tunggu konfirmasi dari admin.";
                $order_stmt->execute([$order_id, $user_id]);
                $order = $order_stmt->fetch();
            } else {
                $error = "Gagal memindahkan file bukti transfer.";
            }
        } catch (Exception $e) {
            $error = "Terjadi kesalahan: " . $e->getMessage();
        }
    } else {
        $error = "Gagal mengunggah file atau file tidak dipilih.";
    }
}
?>
<main class="container mx-auto p-4 md:p-8">
    <div class="bg-white rounded-xl shadow-lg p-8 max-w-2xl mx-auto">
        <?php if ($order['status'] === 'awaiting_confirmation'): ?>
            <?php
                // Siapkan pesan untuk WhatsApp
                $wa_number = "62818123610";
                $wa_message = "Halo Admin,\n\nSaya " . e($_SESSION['username']) . " sudah mengunggah bukti transfer untuk kursus:\n*" . e($order['title']) . "*\n\nNomor Pesanan: #" . e($order['id']) . "\n\nMohon segera dikonfirmasi. Terima kasih.";
                $wa_link = "https://wa.me/" . $wa_number . "?text=" . urlencode($wa_message);
            ?>
            <div class="text-center">
                <h1 class="text-2xl font-bold text-green-600">Terima Kasih!</h1>
                <p class="mt-4 text-gray-700">Bukti pembayaran Anda untuk kursus "<?= e($order['title']) ?>" telah kami terima.</p>
                <p class="mt-2 text-gray-700">Admin akan segera melakukan verifikasi. Untuk mempercepat proses, Anda bisa mengirim notifikasi via WhatsApp.</p>
                
                <div class="mt-8 space-y-4">
                    <a href="<?= $wa_link ?>" target="_blank" class="block w-full text-center bg-green-500 text-white font-semibold py-3 rounded-lg hover:bg-green-600 transition-colors">
                        Kirim Konfirmasi via WhatsApp
                    </a>
                    <a href="/dashboard.php" class="block w-full text-center bg-gray-800 text-white font-semibold py-3 rounded-lg hover:bg-gray-900">
                        Kembali ke Dashboard
                    </a>
                </div>
            </div>
        <?php elseif ($order['status'] === 'pending'): ?>
            <h1 class="text-3xl font-bold text-gray-800 mb-6">Instruksi Pembayaran</h1>
            <?php if ($message): ?><div class="bg-green-100 p-4 rounded-lg mb-6 text-green-800"><?= e($message) ?></div><?php endif; ?>
            <?php if ($error): ?><div class="bg-red-100 p-4 rounded-lg mb-6 text-red-800"><?= e($error) ?></div><?php endif; ?>
            
            <p class="text-gray-700">Silakan selesaikan pembayaran untuk kursus "<?= e($order['title']) ?>".</p>
            <div class="my-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                <p class="text-gray-600">Total Pembayaran:</p>
                <p class="text-3xl font-bold text-blue-600">Rp <?= number_format($order['amount']) ?></p>
            </div>
            <div class="my-6 text-gray-700">
                <p class="font-semibold">Transfer ke rekening berikut:</p>
                <p>Bank: <strong class="text-gray-900">Bank BCA</strong></p>
                <p>Nomor Rekening: <strong class="text-gray-900">123-456-7890</strong></p>
                <p>Atas Nama: <strong class="text-gray-900">Nama Pemilik E-Course</strong></p>
            </div>
            <hr class="my-6">
            <h2 class="text-xl font-bold mb-4 text-gray-800">Unggah Bukti Transfer</h2>
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="<?= e(generate_csrf_token()); ?>">
                <input type="file" name="payment_proof" accept="image/png, image/jpeg, image/jpg" class="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100" required>
                <button type="submit" class="w-full mt-4 px-6 py-3 font-semibold text-white bg-blue-500 rounded-lg hover:bg-blue-600">Saya Sudah Bayar</button>
            </form>
        <?php else: // Status completed, rejected, dll. ?>
             <div class="text-center">
                <h1 class="text-2xl font-bold text-gray-800">Status Pesanan: <?= e(ucfirst($order['status'])) ?></h1>
                <p class="mt-4 text-gray-700">Anda sudah menyelesaikan proses untuk pesanan ini.</p>
                <a href="/dashboard.php" class="inline-block mt-8 px-6 py-3 font-semibold text-white bg-gray-800 rounded-lg">Kembali ke Dashboard</a>
            </div>
        <?php endif; ?>
    </div>
</main>
<?php require_once '../includes/footer.php'; ?>