<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register Akun Baru</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    
    <link href='https://unpkg.com/boxicons@2.1.2/css/boxicons.min.css' rel='stylesheet'>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    
    <style>
        body {
            font-family: 'Poppins', sans-serif;
            background: white; /* Gradien hijau sebagai background */
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            padding: 20px;
            box-sizing: border-box;
        }

        .auth-container {
            background-color: #FFFFFF;
            border-radius: 15px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.2);
            padding: 40px;
            max-width: 450px; /* Sedikit lebih lebar untuk register */
            width: 100%;
            text-align: center;
            overflow: hidden; /* Penting untuk transisi */
        }

        .auth-container h2 {
            color: #333;
            margin-bottom: 30px;
            font-weight: 700;
            font-size: 28px;
        }

        .form-group {
            margin-bottom: 20px;
            text-align: left;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #555;
            font-size: 14px;
        }

        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 10px;
            font-size: 16px;
            color: #333;
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
            box-sizing: border-box;
        }
        .form-control:focus {
            border-color: #4dab25;
            outline: none;
            box-shadow: 0 0 0 0.25rem rgba(77, 171, 37, 0.25);
        }

        .submit-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #4dab25, #024d52);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s ease, transform 0.2s ease, box-shadow 0.3s ease;
            margin-top: 10px;
        }
        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0,0,0,0.2);
        }

        .link-text {
            margin-top: 20px;
            font-size: 14px;
            color: #777;
        }
        .link-text a {
            color: #024d52;
            text-decoration: none;
            font-weight: 600;
            transition: color 0.2s ease;
        }
        .link-text a:hover {
            color: #4dab25;
            text-decoration: underline;
        }

        /* OTP Styles */
        .otp-info {
            font-size: 14px;
            color: #555;
            margin-bottom: 20px;
        }
        .otp-resend {
            font-size: 13px;
            margin-top: 15px;
        }
        .otp-resend a {
            color: #024d52;
            text-decoration: none;
            font-weight: 600;
        }
        .otp-resend a:hover {
            color: #4dab25;
            text-decoration: underline;
        }
        .error-message, .success-message {
            margin-top: 15px;
            padding: 10px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
        }
        .error-message {
            background-color: #ffe6e6;
            color: #cc0000;
            border: 1px solid #ffb3b3;
        }
        .success-message {
            background-color: #e6ffe6;
            color: #008000;
            border: 1px solid #b3ffb3;
        }

        /* Hidden by default */
        .hidden {
            display: none;
        }

        /* Responsive adjustments */
        @media (max-width: 500px) {
            .auth-container {
                padding: 30px 25px;
                margin: 0 15px;
            }
            .auth-container h2 {
                font-size: 24px;
                margin-bottom: 25px;
            }
            .form-control {
                padding: 10px 12px;
                font-size: 15px;
            }
            .submit-btn {
                padding: 12px;
                font-size: 16px;
            }
            .link-text, .otp-info, .error-message, .success-message {
                font-size: 13px;
                margin-top: 15px;
            }
            .otp-resend {
                font-size: 12px;
            }
        }
    </style>
