<?php

require_once "models/post.model.php";
require_once "models/get.model.php";
require_once "models/put.model.php";
require_once "models/connection.php";

require_once "vendor/autoload.php";
use Firebase\JWT\JWT;

class PostController 
{
	
	static public function postData($table,$data) 
	{
		
		$response = PostModel::postData($table,$data);

		$return = new PostController();
		$return ->fncResponse($response);

	}

	static public function postLogin($table,$data) 
	{
	    if($table == "clientes_app"){
	        
	        $usuario = "IdCliente";
	        $idUsuario = "IdClienteApp";
	        
	    }else{
	        
	        $usuario = "Patente";
	        $idUsuario = "IdUsuario";
	    }
	    
	    
		$response = GetModel::getDataFilter($table,"*",$usuario,$data[$usuario]);
		
		if(!empty($response)){

			if($response[0]->{"Password"} == $data['Password']){

				$token = Connection::jwt($response[0]->{$idUsuario},$response[0]->{$usuario});
				$jwt = JWT::encode($token,"tr184c1tyu159ui43a2s1d",'HS256');

				$data = array(

					"Token" => $jwt,
					"TokenExp" => $token["exp"]

				);

				$update = PutModel::putData($table,$data,$response[0]->{$idUsuario},$idUsuario);

				if(isset($update["comment"]) && $update["comment"] == "The process was successful"){

					$response[0]->{"Token"} = $jwt;
					$response[0]->{"TokenExp"} = $token["exp"];
					unset($response[0]->{"Password"});

					$return = new PostController();
		    	    $return ->fncResponse($response);

				}

			}else{

				$response = null;
				$return = new PostController();
		    	$return ->fncResponse($response);

			}

		}else{

			$response = null;
			$return = new PostController();
		    $return ->fncResponse($response);

		}

	}

	public function fncResponse($response){

		if(!empty($response)){

			$json = array(
				'status'=> 200,
				'result'=> $response
			);

		}else{

			$json = array(
				'status'=> 404,
				'result'=> "Not found",
				'method'=> "post",
			);

		}

		echo json_encode($json,http_response_code($json['status']));

	}

}



?>