<?php

namespace Saireh\Payroll;

use Exception;
use Saireh\Payroll\CurlRequest;

class OAuthToken
{
    private CurlRequest $request;
    private $payroll_client_id;
    private $payroll_client_secret;
    private $payroll_resource;

    function __construct($environment, CurlRequest $request)
    {
        if ($environment == "dev" || $environment == "qa") {
            $environment = "qa";
        } else {
            $environment = "prod";
        }

        $this->request = $request;
        $this->payroll_client_id = getenv("PAYROLL_CLIENT_ID");
        $this->payroll_client_secret = getenv("PAYROLL_CLIENT_SECRET");
        $this->payroll_resource = "urn:sap_payroll_api:resource:pcf_api:$environment";
    }

    public static function url($environment)
    {
        if ($environment === 'prod') {
            return 'https://corp.sts.ford.com/';
        } elseif ($environment === 'dev' || $environment === 'qa') {
            return 'https://corpqa.sts.ford.com/';
        } else {
            throw new \InvalidArgumentException("Environment not valid: $environment");
        }
    }


    function max_time_passed($nombreVariable, $tiempoMaximoSegundos)
    {
        // Iniciar sesión si no está iniciada
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }

        // Verificar si la variable de sesión existe y si se ha establecido un tiempo
        if (isset($_SESSION[$nombreVariable]) && isset($_SESSION[$nombreVariable . '_time'])) {
            // Calcular el tiempo transcurrido desde la última actualización de la variable de sesión
            $tiempoTranscurrido = time() - $_SESSION[$nombreVariable . '_time'];

            // Devolver verdadero si ha pasado más tiempo del especificado
            return ($tiempoTranscurrido > $tiempoMaximoSegundos);
        }
        $_SESSION[$nombreVariable . '_time'] = time();
        // Devolver verdadero si la variable de sesión no está establecida
        return true;
    }

    function get_baerer_token($environment)
    {
        $data = array(
            'grant_type' => 'client_credentials',
            'client_id' => $this->payroll_client_id,
            'client_secret' => $this->payroll_client_secret,
            'resource' => $this->payroll_resource,
        );

        $curl_session_args = array(
            CURLOPT_URL => OAuthToken::url($environment) . "adfs/oauth2/token",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => http_build_query($data),
        );
        try {
            //code...
            $response = $this->request->post($curl_session_args);
            $token_response = json_decode($response[0], true);
            if ($this->max_time_passed("payroll_api_token", $token_response["expires_in"])) {
                $_SESSION["payroll_api_token"] = $token_response["access_token"];
            }


            return $_SESSION["payroll_api_token"];
        } catch (Exception $th) {
            echo "Fatal error trying to reach Oauth API {$th->getMessage()}";
            exit;
        }
    }
}
