<?php
class ClienteSunatAPI {
    private $serverName;
    private $connectionOptions;
    private $con;

    public function __construct() {
        $this->serverName = DB_HOST;
        $this->connectionOptions = [
            "Database" => DB_NAME,
            "Uid" => DB_USER,
            "PWD" => DB_PASS,
            "CharacterSet" => "UTF-8"
        ];
        $this->con = sqlsrv_connect($this->serverName, $this->connectionOptions);
        if ($this->con === false) {
            die(print_r(sqlsrv_errors(), true));
        }
    }

    public function consultaClienteDb($term) {
        $term = "%".$term."%";
        $sql = "  SELECT CL_IdCliente AS id_cliente, rtrim(ltrim(CL_Nombre)) AS nombre_cliente, 
                        rtrim(ltrim(CL_Direccion)) AS direccion, 
                        rtrim(ltrim(CL_Ruc))+rtrim(ltrim(CL_Dni))AS doc_identidad,
                        'P1' AS id_precio ,rtrim(ltrim(CL_Celular)) as CL_Celular,rtrim(ltrim(CL_Correo)) as CL_Correo,
                        CL_Exhonerado_IGV,CL_Retencion,CL_Percepcion,
                        CL_IdEstado,rtrim(ltrim(CL_User)) as CL_User
                FROM Cliente 
                WHERE rtrim(ltrim(CL_Nombre)) LIKE ? OR CL_Ruc LIKE ? OR CL_Dni LIKE ?";
        $params = [$term, $term, $term];
        $stmt = sqlsrv_query($this->con, $sql, $params);
        $result = [];
        if ($stmt) {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $result[] = $row;
            }
        }
        return $result;
    }

    public function consultarSunatDni($dni) {
        $token = 'apis-token-1.aTSI1U7KEuT-6bbbCguH-4Y8TI6KS73N';
        $curl = curl_init("https://api.apis.net.pe/v1/dni?numero=$dni");
        curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                "Authorization: Bearer $token",
                "Referer: https://apis.net.pe/consulta-dni-api"
            ]
        ]);
        $response = curl_exec($curl);
        curl_close($curl);
        return json_decode($response, true);
    }

    public function consultarSunatRuc($ruc) {
        $token = 'apis-token-1.aTSI1U7KEuT-6bbbCguH-4Y8TI6KS73N';
        $curl = curl_init("https://api.apis.net.pe/v1/ruc?numero=$ruc");
        curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                "Authorization: Bearer $token",
                "Referer: https://apis.net.pe/api-ruc"
            ]
        ]);
        $response = curl_exec($curl);
        curl_close($curl);
        return json_decode($response, true);
    }

 

}