</head>
<body>
    <div class="auth-container">
        <h2 id="formTitle">Register</h2>

        <form id="registerFormStage1">
            <div class="form-group">
                <label for="fullName">Nama Lengkap</label>
                <input type="text" id="fullName" name="fullName" class="form-control" placeholder="Masukkan nama lengkap Anda" required>
            </div>
            <div class="form-group">
                <label for="emailOrUsername">Email atau Username</label>
                <input type="text" id="emailOrUsername" name="emailOrUsername" class="form-control" placeholder="Masukkan email atau username" required>
            </div>
            <div class="form-group">
                <label for="phoneNumber">Nomor Telepon (WhatsApp)</label>
                <input type="tel" id="phoneNumber" name="phoneNumber" class="form-control" placeholder="Cth: 6281234567890" required>
                <small class="form-text text-muted" style="font-size:12px;">Pastikan nomor ini terhubung ke WhatsApp.</small>
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" id="password" name="password" class="form-control" placeholder="Buat password" required>
            </div>
            <div class="form-group">
                <label for="confirmPassword">Konfirmasi Password</label>
                <input type="password" id="confirmPassword" name="confirmPassword" class="form-control" placeholder="Ketik ulang password" required>
            </div>
            
            <button type="submit" class="submit-btn" id="sendOtpRegisterBtn">Register & Kirim OTP</button>
            <div id="registerMessage1" class="message-area"></div>
        </form>

        <form id="registerFormStage2" class="hidden">
            <div class="otp-info" id="otpInstruction">
                Kode OTP telah dikirim ke nomor WhatsApp Anda. Mohon masukkan kode tersebut untuk menyelesaikan pendaftaran.
            </div>
            <div class="form-group">
                <label for="otpCode">Kode OTP</label>
                <input type="text" id="otpCode" name="otpCode" class="form-control" placeholder="Masukkan 6 digit kode OTP" maxlength="6" required>
            </div>
            <button type="submit" class="submit-btn" id="verifyOtpRegisterBtn">Verifikasi & Selesaikan Pendaftaran</button>
            <div class="otp-resend">
                Tidak menerima kode? <a href="#" id="resendOtpRegisterLink">Kirim Ulang OTP</a>
            </div>
            <div id="registerMessage2" class="message-area"></div>
        </form>

        <div class="link-text">
            Sudah punya akun? <a href="login.php">Login</a>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const registerFormStage1 = document.getElementById('registerFormStage1');
            const registerFormStage2 = document.getElementById('registerFormStage2');
            const sendOtpRegisterBtn = document.getElementById('sendOtpRegisterBtn');
            const verifyOtpRegisterBtn = document.getElementById('verifyOtpRegisterBtn');
            const resendOtpRegisterLink = document.getElementById('resendOtpRegisterLink');
            const otpInstruction = document.getElementById('otpInstruction');

            const fullNameInput = document.getElementById('fullName');
            const emailOrUsernameInput = document.getElementById('emailOrUsername');
            const phoneNumberInput = document.getElementById('phoneNumber');
            const passwordInput = document.getElementById('password');
            const confirmPasswordInput = document.getElementById('confirmPassword');
            const otpCodeInput = document.getElementById('otpCode');

            const registerMessage1 = document.getElementById('registerMessage1');
            const registerMessage2 = document.getElementById('registerMessage2');

            let userDataTemp = {}; // Menyimpan data pendaftaran sementara sebelum verifikasi OTP

            // Fungsi untuk menampilkan pesan (error/success)
            function showMessage(element, message, type) {
                element.innerHTML = message;
                element.className = 'message-area ' + (type === 'success' ? 'success-message' : 'error-message');
                element.classList.remove('hidden');
            }

            // Fungsi untuk menyembunyikan pesan
            function hideMessage(element) {
                element.innerHTML = '';
                element.className = 'message-area hidden';
            }

            // Tahap 1: Handle Pendaftaran Awal & Pengiriman OTP
            registerFormStage1.addEventListener('submit', function(e) {
                e.preventDefault();
                hideMessage(registerMessage1);
                sendOtpRegisterBtn.disabled = true;
                sendOtpRegisterBtn.textContent = 'Memproses...';

                // Validasi Password Match
                if (passwordInput.value !== confirmPasswordInput.value) {
                    showMessage(registerMessage1, 'Password dan Konfirmasi Password tidak cocok.', 'error');
                    sendOtpRegisterBtn.disabled = false;
                    sendOtpRegisterBtn.textContent = 'Register & Kirim OTP';
                    return;
                }

                // Simpan data form sementara
                userDataTemp = {
                    fullName: fullNameInput.value,
                    emailOrUsername: emailOrUsernameInput.value,
                    phoneNumber: phoneNumberInput.value,
                    password: passwordInput.value,
                    confirmPassword: confirmPasswordInput.value
                };

                // --- Panggilan API Backend untuk Pendaftaran Awal & Pengiriman OTP ---
                fetch('../api/register_initiate_otp.php', { // Sesuaikan path jika berbeda
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(userDataTemp)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        registerFormStage1.classList.add('hidden');
                        registerFormStage2.classList.remove('hidden');
                        otpInstruction.textContent = `Kode OTP telah dikirim ke nomor WhatsApp ${userDataTemp.phoneNumber}. Mohon masukkan kode tersebut untuk menyelesaikan pendaftaran.`;
                        showMessage(registerMessage2, data.message || 'OTP berhasil dikirim. Silakan cek WhatsApp Anda.', 'success');
                    } else {
                        showMessage(registerMessage1, data.message || 'Pendaftaran gagal. Silakan coba lagi.', 'error');
                    }
                    sendOtpRegisterBtn.disabled = false;
                    sendOtpRegisterBtn.textContent = 'Register & Kirim OTP';
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage(registerMessage1, 'Terjadi kesalahan jaringan atau server. Coba lagi.', 'error');
                    sendOtpRegisterBtn.disabled = false;
                    sendOtpRegisterBtn.textContent = 'Register & Kirim OTP';
                });
            });

            // Tahap 2: Handle Verifikasi OTP & Finalisasi Pendaftaran
            registerFormStage2.addEventListener('submit', function(e) {
                e.preventDefault();
                hideMessage(registerMessage2);
                verifyOtpRegisterBtn.disabled = true;
                verifyOtpRegisterBtn.textContent = 'Memverifikasi...';

                const otpCode = otpCodeInput.value;

                // Gabungkan data pendaftaran sementara dengan OTP untuk dikirim ke backend
                const finalRegistrationData = {
                    emailOrUsername: userDataTemp.emailOrUsername, // Penting: Kirim identifier yang sama
                    otpCode: otpCode
                };

                // --- Panggilan API Backend untuk Verifikasi OTP & Finalisasi Register ---
                fetch('../api/register_verify_otp.php', { // Sesuaikan path jika berbeda
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(finalRegistrationData)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMessage(registerMessage2, data.message || 'Pendaftaran berhasil! Anda akan dialihkan ke halaman login.', 'success');
                        setTimeout(() => {
                            window.location.href = 'login.php'; // Arahkan ke halaman login setelah sukses
                        }, 2000);
                    } else {
                        showMessage(registerMessage2, data.message || 'Verifikasi OTP gagal. Kode tidak valid atau kedaluwarsa.', 'error');
                        verifyOtpRegisterBtn.disabled = false;
                        verifyOtpRegisterBtn.textContent = 'Verifikasi & Selesaikan Pendaftaran';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage(registerMessage2, 'Terjadi kesalahan jaringan atau server. Coba lagi.', 'error');
                    verifyOtpRegisterBtn.disabled = false;
                    verifyOtpRegisterBtn.textContent = 'Verifikasi & Selesaikan Pendaftaran';
                });
            });

            // Kirim Ulang OTP
            resendOtpRegisterLink.addEventListener('click', function(e) {
                e.preventDefault();
                hideMessage(registerMessage2);
                otpCodeInput.value = '';
                resendOtpRegisterLink.style.pointerEvents = 'none';
                resendOtpRegisterLink.textContent = 'Mengirim ulang...';

                // --- Panggilan API Backend untuk Kirim Ulang OTP ---
                fetch('../api/resend_otp_register.php', { // Sesuaikan path jika berbeda
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ phoneNumber: userDataTemp.phoneNumber }) // Kirim nomor HP untuk resend
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMessage(registerMessage2, data.message || 'OTP baru berhasil dikirim. Silakan cek WhatsApp Anda.', 'success');
                    } else {
                        showMessage(registerMessage2, data.message || 'Gagal mengirim ulang OTP. Silakan coba lagi.', 'error');
                    }
                    resendOtpRegisterLink.style.pointerEvents = 'auto';
                    resendOtpRegisterLink.textContent = 'Kirim Ulang OTP';
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage(registerMessage2, 'Terjadi kesalahan jaringan atau server saat mengirim ulang. Coba lagi.', 'error');
                    resendOtpRegisterLink.style.pointerEvents = 'auto';
                    resendOtpRegisterLink.textContent = 'Kirim Ulang OTP';
                });
            });
        });
    </script>
</body>
</html>