<?php
session_start();
require_once ("../conexion.php");
require_once('../include/sesiones.php');
require_once('../php_api/api.php');

include('json.php');
$dataDocument = json_encode($json,JSON_UNESCAPED_UNICODE);
$fh = fopen("../jsons/".$prefijo.$numero.".json", 'w');
fwrite($fh, $dataDocument);
fclose($fh);
$dataDocument = $json;


createInvoiceproduccion($configuration,$json);

function createInvoiceproduccion($configuration,$json)
{
    global $docs_id;
    global $prefijo;
    global $numero;
    global $con;
    global $mysqli;


    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "{$configuration->base_url}ubl2.1/support-document",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>json_encode($json),
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Accept: application/json',
            "Authorization: Bearer {$configuration->token}"
        ),
    ));

    $response = curl_exec($curl);
    curl_close($curl);
    $book=json_decode($response, true);
    $message=$book['message'];



    if($message<>'AttachedDocument #'.$prefijo.$numero.' generada con éxito')
    {
        if($message=='The given data was invalid.')
        {
            echo "<div class='alert alert-danger alert-dismissable'>Los datos proporcionados no son válidos.</div>";
            if(!empty($book['errors']))
            {
                foreach ($book['errors'] as $key => $value) 
                {
                    if(!empty($value))
                    {
                        foreach ($value as $key2 => $value2) 
                        {
                            echo '<div class="alert alert-warning alert-dismissable">'.$value2.'</div>';
                            //echo "<div class='alert alert-warning alert-dismissable'>".$book["errors"]["number"][0] . "</div>";  
                        }
                    }
                }
            }
        }
    }
    else 
    {
       
        $resultado=json_decode($response);
        $cuds=$resultado->ResponseDian->Envelope->Body->SendBillSyncResponse->SendBillSyncResult->XmlDocumentKey;
        $validacion=$resultado->ResponseDian->Envelope->Body->SendBillSyncResponse->SendBillSyncResult->IsValid; 
        if($validacion=="true")
        {
            echo "<div class='alert alert-info alert-dismissable'> EL DOCUMENTO DE SOPORTE $prefijo$nom_numero FUE CARGADO CORRECTAMENTE</div>";
            $registrs=mysqli_query($con,"UPDATE dian_documento_soporte Set
                                            dosc_cuds='$cuds', 
                                            estado_dian='Aprobada'
                                            Where docs_id='$docs_id'") or die(mysqli_error($con));
        }
        else if($validacion=="false")
        {
            $estado=$resultado->ResponseDian->Envelope->Body->SendBillSyncResponse->SendBillSyncResult->StatusMessage;  
            $regla=$resultado->ResponseDian->Envelope->Body->SendBillSyncResponse->SendBillSyncResult->ErrorMessage->string; 

            echo "<div class='alert alert-danger alert-dismissable'><strong> EL DOCUMENTO DE SOPORTE ".$prefijo.$numero." NO SE CARGO POR ERRORES</strong></div>";
            
            echo "<div class='alert alert-danger alert-dismissable'<H2>"; echo $estado; echo "</div>";
            foreach ((array) $regla as $val) 
            { 
                echo "<div class='alert alert-warning alert-dismissable'>";
                echo $val, '<br>';
                echo "</div>";

                if ($val=='Regla: 90, Rechazo: Documento procesado anteriormente.')
                {
                    $registrs=mysqli_query($con,"UPDATE dian_documento_soporte Set
                                            dosc_cuds='$cuds', 
                                            estado_dian='Aprobada'
                                            Where docs_id='$docs_id'") or die(mysqli_error($con));

                }
            }
        }
    }
}
?>