<?php
include('functions.php');
unset($_SESSION['username']);
unset($_SESSION['password']);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'];
    $username = $_POST['username'];
    $password = $_POST['password'];


 //-------------------API CALL------------------------------------//

    $jsonFilePath = __DIR__ . '/../urls/api_endpoints.json';
    $jsonData = file_get_contents($jsonFilePath);
    $endpoints = json_decode($jsonData, true);
    $url = $endpoints['index'];

//---------------------------ENDS HERE-----------------------------------------//


    $data = array("username" => $username, "password" => $password);

    $result = make_post_request($url, $data);
    $response = json_decode($result, true);

    if (isset($response['token'])) {
        $_SESSION['token'] = $response['token'];
        $_SESSION['username'] = $username;
        $_SESSION['password'] = $password; // Storing password is not recommended.
        $_SESSION['token_expiry'] = time() + 60; // Set token expiry time (10 minutes from now)

        $message = "Login successful! Token stored.";

        $_SESSION['acesslevel'] = '';



                      
//-------------------API CALL------------------------------------//

        $jsonFilePath = __DIR__ . '/../urls/api_endpoints.json';
        $jsonData = file_get_contents($jsonFilePath);
        $endpoints = json_decode($jsonData, true);
        $url_one = $endpoints['login']. $username . "/password?";
//---------------------------ENDS HERE-----------------------------------------//

        
        $result = make_get_request($url_one, ["Authorization: $token"]);
        $user_list = json_decode($result, true);

        foreach ($user_list as $user) {
            if ($user['pid'] == $username) {
                $_SESSION['acesslevel'] = $user['access_level'];
                break;
            }
        }

        $redirect_page = isset($_SESSION['redirect_page']) ? $_SESSION['redirect_page'] : 'dashboard.php';

// Debugging: Confirm before redirecting
        echo "Redirecting to: " . $redirect_page . "<br>";
        echo "Token Expiry before redirect: " . $_SESSION['token_expiry'] . "<br>";
        echo "Current Time before redirect: " . time() . "<br>";

// Then perform the redirect
        header("Location: $redirect_page");
        exit;


    } else {
        $message = "Login failed!";
    }
}
?>
