<!doctype html>
<?php
// MUST CHANGE FOR HOSTING OR LOCAL DEVELOPMENT
include_once __DIR__ . '/../config/root_path.php';

$token = $_GET['token'] ?? '';
?>
<html>

<head>
    <meta charset="utf-8">
    <title>Verifikasi Email</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body class="d-flex justify-content-center align-items-center vh-100 bg-light">

    <div class="card p-4 text-center shadow-sm" style="max-width:420px;">
        <h4 class="mb-3">Verifikasi Email</h4>
        <p id="msg">Memproses verifikasi...</p>
    </div>

    <script>
        const token = <?= json_encode($token) ?>;
        const path = `${window.location.origin}${window.location.pathname.includes('/padel/') ? '/padel/' : '/'}`;

        // =========================
        // TOKEN EMPTY CHECK
        // =========================
        if (!token) {
            Swal.fire({
                icon: 'error',
                title: 'Token tidak ditemukan',
                text: 'Link verifikasi tidak valid atau sudah rusak.'
            }).then(() => {
                window.location.href = path;
            });
        } else {

            fetch(`../endpoints/verify.php?token=${encodeURIComponent(token)}`)
                .then(async res => {
                    let data;
                    try {
                        data = await res.json();
                    } catch (e) {
                        throw new Error('Response bukan JSON');
                    }
                    return data;
                })
                .then(r => {
                    if (r.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil',
                            text: r.message || 'Email berhasil diverifikasi'
                        }).then(() => {
                            window.location.href = path;
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal',
                            text: r.error || 'Verifikasi gagal'
                        }).then(() => {
                            window.location.href = path;
                        });
                    }
                })
                .catch(err => {
                    Swal.fire({
                        icon: 'error',
                        title: 'Terjadi Kesalahan',
                        text: err.message || 'Tidak dapat memproses verifikasi'
                    }).then(() => {
                        window.location.href = path;
                    });
                });
        }
    </script>

</body>

</html>