<script>
    function checkLogin() {
        if (typeof AndroidInterface !== "undefined" && typeof AndroidInterface.getData === "function") {
            let jsonData = AndroidInterface.getData();
            console.log("Raw data dari AndroidInterface:", jsonData);

            try {
                let data = JSON.parse(jsonData);
                console.log("Parsed JSON:", data);

                const token = data.token;
                const handphone = data.handphone;

                if (token && handphone) {
                    console.log("Mengirim ke verifyToken.php:", { token, handphone });

                    fetch('../verifyToken.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ token, handphone })
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(result => {
                        console.log("Hasil verifikasi:", result);

                        if (result && result.valid === true) {
                            console.log("Login valid, redirect ke page.php");
                            window.location.href = "https://agen.manjapro.net/";
                        } else {
                            console.warn("Token tidak valid atau data response tidak sesuai format.");
                        }
                    })
                    .catch(error => {
                        console.error("Gagal verifikasi token:", error);
                    });
                } else {
                    console.warn("Token atau handphone kosong:", data);
                }
            } catch (e) {
                console.error("Gagal parse JSON dari AndroidInterface:", e);
            }
        } else {
            console.warn("AndroidInterface tidak tersedia.");
            // window.location.href = "https://play.google.com/store/apps/details?id=com.bilspro.appbilspro";
        }
    }

    window.addEventListener("DOMContentLoaded", checkLogin);
</script>

<?php 
// include('../config/connect.php');

include "../config/connect.php"; 
include "../config/whatsapp_api.php"; 
include "../list_data/sweetalert.php"; 
include "../config/tanggal_indo.php";

$logo = (baseurl() == "https://agen.manjapro.net/") ? 'images/white_logo_manja.png' : 'images/white_logo.png';

// $logo = (baseurl() = "https://agen.manjapro.net/") ? 'images/white_logo.png' : 'images/white_logo_manja.png';
// $logo = 'images/white_logo.png';

// echo baseurl();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>Agen Hotspot</title>
    <!-- Google Font: Source Sans Pro -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="css/fontawesome-free/css/all.min.css">
    <link rel="stylesheet" href="https://bilspro.com/plugins/icheck-bootstrap/icheck-bootstrap.min.css">
    <link rel="stylesheet" href="https://bilspro.com/dist/css/adminlte.min.css">
    <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
</head>
<body style="zoom: 85%;">
    

<div class="container p-0" style="height: 100vh">
    <div class="card" style="height: 600px; background-color: #fca503; border-bottom-left-radius: 40px; border-bottom-right-radius: 40px;">
        <center>
            <img src="<?php echo $logo; ?>" alt="logo" width="150" style="margin-top: 80px; margin-bottom: 10px;">
            <h2 style="margin-bottom: 120px; color: white;"><b>Selamat Datang!</b></h2>
        </center>
        <div class="card" style="margin: 20px; border-radius: 10px;">
            <div class="card-body">
                <center>
                    <h4><b>Login Agen</b></h4><hr>
                    
                </center>
                <form method="post">
                    <div class="form-group">
                        <label>Nomor Handphone</label>
                        <input type="number" class="form-control form-control-lg" name="nohp" placeholder="Nomor Handphone" id="inputField" required>
                    </div>
                    <div class="form-group">
                        <label>Password</label>
                        <div class="input-group mb-4">
                            <input type="password" class="form-control form-control-lg" id="password" name="password" placeholder="Password" required>
                            <input type="hidden" id="deviceInfo" name="deviceInfo">
                            <div class="input-group-append">
                                <div class="input-group-text">
                                    <span class="fas fa-eye" id="toggle-password"></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <a href="lupa_password">Lupa Password ?</a>
                    <div style="margin: 30px;">
                        <input type="submit" class="btn btn-block btn-lg font-weight-medium auth-form-btn text-light text-bold" name="login" style="border-radius: 40px; background-color: #fca503;" value="LOGIN">
                    </div>
                </form>
            </div>
        </div>
        
<!--<button onclick="tampilkanNama()">Tampilkan Nama</button>-->
        <?php
            if (isset($_POST['login'])) {
                // Normalizing the phone number
                $handphone = preg_replace('/^0/', '62', $_POST['nohp']);
                if (substr($handphone, 0, 2) != '62') {
                    $handphone = '62' . $handphone; // Add country code if missing
                }
    
                try {
                    // Fetch user details
                    $stmt = $pdo->prepare("SELECT id, password, status FROM agen_voucher WHERE nomor_whatsapp = :handphone");
                    $stmt->bindParam(':handphone', $handphone, PDO::PARAM_STR);
                    $stmt->execute();
                    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
                    if ($user) {
                        if (password_verify($_POST['password'], $user['password'])) {
                            if ($user['status'] == "Aktif") {
                                session_start();
                                $_SESSION['agen'] = $user['id'];
    
                                // Buat dan simpan token
                                $token = createToken($user['id']);
                                
                                if (isset($_POST['deviceInfo'])) {
                                    // Pecah string berdasarkan baris baru
                                    $lines = explode("\r\n", $_POST['deviceInfo']);
                                    $deviceInfo = array();
                                
                                    // Proses setiap baris
                                    foreach ($lines as $line) {
                                        // Pisahkan berdasarkan ": "
                                        $parts = explode(": ", $line);
                                        if (count($parts) == 2) {
                                            $deviceInfo[$parts[0]] = $parts[1];
                                        }
                                    }
                                
                                    // Encode array ke JSON dalam satu baris
                                    $device_agen = json_encode($deviceInfo);
                                } else {
                                    // Jika tidak ada data deviceInfo
                                    $device_agen = 'NO DEVICE';
                                }
                                
                                // Update token di database
                                $stmt = $pdo->prepare("UPDATE agen_voucher SET token = :token, last_login = :last, device_agen = :device_agen WHERE id = :id");
                                $waktu = date('Y-m-d H:i:s');
                                $stmt->bindParam(':token', $token);
                                $stmt->bindParam(':last', $waktu);
                                $stmt->bindParam(':device_agen', $device_agen);
                                $stmt->bindParam(':id', $user['id']);
                                $stmt->execute();
                                
                                // Simpan token ke localStorage
                                echo "<script>
                                    const data = {
                                      token: '$token',
                                      handphone: '$handphone'
                                    };
                                    AndroidInterface.saveData(JSON.stringify(data));
                                </script>";
                                sweetAlert("Login Berhasil", "success", baseurl());
                            } else {
                                sweetAlert("Login Gagal.. Status Agen anda tidak aktif, silahkan hubungi admin", "error", baseurl());
                            }
                        } else {
                            sweetAlert("Login Gagal.. Username atau Password Tidak terdaftar", "error", baseurl());
                        }
                    } else {
                        sweetAlert("Login Gagal.. Username atau Password Tidak terdaftar", "error", baseurl());
                    }
                } catch (PDOException $e) {
                    sweetAlert("Login Gagal.. Terjadi kesalahan pada server: " . $e->getMessage(), "error", baseurl());
                }
            }
        ?>
        <div class="text-center" id="setmargin">
            <br>
            <p><i>Versi 2.1.1 @2025</i></p>
            
        </div>
    </div>
</div>
<!-- jQuery -->
<script src="https://bilspro.com/plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="https://bilspro.com/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="https://bilspro.com/dist/js/adminlte.min.js"></script>
<script type="text/javascript">
    // Fungsi untuk mengambil informasi perangkat dan mengisi field hidden pada form
    function fetchDeviceInfo() {
        if (window.Android) {
            var deviceInfo = Android.getDeviceInfo(); // Memanggil informasi perangkat dari Android
            console.log(deviceInfo); // Menampilkan info di konsol
            document.getElementById('deviceInfo').value = deviceInfo; // Mengisi field hidden dengan informasi perangkat
        } else {
            document.getElementById('deviceInfo').value = ""; // Jika Android tidak tersedia
        }
    }

    // Memanggil fetchDeviceInfo saat halaman dimuat
    window.onload = function() {
        fetchDeviceInfo();
    };
</script>
<script>
    document.getElementById('toggle-password').addEventListener('click', function() {
        var passwordInput = document.getElementById('password');
        var icon = this;
        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        } else {
            passwordInput.type = 'password';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        }
    });
