<?php
require_once 'core/Auth.php';


class Middleware {

    public static function requireAuth() {
        $headers = getallheaders();
        if (!isset($headers['Authorization'])) {
            http_response_code(401);
            echo json_encode(['status' => 'error', 'message' => 'Token no enviado']);
            exit;
        }

        $token = str_replace('Bearer ', '', $headers['Authorization']);
        try {
            $Resp = Auth::validateToken($token);
        } catch (Exception $e) {
            http_response_code(401);
            echo json_encode(['status' => 'error', 'message' => 'Token inválido o expirado']);
            exit;
        }

        $Resp->path = Middleware::expendToken($Resp->cid);
        return $Resp;

    }

    public static function expendToken($account) {

       require_once('../configOPFBasic.php');

       $SQL = "SELECT path FROM opf_accounts where account = '$account'";

       $result = mysqli_query($link,$SQL); 
       
        if($result){
            $rowData = mysqli_fetch_assoc($result);
            if ($rowData <> null) {

                $SQL2 = "UPDATE opf_accounts SET token = '' where account = '$account'";
                $result2 =mysqli_query($link,$SQL2); 
                if(!$result){throw new Exception("Error en la BD ".mysqli_error($link),500);}

                return $rowData["path"];

            }else{
                throw new Exception("ClienteID no encontrado",500);
            }

        }else{
            throw new Exception("Error consultando la BD ".mysqli_error($link),500);
        }


    }

}
