<?php 
    Session::init(); 
    $ver = (Session::get('rol') == 1 OR Session::get('rol') == 2 OR Session::get('rol') == 3 OR Session::get('rol') == 5 OR Session::get('rol') == 7) ? '' :  header('location: ' . URL . 'err/danger'); 
    $ver = (Session::get('bloqueo') == 0 OR Session::get('bloqueo') == null) ? '' :  header('location: ' . URL . 'err/bloqueo');
?>
<?php
require_once 'public/lib/print/num_letras.php';
require_once 'models/ajuste_model.php';
require_once 'models/comprobante_model.php';

class Whatsapp extends Controller {

	function __construct() {
		parent::__construct();
	}
    
    public function get_send_wsp(): void {
    header('Content-Type: application/json');

    try {
        
            $hdr = $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '';
            if (strtolower($hdr) !== 'xmlhttprequest') {
                throw new \InvalidArgumentException('Petición inválida');
            }

            $number   = trim((string)($_POST['number'] ?? ''));
            $url_document    = trim((string)($_POST['media'] ?? ''));
            $filename = trim((string)($_POST['filename'] ?? ''));
            
            if ($number === '') {
                throw new \InvalidArgumentException('Debe indicar un número de teléfono');
            }

            $wtsp = $this->getInstanceWtsp();
            $token = $wtsp['wsp_token'];
            $message = $wtsp['wsp_message'];

            $url = 'https://efasis.efa-api.com/api/message/send/pdf';

            $payload = json_encode([
                'number'   => $number,
                'file'     => $url_document,
                'filename' => $filename,
                'message'  => $message,
            ]);

            $headers = [
                'Content-Type: application/json',
                "Authorization: Bearer {$token}",
            ];

        
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER,   $headers);
            curl_setopt($ch, CURLOPT_POST,         true);
            curl_setopt($ch, CURLOPT_POSTFIELDS,   $payload);

            $response   = curl_exec($ch);
            $httpCode   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            $responseData = json_decode($response, true);

            if ($httpCode === 200) {
                http_response_code(200);
                echo json_encode([
                    'ok'      => true,
                    'message' => 'Documento enviado con éxito',
                    'data'    => $responseData,
                ]);
            } else {
                http_response_code(502);
                echo json_encode([
                    'ok'      => false,
                    'message' => 'Error al enviar el documento',
                    'data'    => $responseData,
                ]);
            }
        }
        catch (\InvalidArgumentException $e) {
            http_response_code(422);
            echo json_encode(['ok' => false, 'message' => $e->getMessage()]);
        }
        catch (\Throwable $e) {
            http_response_code(500);
            echo json_encode(['ok' => false, 'message' => 'Error interno del servidor']);
        }
    }

    function getInstanceWtsp(){

        $ajuste = new Ajuste_Model();
        $ajustes = $ajuste->datoplataforma_data();
        $this->checkApiStatus($ajustes->api_wsp, $ajustes->wsp_token);

        return [
            
            'wsp_token' => (string) $ajustes->wsp_token,
            'wsp_message' => (string) $ajustes->wsp_message,
        ];

    }

    function checkApiStatus(string $status, string $token): void {
        if ($status != '1') {
            http_response_code(403);
            echo json_encode([
            'ok'      => false,
            'message' => 'No tienes habilitados los permisos de envío por API de WhatsApp'
            ]);
            exit;
        }

        if ($token === '') {
            http_response_code(403);
            echo json_encode([
            'ok'      => false,
            'message' => 'No tienes habilitado ningún token de envío por API de WhatsApp'
            ]);
            exit;
        }
    }
}