<script>
    // if (typeof AndroidInterface === "undefined" || typeof AndroidInterface.getData !== "function") {
    //     alert("Mohon maaf, layanan ini hanya dapat digunakan melalui aplikasi resmi. Silakan unduh aplikasi kami melalui Play Store untuk melanjutkan.");
    //     window.location.href = "https://play.google.com/store/apps/details?id=com.bilspro.appbilspro";
    //     return;
    // }
    if (typeof AndroidInterface !== "undefined" && typeof AndroidInterface.getData === "function") {
    } else {
            alert("Mohon maaf, layanan ini hanya dapat digunakan melalui aplikasi resmi. Silakan unduh aplikasi kami melalui Play Store untuk melanjutkan.");
            window.location.href = "https://play.google.com/store/apps/details?id=com.bilspro.appbilspro";
            // window.location.href = "market://details?id=com.bilspro.appbilspro";
        }
    // function checkLogin() {
    //     if (typeof AndroidInterface !== "undefined" && typeof AndroidInterface.getData === "function") {
    //         const jsonData = AndroidInterface.getData();
    //         console.log("Raw data dari AndroidInterface:", jsonData);
    
    //         try {
    //             const 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 => response.json())
    //                 .then(result => {
    //                     console.log("Hasil verifikasi:", result);
    //                     if (result.valid) {
    //                         console.log("Login valid: userId = " + result.userId);
    //                         // window.location.href = "page.php";
    //                     } else {
    //                         console.warn("Token tidak valid.");
    //                     }
    //                 })
    //                 .catch(error => {
    //                     console.error('Gagal verifikasi token:', error);
    //                 });
    //             } else {
    //                 console.warn("Token atau handphone kosong:", data);
    //             }
    //         } catch (e) {
    //             console.error("Gagal parse JSON:", e);
    //         }
    //     } else {
    //         console.warn("AndroidInterface tidak tersedia.");
    //     }
    // }
    
    // window.addEventListener("DOMContentLoaded", checkLogin);
</script>

<script>
function tampilkanNama() {
    if (typeof AndroidInterface !== "undefined" && typeof AndroidInterface.getData === "function") {
        const jsonData = AndroidInterface.getData();
        try {
            const dataObj = JSON.parse(jsonData);
            const handphone = dataObj.handphone || "(tidak tersedia)";
            const token = dataObj.token || "(tidak tersedia)";
            alert("Token: " + token + "\nHandphone: " + handphone);
        } catch (e) {
            alert("Gagal membaca data JSON: " + e.message);
        }
    } else {
        alert("Fitur hanya tersedia di aplikasi Android.");
    }
}
</script>



<?php 

error_reporting(0);
ini_set('display_errors', 0);

session_start();

// print_r($_SESSION);
function createToken($userId) {
    $secretKey = 'TjpWb208PUR0tENqsv1B7GVkVWRML2hjSVN4QUs5V251cDFKWVpGQzJsUjBtZ2NCMzVKc1JZR1RVK2M9';

    // Payload
    $payload = [
        'userId' => $userId,
        'iat' => time(),
        'exp' => time() + (7 * 24 * 60 * 60)
    ];

    // Encode payload
    $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
    $base64Header = base64_encode($header);
    $base64Payload = base64_encode(json_encode($payload));
    
    // Signature
    $signature = hash_hmac('sha256', $base64Header . "." . $base64Payload, $secretKey, true);
    $base64Signature = base64_encode($signature);

    // Token
    return $base64Header . "." . $base64Payload . "." . $base64Signature;
}

// Redirect from index.php to the base URL
$requestUri = $_SERVER['REQUEST_URI'];
if (strpos($requestUri, 'index.php') !== false) {
    $newUrl = str_replace('index.php', '', $requestUri);
    header('Location: ' . rtrim($newUrl, '/') . '/');
    exit;
}

// Check if user is logged in
$isLoggedIn = isset($_SESSION['agen']);

// Get the URL path
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// Include the appropriate view based on session status and path
switch ($path) {
    case '/lupa_password':
        include 'autentikasi/forget_pass.php';
        break;

    default:
        if ($isLoggedIn) {
            include 'page.php';
        } else {
            include 'autentikasi/aut_akses.php';
            exit();
            // $token = isset($_SESSION['token']) ? $_SESSION['token'] : null;
            // if ($token) {
            //     $userId = verifyToken($token);
            //     if (!$userId) {
            //         include 'autentikasi/aut_akses.php';
            //         exit();
            //     }
            //     $_SESSION['agen'] = $userId;
            //     include "page.php";
            // } else {
            //     include 'autentikasi/aut_akses.php';
            //     exit();
            // }
        }
        break;
}

?>
