<?php
/* Template Name: TOEFL Login Page */
get_header();
?>

<div class="toefl-container" style="max-width:600px;margin:50px auto;padding:20px;border:1px solid #ccc;border-radius:10px;">
    <h2 style="text-align:center;">TOEFL Online Test</h2>

    <?php
    if (isset($_POST['signup'])) {
        $name = sanitize_text_field($_POST['name']);
        $email = sanitize_email($_POST['email']);
        $address = sanitize_text_field($_POST['address']);

        if (!email_exists($email)) {
            $random_password = wp_generate_password(12, false);
            $user_id = wp_create_user($email, $random_password, $email);
            wp_update_user([
                'ID' => $user_id,
                'display_name' => $name,
                'nickname' => $name,
                'description' => $address
            ]);
            echo '<p style="color:green;">Akun berhasil dibuat. Silakan login menggunakan nama dan email Anda.</p>';
        } else {
            echo '<p style="color:red;">Email sudah terdaftar. Silakan login.</p>';
        }
    }

    if (isset($_POST['login'])) {
        $email = sanitize_email($_POST['email']);
        $name = sanitize_text_field($_POST['name']);
        $user = get_user_by('email', $email);

        if ($user && $user->display_name === $name) {
            wp_set_current_user($user->ID);
            wp_set_auth_cookie($user->ID);
            echo '<script>window.location.href="' . site_url('/panduan-test/') . '";</script>';
        } else {
            echo '<p style="color:red;">Nama atau email salah.</p>';
        }
    }
    ?>

    <div style="margin-top:30px;">
        <h3>Sign Up</h3>
        <form method="post">
            <label>Nama Lengkap</label><br>
            <input type="text" name="name" required style="width:100%;padding:8px;"><br><br>
            <label>Email</label><br>
            <input type="email" name="email" required style="width:100%;padding:8px;"><br><br>
            <label>Alamat</label><br>
            <input type="text" name="address" required style="width:100%;padding:8px;"><br><br>
            <button type="submit" name="signup" style="padding:10px 20px;">Sign Up</button>
        </form>
    </div>

    <hr style="margin:40px 0;">

    <div>
        <h3>Login</h3>
        <form method="post">
            <label>Nama Lengkap</label><br>
            <input type="text" name="name" required style="width:100%;padding:8px;"><br><br>
            <label>Email</label><br>
            <input type="email" name="email" required style="width:100%;padding:8px;"><br><br>
            <button type="submit" name="login" style="padding:10px 20px;">Login</button>
        </form>
    </div>
</div>

<?php get_footer(); ?>
Scroll to Top