<?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;

createInvoice($configuration,$json);
function createInvoice($configuration,$json)
{
    global $ven_id;
    global $usu_id;
    global $empresa;
    global $numero;
    global $ser_id;
    global $prefijo;
    global $Cliente_clie_id;
    global $con;
    global $mysqli;

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "{$configuration->base_url}ubl2.1/credit-note",
        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_POSTFIELDS =>file_get_contents('../jsons/'.$prefijo.$numero.'.json'),
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Accept: application/json',
            "Authorization: Bearer {$configuration->token}"
        ),
    ));

    $response = curl_exec($curl);
    curl_close($curl);
    sleep(3);
    $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);
        $cude=$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'> LA NOTA CREDITO $prefijo$numero FUE CARGADA CORRECTAMENTE</div>";
            $fecha=date('Y-m-d ');
            $hora=date('H:i:s');

            $can=mysqli_query($con,"SELECT MAX(not_id)as not_id FROM dian_nota_credito") or die(mysqli_error($con)); 
            $dato=mysqli_fetch_array($can);
            $not_id=$dato['not_id']+1;

            $insert_tmp=mysqli_query($con,"INSERT INTO dian_nota_credito (not_id,not_tipo_doc,not_ser_id,not_prefijo,not_numero,not_fecha,not_hora,cliente_id,not_cufe,not_estado,ventas_ven_id,empresa) 
                VALUES ('$not_id','ncp','$ser_id','$prefijo','$numero','$fecha','$hora','$Cliente_clie_id','$cude','Aprobada','$ven_id','$empresa')");
            //detalles
            $can7=mysqli_query($con,"SELECT * FROM dian_nota_credito_detalle_temp where empresa='$empresa' and usuario='$usu_id' and ven_id='$ven_id'") or die(mysqli_error($con));  
            while($row=mysqli_fetch_array($can7))
            {
                $not_art_id=$row['not_art_id'];
                $vend_referencia=$row['not_art_referencia'];
                $vend_nombre=$row['not_art_nombre'];
                $vend_cantidad=$row['not_art_cantidad'];
                //$vend_precio=$row['vend_precio']; //1.000.000
                $vend_precio=$row['not_precio']; //1.000.000
                $vend_iva=$row['not_iva']; //19%
                $vend_descuento=$row['not_descuento']; //10%
                $not_tipo=$row['not_tipo']; //10%

                 $can8=mysqli_query($con,"INSERT INTO dian_nota_credito_detalle (not_art_id,not_art_referencia,not_art_nombre,not_art_cantidad,not_iva,not_descuento,not_precio,not_tipo,empresa,ven_id,dian_not_id) 
                VALUES ('$not_art_id','$vend_referencia','$vend_nombre','$vend_cantidad','$vend_iva','$vend_descuento','$vend_precio','$not_tipo','$empresa','$ven_id','$not_id')") or die(mysqli_error($con)); 
            }
            $sql=mysqli_query($con,"DELETE FROM dian_nota_credito_detalle_temp WHERE empresa='$empresa' and usuario='$usu_id' and ven_id='$ven_id'") or die(mysqli_error($con));
        }
        else if($validacion=="false")
        {
            $estado=$resultado->ResponseDian->Envelope->Body->SendBillSyncResponse->SendBillSyncResult->StatusDescription;  
            $regla=$resultado->ResponseDian->Envelope->Body->SendBillSyncResponse->SendBillSyncResult->ErrorMessage->string; 
            echo "<div class='alert alert-info alert-dismissable'> LA NOTA CREDITO $prefijo$numero NO SE CARGO POR ERRORES</div>";
            echo "<div class='alert alert-danger alert-dismissable'>"; echo $estado; echo "</div>";
           
            foreach ((array) $regla as $val) 
            { 
                echo "<div class='alert alert-warning alert-dismissable'>";
                echo $val, '<br>';
                echo "</div>";
            }
        }
    }
}
?>