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

$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if($action == 'ajax')
{
    $ubicacion = mysqli_real_escape_string($con,(strip_tags($_REQUEST['ubicacion'], ENT_QUOTES)));
    $proveedor = mysqli_real_escape_string($con,(strip_tags($_REQUEST['proveedor'], ENT_QUOTES)));
    $familia = mysqli_real_escape_string($con,(strip_tags($_REQUEST['familia'], ENT_QUOTES)));
    $q = mysqli_real_escape_string($con,(strip_tags($_REQUEST['q'], ENT_QUOTES)));
    $estado = mysqli_real_escape_string($con,(strip_tags($_REQUEST['estado'], ENT_QUOTES)));
    $buscar = mb_strtoupper($q);
    
    include '../include/pagination.php';
    $page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
    $per_page = $conf_pagi_articulos; 
    $adjacents  = 4; 
    $offset = ($page - 1) * $per_page;

    /// organizar listao de articulos///
    $ordenes = [
    'art_cantidad'   => 'b.art_cantidad desc',
    'art_referencia' => 'a.art_referencia asc',
    'art_nombre'     => 'a.art_nombre asc',
    ];

    $ordenar = $ordenes[$organizar_articulos] ?? 'b.art_cantidad desc'; // valor por defecto

    ////// filtro de busqueda de los articulos//////////

    $where = "a.empresa='$empresa' AND a.art_tipo='articulo' AND a.art_estado LIKE '$estado'";

    // Agregar filtros condicionalmente
    if (!empty($ubicacion)) {
        $where .= " AND a.ubicacion_ubi_id='$ubicacion'";
    }
    if (!empty($proveedor)) {
        $where .= " AND a.proveedor_pro_id='$proveedor'";
    }
    if (!empty($familia)) {
        $where .= " AND a.familias_fam_id='$familia'";
    }

    // Filtro de búsqueda
    $where .= " AND (a.art_referencia LIKE '%$q%' OR a.art_nombre LIKE '%$q%' OR a.art_barras LIKE '%$q%' OR a.art_referencia2 LIKE '%$q%')";

    // Query para contar resultados
    $count_query = mysqli_query($con, "SELECT COUNT(*) AS numrows FROM articulos a WHERE $where");
    $row = mysqli_fetch_array($count_query);
    $numrows = $row['numrows'];
    $total_pages = ceil($numrows / $per_page);
    $reload = '../I_articulos.php';

    // Query principal
    $sql = mysqli_query($con, "SELECT *, a.art_id AS art_id, b.art_id AS art_idd, SUM(b.art_cantidad) AS art_cantidad 
        FROM articulos a 
        JOIN articulos_has_bodegas b ON a.art_id = b.articulos_art_id 
        WHERE $where AND b.sucursal='$sucursal'
        GROUP BY a.art_id 
        ORDER BY $ordenar, a.art_nombre ASC 
        LIMIT $offset, $per_page");

    }
if ($numrows>0) { ?>
<div class="table-responsive">
    <table class="table table-bordered table-hover table-striped" style="font-size: 9pt;">
        <tr>
            <th width="8%">CODIGO</th>
            <th width="8%">REFERENCIA</th>
            <th>NOMBRE</th>
            <?php if($tienda_online=='si') { ?>
                <th width="4%">ONLINE</th>
            <?php } ?>
            <th width="1%"></th>
            <th width="10%">STOCK</th>
            <th width="8%">PRECIO</th>
            <?php if ($negocio_neg_id==3) { ?>
                <th width="10%">UBICACIÓN</th>
            <?php } ?>
            <th width="15%"></th>
        </tr>
        <?php
        while ($reg=mysqli_fetch_array($sql))
        {
            $art_id=$reg['art_id'];
            $id=$reg['art_id'];
            $art_idd=$reg['art_idd'];
            $art_referencia=$reg['art_referencia'];
            $art_escaso=$reg['art_escaso'];
            $art_cantidad=$reg['art_cantidad'];
        ?>
        <tr>
            
            <td>
            <?php 
                echo mb_strtoupper(str_replace($buscar, "<strong><span style='color: ".$resaltador."'>".$buscar."</span></strong>", $reg['art_referencia']));
            ?>
            </td>
            <td>
            <?php 
                echo mb_strtoupper(str_replace($buscar, "<strong><span style='color:".$resaltador."'>".$buscar."</span></strong>", $reg['art_referencia2']));
            ?> 
            </td>
            <td>
            <?php 
                echo mb_strtoupper(str_replace($buscar, "<strong><span style='color:".$resaltador."'>".$buscar."</span></strong>", $reg['art_nombre']));
            ?> 
            </td>
            
            <?php if($tienda_online=='si') { ?>
            <td><center>
                <?php
                if($reg['art_online']=="Activo")
                {
                    echo $estados='<a href="#" onclick="online('.$reg['art_id'].')"> <div style=" background: blue;border-radius: 50%; width: 13px;height: 13px; "title="Inactivo"> </div></a>';
                }
                else  
                {
                    echo $estados='<a href="#" onclick="online('.$reg['art_id'].')"> <div style=" background: red;border-radius: 50%; width: 13px;height: 13px;" title="Activo"> </div></a>';
                }
                ?></center> 
            </td>
            <?php    }   ?>

            <td>
             <?php if ($art_cantidad>$art_escaso) { ?>
                     <div style="float: left; background: green;border-radius: 50%; width: 13px;height: 13px;  "></div>
                <?php   } else if ($art_cantidad>0 && $art_cantidad<=$art_escaso) { ?>
                    <div style=" float: left;background: yellow;border-radius: 50%; width: 13px;height: 13px;"></div>
                <?php   } else if ($art_cantidad<=0) { ?>
                     <div style="float: left; background: red;border-radius: 50%; width: 13px;height: 13px;"></div>
                <?php   }  ?>
            </td>
            <td>
                 <?php
                    $sucu_coun=mysqli_query($con,"SELECT count(*) as num_sucursales FROM sucursal where empresa='$empresa' and suc_id<>'$sucursal' and suc_estado='activo'");
                    $rowsucu_coun=mysqli_fetch_array($sucu_coun);
                    $num_sucursales=$rowsucu_coun['num_sucursales'];

                ?>
                <span class="" style="color:black;">
                    <?php if($num_sucursales>0) { echo $suc_nombre; echo ':'; } ?><?php 
                        if (fmod($art_cantidad, 1) == 0) 
                        {
                            echo number_format($art_cantidad, 0, '.', '');
                        } 
                        else 
                        {
                            echo number_format($art_cantidad, 2, '.', '');
                        }
                    ?> 
                </span>
                </br>
                <?php
                    $sucu=mysqli_query($con,"SELECT * FROM sucursal where empresa='$empresa' and suc_id<>'$sucursal' and suc_estado='activo'");
                    while($sucu1=mysqli_fetch_array($sucu))
                    {
                        $suc_id=$sucu1['suc_id'];
                        $sucursal_nombre=$sucu1['suc_nombre'];

                        $can=mysqli_query($con,"SELECT *, sum(art_cantidad) as art_cantidad FROM articulos_has_bodegas WHERE articulos_art_id='$art_id' and sucursal='$suc_id' ") or die(mysqli_error($con));
                        $c=mysqli_fetch_array($can);
                        $cantidad=$c['art_cantidad'];
                ?>

                    <span class="" style="color:#a2a0a2;"><?php echo $sucursal_nombre; ?>:<?php echo number_format($cantidad,0); ?> </span>
                <?php } ?>
            </td>

            <td><p class="pull-right"><?php echo number_format($reg['art_pvp'],0);?></p></td>
            <?php if ($negocio_neg_id==3){?>
            <td ><p class="pull-center">
                <?php 
                    $ubicacion=$reg['ubicacion_ubi_id'];
                    $ubi = mysqli_query($con,"SELECT * FROM ubicacion where ubi_id='$ubicacion' and empresa='$empresa' and sucursal='$sucursal'") ;
                    $ub = mysqli_fetch_array( $ubi );
                    $ubi_nombre=$ub['ubi_nombre']; 
                    if($ubi_nombre<>'SIN UBICACION')
                    {
                        echo $ubi_nombre;
                    }   
                ?>
            </p></td>
            <?php } ?>
            <td>
                <a data-id="<?php echo $art_id;?>" class="btn btn-edit btn-xs btn-warning"  title="Tarifas de Precio"> <i class="btn-icon-only icon-usd"></i></a>
                <?php 
                $per=mysqli_query($con,"SELECT * FROM modulo_permiso where usuario='$usu_id' and mod_id='5' and modp_nombre='Modificar Articulo' ") or die(mysqli_error($con));
                $permi = mysqli_fetch_array($per);
                $estado=$permi['estado'];
                if ($estado=='Activo') { ?>
                    <a data-id="<?php echo $id;?>" title="Editar Articulo" class="btn-art btn btn-xs btn-info"> <i class="btn-icon-only icon-edit"></i></a>
                <?php } ?> 

                <?php  
                $per1=mysqli_query($con,"SELECT * FROM modulo_permiso where usuario='$usu_id' and mod_id='5' and modp_nombre='Eliminar Articulo' ") or die(mysqli_error($con));
                $permi1 = mysqli_fetch_array($per1);
                $estado1=$permi1['estado'];
                if ($estado1=='Activo') { ?>
                    <a href="#" onclick="eliminar('<?php echo $art_id;?>')" title="Eliminar" class="btn btn-xs btn-danger"><i class="btn-icon-only icon-remove"></i></a>
                <?php } ?>


              
            <?php  if ($negocio_neg_id==1){?>
                <a data-id="<?php echo $id;?>" class="btn btn-ser btn-xs btn-default" title="Serial"> <i class="btn-icon-only icon-barcode"></i></a>
            <?php  } ?>
            <?php 
                $can=mysqli_query($con,"SELECT * FROM articulos_detallado WHERE bodegas_art_id='$art_idd'") or die(mysqli_error($con));
                $c=mysqli_fetch_array($can);
                if(isset($c['artd_cantidad']))
                {
                    $artd_cantidad=$c['artd_cantidad'];
                }

                    if($c>0){ ?>
                        <a data-id="<?php echo $art_id;?>" class="btn btn-det btn-xs btn-success" title="Detallar"> <i class="btn-icon-only icon-cut"></i></a>
            <?php  } ?>

           
            </td>
        </tr>
        <?php } ?>
        <tr>
        <?php if ($negocio_neg_id==3 ){ $col=8; } else { $col=7; } if($tienda_online=='si'){$onl=1;}else{$onl=0;} ?>
            <td colspan="<?php echo $col+$onl+1;?>">
                <span class="pull-right">
                    <?php echo paginate($reload, $page, $total_pages, $adjacents); ?>
                </span>
                <input type="hidden" name="pagina" id="pagina" value="<?php echo $page; ?>">
            </td>
        </tr>
    </table>
</div>
      <?php
    }
?>
<script>
//modificar    
 $(".btn-art").click(function(){
    id = $(this).data("id");
    var pagina=$("#pagina").val();
    $.get("php_articulo/form_modificar_articulo.php","id="+id+"&pagina="+pagina,function(data){
        $("#form-art").html(data);
    });
    $('#modificar_articulo').modal('show');
});

//tarifas
$(".btn-edit").click(function(){
      id = $(this).data("id");
      $.get("./php_articulo/form_tarifas_precio.php","id="+id,function(data){
        $("#form-edit").html(data);
      });
      $('#editModal').modal('show');
    });

//detallar
    $(".btn-det").click(function(){
      id = $(this).data("id");
      $.get("./php_articulo/form_detallar.php","id="+id,function(data){
        $("#form-det").html(data);
      });
      $('#detallar').modal('show');
    }); 

//seriales
    $(".btn-ser").click(function(){
      id = $(this).data("id");
      $.get("./php_articulo/form_seriales.php","id="+id,function(data){
        $("#form-ser").html(data);
      });
      $('#serModal').modal('show');
    });
</script>



<div class="modal fade" id="detallar" tabindex="-1" role="dialog" >
    <div class="modal-dialog">
        <div class="modal-content">
            <div id="form-det"></div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<div class="modal fade" id="serModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">Eliminar Seriales</h4>
            </div>
            <div class="modal-body">
                <div id="form-ser"></div>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<div class="modal fade" id="modal_serial_nuevo" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">AGREGAR SERIALES</h4>
            </div>
            <div class="modal-body">
                <div id="form-serial_nuevo"></div>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
