<?php
include('is_logged.php');
require_once ("../config/db.php");
require_once ("../config/conexion.php");

$query=mysqli_query($con, "select * from tasa where id_tasa='1'");
while ($row=mysqli_fetch_array($query))
{
    $id_tasa=$row['id_tasa'];
    $tasa_actual=$row['tasa'];
    $ult_act=$row['fecha'];
}   
    
$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if (isset($_GET['id']) && isset($_GET['pro']))
{
    $numero_factura=intval($_GET['id']);
    $nombre_pro=$_GET['pro'];
    
    $e=mysqli_query($con,"select * from proveedores where nombre_proveedor='$nombre_pro'")  or die(mysqli_error($con));
    $r=mysqli_fetch_array($e);
    $pro=$r['id_pro'];
    
    $query=mysqli_query($con, "select * from compras where numero_fact='".$numero_factura."' && proveedor='".$pro."'");
    $count=mysqli_num_rows($query);
    if ($count>0)
    {
        if ($delete1=mysqli_query($con,"DELETE FROM compras WHERE numero_fact='".$numero_factura."' && proveedor='".$pro."'"))
        {
            $query_eliminar=mysqli_query($con, "select * from detalle_compra where numero_compra='".$numero_factura."' && id_proveedor='".$pro."'"); 
            while($res=mysqli_fetch_array($query_eliminar))
            {
                $id_producto=$res['id_producto'];
                $cantidad=$res['cantidad'];
                $query_pro=mysqli_query($con,"SELECT * FROM `products` WHERE `id_producto`='$id_producto';") or die(mysqli_error($con));
                $res_pro=mysqli_fetch_array($query_pro);
                $existencia=$res_pro['existencia'];
                $act=$existencia-$cantidad;
                mysqli_query($con,"UPDATE `products` SET `existencia` = '$act' WHERE `products`.`id_producto` ='$id_producto';");
            }
            mysqli_query($con,"DELETE FROM detalle_compra WHERE numero_compra='".$numero_factura."' && id_proveedor='".$pro."'");
            ?>
            <div class="alert alert-success alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <strong>Aviso!</strong> Datos eliminados exitosamente.
            </div>
            <?php 
        }
        else 
        {
            ?>
            <div class="alert alert-danger alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <strong>Error!</strong> Lo siento algo ha salido mal intenta nuevamente.
            </div>
            <?php
        }
            
    } 
    else 
    {
        ?>
        <div class="alert alert-danger alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <strong>Error!</strong> No se pudo eliminar esta compra.
        </div>
        <?php
    }
        
}
if($action == 'ajax')
{
    $q = mysqli_real_escape_string($con,(strip_tags($_REQUEST['q'], ENT_QUOTES)));
    $sTable = "compras, proveedores";
    $sWhere = "";
    $sWhere.=" WHERE compras.proveedor=proveedores.id_pro";
    if( $_GET['q'] != "")
    {
        $sWhere.= " and (proveedores.nombre_proveedor like '%$q%' or compras.numero_fact like '%$q%')";
    }
    $sWhere.=" order by compras.id_compra desc";
    include 'pagination.php'; //include pagination file
    //pagination variables
    $page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
    $per_page = 20; //how much records you want to show
    $adjacents  = 4; //gap between pages after number of adjacents
    $offset = ($page - 1) * $per_page;
    //Count the total number of row in your table*/
    $count_query   = mysqli_query($con, "SELECT count(*) AS numrows FROM $sTable  $sWhere");
    $row= mysqli_fetch_array($count_query);
    $numrows = $row['numrows'];
    $total_pages = ceil($numrows/$per_page);
    $reload = './adquisiciones.php';
        //main query to fetch the data
    $sql="SELECT * FROM  $sTable $sWhere LIMIT $offset,$per_page";
    $query = mysqli_query($con, $sql);
    //loop through fetched data
    ?>
    <div class="table-responsive">
        <table class="table" style="font-size:12px;">
            <tr class="warning">
                <th>Numero factura</th>
                <th>Fecha</th>
                <th>Proveedor</th>
                <?php if($_SESSION['rol']!="almacen")
                {
                ?>
                <th class='text-right'>Exentas</th>
                <th class='text-right'>Base</th>
                <th class='text-right'>Iva</th>
                <th class='text-right'>Monto Total</th>
                <th class='text-right'>Abonado</th>
                <th class='text-right'>Por Pagar</th>
                <?php } ?>
                <th class='text-right'>Acciones</th>
            </tr>
            <?php
            if ($numrows>0)
            {
                $tax = floatval(TAX);
                while ($row=mysqli_fetch_array($query))
                {
                    $id_compra=$row['id_compra'];
                    $numero_factura=$row['numero_fact'];
                    $fecha=date("d/m/Y", strtotime($row['fecha']));
                    $nombre_proveedor=$row['nombre_proveedor'];
                    $telefono_proveedor=$row['telefono_proveedor'];
                    $email_proveedor=$row['correo_proveedor'];
                    $pro = isset($row['proveedor']) ? intval($row['proveedor']) : (isset($row['id_pro']) ? intval($row['id_pro']) : 0);
                    
                    $total_compra_cabecera = floatval($row['total']);

                    // Consultamos el desglose detallado
                    $tot_det = mysqli_query($con, "SELECT 
                        SUM(cantidad * precio_compra) AS monto_total,
                        SUM(CASE WHEN exento = 1 THEN (cantidad * precio_compra) ELSE 0 END) AS total_exento,
                        SUM(CASE WHEN exento = 0 THEN (cantidad * precio_compra) ELSE 0 END) AS total_gravado
                        FROM detalle_compra WHERE numero_compra='$numero_factura' AND id_proveedor=$pro");
                    
                    $fetch_det = mysqli_fetch_array($tot_det);
                    $monto_total_det = ($fetch_det['monto_total'] != null) ? floatval($fetch_det['monto_total']) : 0;
                    $exento = ($fetch_det['total_exento'] != null) ? floatval($fetch_det['total_exento']) : 0;
                    $gravado = ($fetch_det['total_gravado'] != null) ? floatval($fetch_det['total_gravado']) : 0;

                    // Salvaguarda si la tabla detalle_compra está vacía
                    if ($monto_total_det == 0) {
                        $gravado = $total_compra_cabecera;
                        $monto_total = $total_compra_cabecera;
                        $exento = 0;
                    } else {
                        $monto_total = $monto_total_det;
                    }

                    // Cálculos claros: La Base solo procesa lo Gravado
                    $base = $gravado / (1 + ($tax / 100));
                    $iva = $base * ($tax / 100);

                    $abonos=$row['abono'];
                    $por_pagar=$row['por_pagar'];
                
                    // Formateo para la nueva columna Exentas
                    $exentof=number_format($exento,2,",", ".");
                    $dolar_a_bolivarexe=$exento*$tasa_actual;
                    $dolar_a_bolivarexef=number_format($dolar_a_bolivarexe,2,",", ".");

                    $basef=number_format($base,2,",", ".");
                    $dolar_a_bolivarbase=$base*$tasa_actual;
                    $dolar_a_bolivarbasef=number_format($dolar_a_bolivarbase,2,",", ".");
            
                    $ivaf=number_format($iva,2,",", ".");
                    $dolar_a_bolivariva=$iva*$tasa_actual;
                    $dolar_a_bolivarivaf=number_format($dolar_a_bolivariva,2,",", ".");
                    
                    $monto_totalf=number_format($monto_total,2,",", ".");
                    $dolar_a_bolivartot=$monto_total*$tasa_actual;
                    $dolar_a_bolivartotf=number_format($dolar_a_bolivartot,2,",", ".");
                    
                    $abonosf=number_format($abonos,2,",", ".");
                    $dolar_a_bolivarabo=$abonos*$tasa_actual;
                    $dolar_a_bolivarabof=number_format($dolar_a_bolivarabo,2,",", ".");
        
                    $por_pagarf=number_format($por_pagar,2,",", ".");
                    $dolar_a_bolivarpag=$por_pagar*$tasa_actual;
                    $dolar_a_bolivarpagf=number_format($dolar_a_bolivarpag,2,",", ".");
                    ?>
                    <tr style="font-size:11px;">
                        <td><?php echo $numero_factura; ?></td>
                        <td><?php echo $fecha; ?></td>
                        <td><a href="#" data-toggle="tooltip" data-placement="top" title="<i class='glyphicon glyphicon-phone'></i> <?php echo $telefono_proveedor;?><br><i class='glyphicon glyphicon-envelope'></i>  <?php echo $email_proveedor;?>" ><?php echo $nombre_proveedor;?></a></td>
                    
                        <?php if($_SESSION['rol']!="almacen")
                        {
                        ?>
                            <td class='text-right'>$<?php echo $exentof; ?> / <?php echo $dolar_a_bolivarexef; ?>Bs</td>
                            <td class='text-right'>$<?php echo $basef; ?> / <?php echo $dolar_a_bolivarbasef; ?>Bs</td>
                            <td class='text-right'>$<?php echo $ivaf; ?> / <?php echo $dolar_a_bolivarivaf; ?>Bs</td>
                            <td class='text-right'>$<?php echo $monto_totalf; ?> / <?php echo $dolar_a_bolivartotf; ?>Bs</td>                      
                            <td class='text-right'>$<?php echo $abonosf; ?> / <?php echo $dolar_a_bolivarabof; ?>Bs</td>   
                            <td class='text-right'>
                                <?php 
                                if($por_pagar<=0)
                                {
                                ?>
                                    <span class='label label-success'>
                                        Cancelada
                                    </span>
                                <?php
                                }
                                else
                                {
                                    ?>
                                    $<?php echo $por_pagarf; ?> / <?php echo $dolar_a_bolivarpagf;?>Bs
                                    <?php 
                                } 
                                ?>
                            </td>
                        <?php 
                        } 
                        ?>
                        <td class="text-right">
                        <?php 
                                    if($_SESSION['rol']=="gerencia" || $_SESSION['rol']=="almacen" )
                                    {
                                    ?>
                                        <a href="ver_compra.php?id_compra=<?php echo $id_compra;?>" class='btn btn-default' title='Ver Compra'><i class="glyphicon glyphicon-eye-open"></i></a>
                                    <?php
                                    }
                                
                                
                            if($_SESSION['rol']=="gerencia" || $_SESSION['rol']=="compras")
                            {
                            ?>
                                <a href="#" class='btn btn-default' data-id="<?php echo $numero_factura;?>" data-id2="<?php echo $por_pagarf;?>" data-id3="<?php echo $abonosf;?>" data-toggle="modal" title="Ver estado de cuenta" data-target="#estado_cuenta"><?php echo $numero_factura;?><i class="glyphicon glyphicon-stats"></i></a>
                                <?php
                                 
                                if($por_pagar>0)
                                {   
                                ?>  
                                    <a href="procesar_pago.php?id_compra=<?php echo $id_compra;?>" class='btn btn-default' title='Procesar Pago'><i class="glyphicon glyphicon-credit-card"></i></a>
                                <?php   
                                }
                                if($abonos==0)      
                                {
                                ?>
                                    <a href="editar_compra.php?id_compra=<?php echo $id_compra;?>" class='btn btn-default' title='Editar Compra'><i class="glyphicon glyphicon-edit"></i></a>
                                    <?php 
                                    if($_SESSION['rol']=="gerencia")
                                    {
                                    ?>
                                        <a href="#" class='btn btn-default' title='Anular Compra' onclick="eliminar('<?php echo $numero_factura; ?>','<?php echo $nombre_proveedor;?>')"><i class="glyphicon glyphicon-trash"></i></a>
                                    <?php
                                    }
                                } 
                    
                            }
                            ?>
                        </td>
                    </tr>
                    <?php
                }
                ?>
                <tr>
                    <td colspan=10><span class="pull-right"><?php echo paginate($reload, $page, $total_pages, $adjacents);?></span></td>
                </tr>
            <?php
            }
            ?>
        </table>
    </div>
    <?php
}
?>