<?php
/*********************** USEFULL FUNCTIONS **************************************/

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Selective\BasePath\BasePathMiddleware;
use Slim\Factory\AppFactory;


/**
 * Verificando los parametros requeridos en el método
 */
function verifyRequiredParams($required_fields, $request_params,  Request  $request, Response $response)
{
    global $errorMessages;
    $error = false;
    $error_fields = "";

    // $request_params = $request->getParsedBody();

    foreach ($required_fields as $field) {
        if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
            $error = true;
            $error_fields .= $field . ', ';
        }
    }

    if ($error) {
        // Required field(s) are missing or empty
        // echo error json and stop the app
        $responseBody = array();
        $responseBody["error"] = true;
        $responseBody["message_num"] = '003';
        $responseBody["message"] = str_replace("{1}",substr($error_fields, 0, -2),$errorMessages['003']); 

        return $responseBody;
    }
    return true;
}

/**
 * Validando parametro email si necesario; un Extra ;)
 */
function validateEmailRest($email, Request $request, Response $response)
{
    global $errorMessages;
    $responseBody = array();
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $responseBody["error"] = true;
        $responseBody["message_num"] = '004';
        $responseBody["message"] = $errorMessages['004']; 
        return $responseBody;
    }
    return true;
}

/**
 * Revisa si la consulta contiene un Header "Authorization" para validar
 */
function authenticate(Request $request, Response $response)
{
    global $errorMessages;
    // Getting request headers
    $headers = $request->getHeaders();
    // Verifying Authorization Header
    if (isset($headers['Authorization'])) {
        // get the api key
        $token = $headers['Authorization'];

        // validating api key
        if (!($token[0] == API_KEY)) { //API_KEY declarada en Config.php

            // api key is not present in users table
            $responseBody["error"] = true;
            $responseBody["message_num"] = '005';
            $responseBody["message"] = $errorMessages['005']; 
            // Error 401
            return $responseBody;
        } else {
            //procede utilizar el recurso o metodo del llamado
            return true;
        }
    } else {
        // api key is missing in header
        $responseBody["error"] = true;
        $responseBody["message_num"] = '006';
        $responseBody["message"] = $errorMessages['006']; 
        // error 400
        return $responseBody;
    }
}

/**
 * Revisa si la consulta contiene un Header "Token" para validar y recuperar session
 */
function controlSession(Request $request, Response $response)
{
    global $errorMessages;
    // Getting request headers
    $headers = $request->getHeaders();
    // Debug
    custom_error(2,"Header: ".json_encode($headers, true)); // To debug
    // Verifying Authorization Header
    if (isset($headers['token-user'])) {
        // get the api key
        $token = $headers['token-user'];
        $token = $token[0];
        $rs = DB::Query("SELECT * FROM edas_session_api WHERE uuid = '$token'");
        $data = $rs->fetchAssoc();
        if (!$data)
        {
            // Token is not present in control session table
            $responseBody["error"] = true;
            $responseBody["message_num"] = '005';
            $responseBody["message"] = $errorMessages['005']; 
            // Error 401
            return $responseBody;
        }

        // validating token
        if ($data['dateOfExpiry'] < now()) { // Expiry

            // Expiry
            $responseBody["error"] = true;
            $responseBody["message_num"] = '007';
            $responseBody["message"] = $errorMessages['007']; 
            // Error 401
            return $responseBody;
        } else {
            //procede utilizar el recurso o metodo del llamado
            
            // Update date of Expiry the Token
            $data2 = array();
            $keyvalues2 = array();
            $data2["dateOfExpiry"] = date('Y-m-d H:i:s', strtotime('3 hour'));
            $keyvalues2["id_edas_session_api"] = $data["id_edas_session_api"];
            DB::Update("edas_session_api", $data2, $keyvalues2 );
            // Restore Session of the User
            //  $session_id = $data['session'];  // Restaura la session
            // session_destroy();
            // session_id($session_id);
            // session_start();

            return true;
        }
    } else {
        // api key is missing in header
        $responseBody["error"] = true;
        $responseBody["message_num"] = '006';
        $responseBody["message"] = $errorMessages['006']; 
        // error 400
        return $responseBody;
    }
}




?>