<?php
//CLIENTE
$Nit=$dato1['ven_cc'];
$dv=$clie1['clie_dv']; 
$ven_nombre=utf8_encode($dato1['ven_nombre']);
$ven_telefono=$clie1['clie_telefono']; 
$direccion=utf8_encode($clie1['clie_direccion']); 
$ven_correo=$clie1['clie_correo']; 
$tipo_documento_cli=$clie1['clie_tipo_doc']; 
$tipo_organizacion=$clie1['clie_contribuyente']; 
$tipo_regimen=$clie1['clie_regimen']; 
$municipio=$clie1['clie_ciudad'];

//METODOS DE PAGO
$forma_pago=$forma_pago; //contado=1 credito=2
$tipo_pago=$tipo_pago; //$tipo_pago; // 10=efectivo
$fecha_vencimiento=$dato1['ven_fecha']; 
$plazo_dias=$dato1['ven_dias']; 


$subtotal2=0;
$total_iva=0;

$sql=mysqli_query($con, "SELECT 
        vd.vend_cantidad AS vend_cantidad,
        vd.vend_precio AS vend_precio,
        vd.vend_iva AS vend_iva,
        vd.vend_desc AS vend_desc
    FROM venta_detalle vd WHERE vd.ventas_ven_id='$ven_id'
    UNION ALL
    SELECT 
        vdc.combo_cantidad AS vend_cantidad,
        vdc.combo_precio AS vend_precio,
        vdc.combo_iva AS vend_iva,
        vdc.combo_desc AS vend_desc
    FROM venta_detalle_combo vdc WHERE vdc.ven_id='$ven_id'");

while ($row=mysqli_fetch_array($sql))
{
    $vend_cantidad=$row['vend_cantidad'];
    $vend_precio=$row['vend_precio'];
    $vend_iva=$row['vend_iva'];
    $vend_descuento=$row['vend_desc'];

    $iva0=$vend_iva/100;
    $iva1=1+$iva0;

    $precio_total_sin_iva_item=($vend_precio/$iva1)*$vend_cantidad;
    $descuento_item=($vend_descuento/100)*$precio_total_sin_iva_item;
    $total_iva_item=($precio_total_sin_iva_item-$descuento_item)*$iva0;

    $subtotal2+=$precio_total_sin_iva_item-$descuento_item;
    $total_iva+=$total_iva_item;
}
$sumador_total_con_descuento=($subtotal2+$total_iva);



$json = array(
            "number"            =>  $numero,
            "type_document_id"  =>  $tipo_documento,
            "date"              =>  $fecha,
            "time"              =>  $hora,
            "resolution_number" =>  $ser_resolucion,
            "prefix"            =>  $prefijo,
            "notes"             =>  $observaciones,
            
            "establishment_name" => "",
           /*   "establishment_address" => "calle 11",
            "establishment_phone" => "3150000000",
            "establishment_municipality" => "804",
            "establishment_email" => "x8basura@gmail.com",*/

            "sendmail"          =>  false,
            "customer"          =>  array(
                           "identification_number" => $Nit,
                           "dv"                    => $dv,
                           "name"                  => $ven_nombre,
                           "phone"                 => $ven_telefono,
                           "address"               => $direccion,
                           "email"                 => $ven_correo,
                        //   "merchant_registration" => $registro_mercantil,
                           "type_document_identification_id"=> $tipo_documento_cli,
                           "type_organization_id"  => $tipo_organizacion,
                           "municipality_id"       => $municipio,
                           "type_regime_id"        => $tipo_regimen),

            "payment_form"      =>  array(
                           "payment_form_id"       => $forma_pago,
                           "payment_method_id"     => $tipo_pago,
                           "payment_due_date"      => $fecha_vencimiento,
                           "duration_measure"      => $plazo_dias),



            "legal_monetary_totals" =>  array(
                            "line_extension_amount" => round($subtotal2,2), //base
                            "tax_exclusive_amount"  => round($subtotal2,2), //base
                            "tax_inclusive_amount"  => round($sumador_total_con_descuento,2),
                            "allowance_total_amount"=> "0.00", //descuentos
                            "payable_amount"        => round($sumador_total_con_descuento,2) //total factura
                            ),

            "tax_totals"             =>  array(),
            'with_holding_tax_total' =>  array(),
            'invoice_lines'          =>  array()
);

//Impuestos IVAS de las factura
$sqliva=mysqli_query($con,"SELECT vend_iva
FROM (
    SELECT vd.vend_iva AS vend_iva FROM venta_detalle vd WHERE vd.ventas_ven_id='$ven_id'
    UNION ALL
    SELECT vdc.combo_iva AS vend_iva FROM venta_detalle_combo vdc WHERE vdc.ven_id='$ven_id'
) AS todos_los_ivas
GROUP BY vend_iva ORDER BY vend_iva;");
 
while ($iva=mysqli_fetch_array($sqliva))
{
    $iva_porcentaje=$iva['vend_iva'];
    $datos=mysqli_query($con,"SELECT * FROM iva where iva_porcentaje='$iva_porcentaje' ");
    $fila=mysqli_fetch_array($datos);
    $tipo_impuesto=$fila['tipo_impuesto'];

    $iva0=$iva_porcentaje/100;
    $iva1=1+$iva0;

    $neto_i=0;
    $total_iva=0;

    $sqliva1=mysqli_query($con,"SELECT 
        vd.vend_cantidad AS vend_cantidad,
        vd.vend_precio AS vend_precio,
        vd.vend_iva AS vend_iva,
        vd.vend_desc AS vend_desc
    FROM venta_detalle vd WHERE vd.ventas_ven_id='$ven_id' and vd.vend_iva='$iva_porcentaje'
    UNION ALL
    SELECT 
        vdc.combo_cantidad AS vend_cantidad,
        vdc.combo_precio AS vend_precio,
        vdc.combo_iva AS vend_iva,
        vdc.combo_desc AS vend_desc
    FROM venta_detalle_combo vdc WHERE vdc.ven_id='$ven_id' and vdc.combo_iva='$iva_porcentaje'");
    while ($rowi=mysqli_fetch_array($sqliva1))
    {
        $vend_cantidad=$rowi['vend_cantidad'];
        $vend_precio=$rowi['vend_precio'];
        $vend_iva=$rowi['vend_iva'];
        $vend_descuento=$rowi['vend_desc'];

        $precio_total_sin_iva_item=($vend_precio/$iva1)*$vend_cantidad;
        $descuento_item=($vend_descuento/100)*$precio_total_sin_iva_item;
        $total_iva_item=($precio_total_sin_iva_item-$descuento_item)*$iva0;

        $neto_i+=$precio_total_sin_iva_item-$descuento_item;
        $total_iva+=$total_iva_item;
    }
    array_push($json['tax_totals'],
        [
            "tax_id"        => $tipo_impuesto,
            "tax_amount"    => round($total_iva,2), //TOTAL IVA
            "percent"       => "$iva_porcentaje", //iva %
            "taxable_amount"=> round($neto_i,2)   //TOTAL
        ]
    );
}


//retenciones
$ret=mysqli_query($con, "SELECT * from retencion_venta where ventas_ven_id='$ven_id'");
while ($rets=mysqli_fetch_array($ret))
{
    $codigo=$rets['codigo'];
    $ret_base=$rets['ret_base'];
    $ret_importe=$rets['ret_importe'];
    $ret_porcentaje=$rets['porcentaje'];
    //$total_retencion=(($ret_porcentaje/100)*$subtotal2);
    array_push($json['with_holding_tax_total'], [
                            "tax_id"        => $codigo,
                            "tax_amount"    => round($ret_importe,2),
                            "percent"       => $ret_porcentaje,
                            "taxable_amount"=> round($ret_base,2),
                        ]);
}



//lineas
$sql=mysqli_query($con,"SELECT 
        vd.vend_art_id AS vend_art_id,
        vd.vend_referencia AS vend_referencia,
        vd.vend_nombre AS vend_nombre,
        vd.vend_cantidad AS vend_cantidad,
        vd.vend_precio AS vend_precio,
        vd.vend_iva AS vend_iva,
        vd.vend_desc AS vend_desc,
        'ART' AS tipo
    FROM venta_detalle vd WHERE vd.ventas_ven_id='$ven_id'
    UNION ALL
    SELECT 
        vdc.combo_id AS vend_art_id,
        vdc.combo_referencia AS vend_referencia,
        vdc.combo_nombre AS vend_nombre,
        vdc.combo_cantidad AS vend_cantidad,
        vdc.combo_precio AS vend_precio,
        vdc.combo_iva AS vend_iva,
        vdc.combo_desc AS vend_desc,
        'COMBO' AS tipo FROM venta_detalle_combo vdc WHERE vdc.ven_id='$ven_id'");
while ($row=mysqli_fetch_array($sql))
{
    $tipo=$row['tipo'];
    $vend_art_id=$row['vend_art_id'];
    IF($tipo=='ART')
    {
        $registros=mysqli_query($con,"SELECT * FROM articulos WHERE art_id='$vend_art_id' ") or die(mysqli_error($con));
        $dato=mysqli_fetch_array($registros); 
        $art_tipo_imp=$dato['art_tipo_imp'];
    }
    else
    {
        $registros=mysqli_query($con,"SELECT * FROM combos WHERE com_id='$vend_art_id' ") or die(mysqli_error($con));
        $dato=mysqli_fetch_array($registros); 
        $iva_porcentaje=$dato['com_iva'];

        $com_iva=mysqli_query($con,"SELECT * FROM iva where iva_porcentaje='$iva_porcentaje' ");
        $fila_com=mysqli_fetch_array($com_iva);
        $art_tipo_imp=$fila_com['tipo_impuesto'];
    }
   

    $vend_referencia=$row['vend_referencia'];
    $vend_nombre=$row['vend_nombre'];
    $vend_cantidad=$row['vend_cantidad'];
    $vend_precio=$row['vend_precio']; 
    $vend_iva=$row['vend_iva']; 
    $vend_descuento=$row['vend_desc']; 

    $iva0=$vend_iva/100; 
    $iva1=1+$iva0; 

    $precio_total_sin_iva_item=($vend_precio/$iva1)*$vend_cantidad; 
    $precio_total_sin_iva_item_unitario=($vend_precio/$iva1); 
    $descuento_item=($vend_descuento/100)*$precio_total_sin_iva_item; 
    $descuento_item_unitario=($vend_descuento/100)*$precio_total_sin_iva_item_unitario; 
    $total_iva_item=($precio_total_sin_iva_item-$descuento_item)*$iva0; 

    
    array_push($json['invoice_lines'], 
    [   "unit_measure_id"          => 70,    //70=unidad - 797=KWH
        "invoiced_quantity"        => $vend_cantidad,   //cantidad
        "line_extension_amount"    => round($precio_total_sin_iva_item-$descuento_item,2),  //total sin iva - descuento
        "free_of_charge_indicator" => false,

        "allowance_charges" =>  array(
                                array(
                                    "charge_indicator"        => false,
                                    "allowance_charge_reason" => "DESCUENTO GENERAL",
                                    "amount"                  => round($descuento_item_unitario,2),  //descuento item
                                    "base_amount"             => round($vend_precio,2)      //precio final
                                    ) 
                                ),

        "tax_totals"        =>  array(
                                array(
                                     "tax_id"         => $art_tipo_imp,                  //codigo table taxes 
                                     "tax_amount"     => round($total_iva_item,2),  //iva total
                                     "taxable_amount" => round($precio_total_sin_iva_item-$descuento_item,2), //total sin iva
                                     "percent"        => "$vend_iva"                // % iva
                                  ),
                                ),

       "description"                => utf8_encode($vend_nombre),   //nombre
       "code"                       => $vend_referencia,            //codigo
       "type_item_identification_id"=> 4,                           //type_item_identifications
       "price_amount"               => round($vend_precio,2),       //precio final
       "base_quantity"              => $vend_cantidad               //cantidad
    ]);
}

?>