</script>

<script>
    // Ambil semua elemen input dan div
    const inputFields = document.querySelectorAll('#inputField, #password');  // Menangani input dengan id inputField dan passwordField
    const setMarginDiv = document.getElementById('setmargin');

    // Simpan margin asli
    const originalPaddingBottom = getComputedStyle(setMarginDiv).paddingBottom;
    
    // Fungsi untuk menambah margin dan scroll ke bawah
    function handleFocus() {
        // Cek apakah paddingBottom sudah bertambah
        if (setMarginDiv.style.paddingBottom !== '300px') {
            // Tambah margin bawah pada <div> sebesar 300px
            setMarginDiv.style.paddingBottom = '300px';
    
            // Scroll ke bagian paling bawah halaman setelah margin diperbesar
            setTimeout(() => {
                window.scrollTo({
                    top: document.body.scrollHeight,
                    behavior: 'smooth' // Scroll dengan efek halus
                });
            }, 300); // Beri jeda 300ms untuk animasi margin selesai
        }
    }

    // Fungsi untuk mengembalikan margin ke semula
    function handleBlur() {
        // Kembalikan margin bawah ke nilai semula
        setMarginDiv.style.paddingBottom = originalPaddingBottom;
    }

    // Tambahkan event listener pada setiap elemen input
    inputFields.forEach(input => {
        input.addEventListener('focus', handleFocus);
        input.addEventListener('blur', handleBlur);
    });
</script>


</body>
</html>
