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

$readonly      = 'readonly';
$disabled_cam  = 'disabled';
$sql = "SELECT modp_nombre, estado FROM modulo_permiso WHERE mod_id='19' AND usuario='$usu_id'";
$res = mysqli_query($con, $sql) or die(mysqli_error($con));
// Procesar permisos
while ($row = mysqli_fetch_assoc($res)) {
    if ($row['modp_nombre'] === 'Modificar Precio' && $row['estado'] === 'Activo') {
        $readonly = '';
    }

    if ($row['modp_nombre'] === 'Cambio/Bonificacion' && $row['estado'] === 'Activo') {
        $disabled_cam = '';
    }
}

$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if($action=='ajax'){
    $q=mysqli_real_escape_string($con,(strip_tags($_REQUEST['q'], ENT_QUOTES)));
    $tipo=mysqli_real_escape_string($con,(strip_tags($_REQUEST['tipo'], ENT_QUOTES)));
    $buscar = mb_strtoupper($q);
	include '../include/pagination.php';
	$page=(isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
	$per_page=6; 
	$adjacents=4; 
	$offset=($page-1)*$per_page;
?>
<div class="table-responsive">
	<table class="table">
		<tr class="warning">
			<th width="10%">CODIGO</th>
			<th width="">NOMBRE</th>
			<th width="8%"><span class="pull-center">STOCK</span></th>
			<th width="10%"><span class="pull-left">CANTIDAD</span></th>
			<th width="13%"><span class="pull-right">DESCUENTO</span></th>
			<th width="13%"><span class="pull-right">PRECIO</span></th>
			<th ></th>
			<th width="5%"></th>
		</tr>
<?php
if($tipo=='articulos')
{
	$count_query=mysqli_query($con,"SELECT count(*) AS numrows FROM articulos a, articulos_has_bodegas b
    where a.art_id=b.articulos_art_id and a.empresa='$empresa' and b.sucursal='$sucursal' and a.art_estado='activo' and a.art_tipo='articulo' and (a.art_referencia like '%$q%' OR a.art_nombre like '%$q%' OR a.art_barras like '%$q%' OR a.art_referencia2 like '%$q%')");
    $row= mysqli_fetch_array($count_query);
    $numrows=$row['numrows'];
    $total_pages=ceil($numrows/$per_page);
    $reload='../index.php';
    $sql=mysqli_query($con,"SELECT *, a.art_id as art_id ,b.art_id as art_id_bod FROM articulos a, articulos_has_bodegas b
	where a.art_id=b.articulos_art_id and a.empresa='$empresa' and b.sucursal='$sucursal' and a.art_estado='activo' and a.art_tipo='articulo' and (a.art_referencia like '%$q%' OR a.art_nombre like '%$q%' OR a.art_barras like '%$q%' OR a.art_referencia2 like '%$q%') order by b.art_cantidad DESC, a.art_referencia ASC LIMIT $offset,$per_page");
	if ($numrows>0)
	{

		$sql_tar=mysqli_query($con, "SELECT * from cliente c,cliente_cotizacion_temp cc where c.clie_id=cc.cct_clie_id and cc.usuario='$usu_id' and c.empresa='$empresa'");
		if ($rw_tar= mysqli_fetch_array($sql_tar))
		{
			$tarifas_tar_id=$rw_tar['tarifas_tar_id'];
		}
		else 
		{
			$clim=mysqli_query($con,"SELECT * FROM cliente where clie_destacado='si' AND empresa='$empresa'") or die(mysqli_error($con)); 
			$clim=mysqli_fetch_array($clim);
			$tarifas_tar_id=$clim['tarifas_tar_id'];
		}

		
			
		while ($row=mysqli_fetch_array($sql))
		{


			$art_id=$row['art_id'];
			$art_id_bod=$row['art_id_bod'];
			$art_tipo=$row['art_tipo'];
			$art_referencia=$row['art_referencia'];
			$art_nombre=mb_strtoupper($row['art_nombre']);
			$art_pvp=$row['art_pvp'];
			$art_iva=$row['art_iva'];
			$art_precio_costo=$row['art_precio_costo'];
			


			if ($bajo_cero_tat == 'Si') {

			    $can_real_cot = 0;

			    $consulta = mysqli_query($con, "
			        SELECT 
			            SUM(cott_cantidad * cott_x_cantidad) AS total
			        FROM cotizacion_detalle_temp
			        WHERE empresa = '$empresa'
			        AND usuario = '$usu_id'
			        AND cott_art_id = '$art_id'
			    ") or die(mysqli_error($con));

			    $data = mysqli_fetch_assoc($consulta);
			    $can_real_cot = $data['total'] ?? 0;

			    // stock disponible real
			    $art_cantidad1 = max(0, $row['art_cantidad'] - $can_real_cot);

			} else {
			    $art_cantidad1 = $row['art_cantidad'];
			}


			$art_cantidad=$row['art_cantidad'];

			$art_venta_min=$row['art_venta_min'];



			$sql_pre=mysqli_query($con, "SELECT * from precio WHERE articulos_art_id='$art_id' and tarifas_tar_id='$tarifas_tar_id'");
			if ($rw_pre= mysqli_fetch_array($sql_pre))
			{
				$pre_precio=$rw_pre['pre_precio'];}
			else 
			{
				$pre_precio=$row['art_pvp'];
			}
?>
		<tr>
			<td>
				<input type="hidden" id="art_id<?php echo $art_id_bod; ?>" value="<?php echo $art_id; ?>">
				<input type="hidden" id="art_referencia<?php echo $art_id_bod; ?>" value="<?php echo $art_referencia; ?>">
				<input type="hidden" id="art_iva<?php echo $art_id_bod; ?>" value="<?php echo $art_iva; ?>" >
				<input type="hidden" id="precio_costo<?php echo $art_id_bod; ?>" value="<?php echo $art_precio_costo;?>">
				<?php echo mb_strtoupper(str_replace($buscar, "<strong><span style='color:".$resaltador."'>".$buscar."</span></strong>", $art_referencia ));?>
			</td>
			<td>
				<input type="hidden" id="nombre<?php echo $art_id_bod; ?>" value="<?php echo $art_nombre; ?>">
				<?php echo mb_strtoupper(str_replace($buscar, "<span style='font-weight: bold;color:".$resaltador."'>".$buscar."</span>", $art_nombre ));?>
				<span style="color: red;">
					<?php if($row["art_atributo_estado"]=='si') 
					{  
						$atributo1=$row['atributo1'];
                        $atri1=mysqli_query($con,"SELECT * FROM atributos1 where atri_art_id='$art_id' and atri_id='$atributo1'");
                        $fila1 = mysqli_fetch_array($atri1);
                        if (isset($fila1['atri_nombre'])) { echo $atri_nombre1=$fila1['atri_nombre']; }
                    	$atributo2=$row['atributo2'];
                        $atri2=mysqli_query($con,"SELECT * FROM atributos2 where atri_art_id2='$art_id' and atri_id2='$atributo2'");
                        $fila2 = mysqli_fetch_array($atri2);
                        if (isset($fila2['atri_nombre2'])) { echo ' / '; echo $atri_nombre2=$fila2['atri_nombre2']; }
                    } ?>
                </span>
             </td>
            <td><p style="text-align:right"><?php echo $art_cantidad1; ?></p></td>
			<td>
				<input type="hidden" id="art_venta_min<?php echo $art_id_bod; ?>" value="<?php echo $art_venta_min; ?>" >
				<input type="hidden" id="cantidadexistente<?php echo $art_id_bod; ?>" value="<?php echo $art_cantidad; ?>">
				<input type="hidden" id="cantidad_minima<?php echo $art_id_bod; ?>" value="<?php echo $art_venta_min; ?>">
				<input type="number" class="form-control input-sm" style="text-align:left" id="cantidad<?php echo $art_id_bod; ?>"  value="<?php echo $art_venta_min; ?>"  autocomplete="off"  min="1"  max="<?php echo $art_cantidad1; ?>" oninput="limitarCantidad(this)" >
			</td>
			<td>
				<input type="text" class="form-control input-sm" style="text-align:right" id="descuento<?php echo $art_id_bod; ?>" value="0" ></td>
			<td>
				<input type="text" class="form-control input-sm" style="text-align:right" id="precio_venta<?php echo $art_id_bod; ?>" value="<?php echo $pre_precio;?>"  <?php echo $readonly; ?> >
			</td>
			<td>
				<select id="cambio<?php echo $art_id_bod; ?>" class="form-control name_list input-sm" <?php echo $disabled_cam; ?>>
         			<option value="ven">VENDIDO</option>
        			<option value="cam">CAMBIO</option>
        			<option value="com">BONIFICACIÓN</option>
    			</select> 
			</td>

			<?php if ($bajo_cero_tat=='No') { ?>
				<td>
					<?php
						$butt=mysqli_query($con,"SELECT * from cotizacion_detalle_temp WHERE cott_art_id='$art_id' and usuario='$usu_id'");
						$col= mysqli_fetch_array($butt);
						$numrows1= mysqli_num_rows($butt);
						if ($numrows1==null){
					?>
						<span class="pull-right"><a href="#" class="btn btn-xs  btn-info" onclick="agregar('<?php echo $art_id_bod ?>')"><i class="btn-icon-only icon-plus"></i></a></span>
					<?php } else {?>
						<span class="pull-right"><a href="#" class="btn btn-xs  btn-warning" onclick="agregar('<?php echo $art_id_bod ?>')"><i class="btn-icon-only icon-plus"></i></a></span>
					<?php } ?>
				</td>
			<?php } else { ?>
				<td>
			    	<?php
			        $butt = mysqli_query($con,"SELECT * from cotizacion_detalle_temp WHERE cott_art_id='$art_id' and usuario='$usu_id'");
			        $col = mysqli_fetch_array($butt);
			        $numrows1 = mysqli_num_rows($butt);

			        // Determinar clase y estado del botón según stock y si ya está agregado
			        if ($art_cantidad1 <= 0) {
			            $btn_class = 'btn-default disabled';
			            $btn_icon = 'icon-plus';
			            $btn_title = 'Sin stock';
			            $btn_onclick = '';
			        } else {
			            if ($numrows1 == null) {
			                $btn_class = 'btn-info';
			            } else {
			                $btn_class = 'btn-warning';
			            }
			            $btn_icon = 'icon-plus';
			            $btn_title = 'Agregar';
			            $btn_onclick = "onclick=\"agregar('$art_id_bod')\"";
			        }
				    ?>
				    <span class="pull-right">
				        <a href="#" class="btn btn-xs <?php echo $btn_class; ?>" <?php echo $btn_onclick; ?> title="<?php echo $btn_title; ?>">
				            <i class="btn-icon-only <?php echo $btn_icon; ?>"></i>
				        </a>
				    </span>
				</td>
			<?php } ?>
		</tr>
<?php } } ?>

		<tr>
			<td colspan="8" ><span class="pull-right">
				<?php echo paginate($reload, $page, $total_pages, $adjacents);?></span>
			</td>
		</tr>
<?php } 

if($tipo=='detallados')
{
	$count_query=mysqli_query($con,"SELECT count(*) AS numrows FROM articulos_detallado ");
	$row= mysqli_fetch_array($count_query);
	$numrows=$row['numrows'];
	$total_pages=ceil($numrows/$per_page);
	$reload='./index.php';
	$sql="SELECT * FROM articulos_detallado where (artd_referencia like '%$q%' OR artd_nombre like '%$q%') and empresa='$empresa' LIMIT $offset,$per_page";
	$query = mysqli_query($con, $sql);
	if ($numrows>0)
	{
		while ($rowd=mysqli_fetch_array($query))
		{
			$art_id=$rowd['artd_id'];
			$artd_referencia=$rowd['artd_referencia'];
			$artd_nombre=$rowd['artd_nombre'];
			$artd_pvp=$rowd['artd_pvp'];
			$artd_iva=$rowd['artd_iva'];
			$artd_precio_costo=$rowd['artd_precio_costo'];
			$artd_cantidad=$rowd['artd_cantidad'];
			$artd_unidad=$rowd['artd_unidad'];
?>
		<tr>
			<td>
				<input type="hidden" id="art_referencia<?php echo $art_id; ?>" value="<?php echo $artd_nombre; ?>">
				<input type="hidden" id="nombre<?php echo $art_id; ?>" value="<?php echo $artd_nombre; ?>">
				<input type="hidden" id="iva<?php echo $art_id; ?>" value="<?php echo $artd_iva; ?>">
				<input type="hidden" id="precio_costo<?php echo $art_id; ?>" value="<?php echo $artd_precio_costo;?>" >

				<?php echo $artd_referencia; ?>
			</td>
			<td><?php echo $artd_nombre; ?></td>
			<td><p style="text-align:right"><?php echo $artd_cantidad; ?> (<?php echo $artd_unidad; ?>)</p></td>
			<td><input type="text" class="form-control input-sm" style="text-align:left" id="cantidad<?php echo $art_id; ?>" value="1" ></td>
			<td><input type="text" class="form-control input-sm" style="text-align:right" id="descuento<?php echo $art_id; ?>" value="0"></td>
			<td><input type="text" class="form-control input-sm" style="text-align:right" id="precio_venta<?php echo $art_id;?>" value="<?php echo $artd_pvp;?>"  <?php echo $readonly; ?> >
			</td>
			<td>
				<span class="pull-right"><a href="#" title="Agregar" class="btn btn-xs btn-info" onclick="agregardetallado('<?php echo $art_id ?>')"><i class="btn-icon-only icon-plus"></i></a></span>
			</td>
		</tr>
<?php } } ?>
		<tr>
			<td colspan="8"><span class="pull-right">
				<?php echo paginate($reload, $page, $total_pages, $adjacents);?></span>
			</td>
		</tr>
<?php } 



if($tipo=='combos')
{
	$count_query=mysqli_query($con,"SELECT count(*) AS numrows FROM combos");
	$row=mysqli_fetch_array($count_query);
	$numrows=$row['numrows'];
	$total_pages=ceil($numrows/$per_page);
	$reload='./index.php';
	$sql="SELECT * FROM combos where (com_referencia like '%$q%' OR com_nombre like '%$q%') and empresa='$empresa' LIMIT $offset,$per_page";
	$query = mysqli_query($con, $sql);
	if ($numrows>0)
	{
		while ($rowd=mysqli_fetch_array($query)){
		$com_id=$rowd['com_id'];
		$com_referencia=$rowd['com_referencia'];
		$com_nombre=$rowd['com_nombre'];
		$sumador_total=0;
		$sumador_costo=0;
		$sql1=mysqli_query($con,"SELECT * FROM combos_articulos where combos_com_id='$com_id'");
		while($row1=mysqli_fetch_array($sql1))
		{
			$coma_art_id=$row1['coma_art_id'];
			$coma_art_cantidad=$row1['coma_art_cantidad'];
			$coma_art_precio=$row1['coma_art_precio'];
			$art_pvp=$coma_art_precio*$coma_art_cantidad;

			$sql2=mysqli_query($con,"SELECT * from articulos where  art_id='$coma_art_id' ");
			$art2=mysqli_fetch_array($sql2);
			$art_precio_costo=$art2["art_precio_costo"]*$coma_art_cantidad;
							
			$sumador_costo+=$art_precio_costo;//Sumador
			$sumador_total+=$art_pvp;//Sumador
		}
?>
		<tr>
			<td><input type="hidden" id="art_referencia<?php echo $com_id; ?>" value="<?php echo $com_referencia; ?>"><?php echo $com_referencia; ?></td>
			<td><input type="hidden" id="nombre<?php echo $com_id; ?>" value="<?php echo $com_nombre; ?>" ><?php echo $com_nombre; ?></td>
			<td></td>
			<td><input type="text" class="form-control input-sm" style="text-align:left" id="cantidad<?php echo $com_id; ?>" value="1" ></td>
			<td><input type="hidden" id="descuento<?php echo $com_id; ?>" value="0"></td>
			<td><input type="text" class="form-control input-sm" style="text-align:right" id="precio_venta<?php echo $com_id; ?>" value="<?php echo $sumador_total;?>" readonly ></td>
			<td >
				<span class="pull-right"><a href="#" title="Agregar" class="btn btn-xs btn-info" onclick="agregarcombo('<?php echo $com_id ?>')"><i class="btn-icon-only icon-plus"></i></a></span>
			</td>
		</tr>
<?php } } ?>
		<tr>
			<td colspan="8" ><span class="pull-right">
				<?php echo paginate($reload, $page, $total_pages, $adjacents);?></span>
			</td>
		</tr>
<?php } 





if($tipo=='servicio')
{
	$count_query=mysqli_query($con,"SELECT count(*) AS numrows FROM articulos 
    where empresa='$empresa' and art_tipo='servicio' and (art_referencia like '%$q%' OR art_nombre like '%$q%' OR art_barras like '%$q%') ");
    $row= mysqli_fetch_array($count_query);
    $numrows=$row['numrows'];
    $total_pages=ceil($numrows/$per_page);
    $reload='../I_articulos.php';
    $sql=mysqli_query($con,"SELECT * FROM articulos 
    where empresa='$empresa' and art_tipo='servicio' and (art_referencia like '%$q%' OR art_nombre like '%$q%' OR art_barras like '%$q%') order by art_nombre desc LIMIT $offset,$per_page");
	if ($numrows>0)
	{
		while ($row=mysqli_fetch_array($sql))
		{
			$art_id=$row['art_id'];
			$art_referencia=$row['art_referencia'];
			$art_nombre=mb_strtoupper($row['art_nombre']);
			$pre_precio=$row['art_pvp'];
			$art_iva=$row['art_iva'];
			$art_precio_costo=$row['art_precio_costo'];
			$art_cantidad=0;			
?>
		<tr>
			<td>
				<input type="hidden" id="art_id<?php echo $art_id; ?>" value="<?php echo $art_id; ?>">
				<input type="hidden" id="art_referencia<?php echo $art_id; ?>" value="<?php echo $art_referencia; ?>">
				<input type="hidden" id="nombre<?php echo $art_id; ?>" value="<?php echo $art_nombre; ?>">
				<input type="hidden" id="art_iva<?php echo $art_id; ?>" value="<?php echo $art_iva; ?>" >
				<input type="hidden" id="precio_costo<?php echo $art_id; ?>" value="<?php echo $art_precio_costo;?>">
				<input type="hidden" id="tipo<?php echo $art_id; ?>" value="servicio">

				<?php echo mb_strtoupper(str_replace($buscar, "<strong><span style='color:".$resaltador."'>".$buscar."</span></strong>", $art_referencia ));?>
			</td>
			<td><?php echo mb_strtoupper(str_replace($buscar, "<strong><span style='color:".$resaltador."'>".$buscar."</span></strong>", $art_nombre ));?></td>
			<td><p style="text-align:right"><?php echo $art_cantidad; ?></p></td>
			<td><input type="text" class="form-control input-sm" style="text-align:left" id="cantidad<?php echo $art_id; ?>" value="1" ></td>
			<td><input type="text" class="form-control input-sm" style="text-align:right" id="descuento<?php echo $art_id;?>" value="0"></td>
			<td><input type="text" class="form-control input-sm" style="text-align:right" id="precio_venta<?php echo $art_id; ?>" value="<?php echo $pre_precio;?>" ></td>
			<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>
				<span class="pull-right"><a href="#" class="btn btn-xs btn-info" onclick="agregarservicio_producto('<?php echo $art_id ?>')"><i class="btn-icon-only icon-plus"></i></a></span>
			</td>
		</tr>
<?php } } ?>
		<tr>
			<td colspan="8" ><span class="pull-right">
				<?php echo paginate($reload, $page, $total_pages, $adjacents);?></span>
			</td>
		</tr>
<?php } ?>





<?php
if($tipo=='producto')
{
	$count_query=mysqli_query($con,"SELECT count(*) AS numrows FROM articulos 
    where empresa='$empresa' and art_tipo='producto' and (art_referencia like '%$q%' OR art_nombre like '%$q%' OR art_barras like '%$q%') ");
    $row= mysqli_fetch_array($count_query);
    $numrows=$row['numrows'];
    $total_pages=ceil($numrows/$per_page);
    $reload='../I_articulos.php';
    $sql=mysqli_query($con,"SELECT * FROM articulos 
    where empresa='$empresa' and art_tipo='producto' and (art_referencia like '%$q%' OR art_nombre like '%$q%' OR art_barras like '%$q%') order by art_nombre desc LIMIT $offset,$per_page");
	if ($numrows>0)
	{
		while ($row=mysqli_fetch_array($sql))
		{
			$art_id=$row['art_id'];
			$art_referencia=$row['art_referencia'];
			$art_nombre=mb_strtoupper($row['art_nombre']);
			$pre_precio=$row['art_pvp'];
			$art_iva=$row['art_iva'];
			$art_precio_costo=$row['art_precio_costo'];
			$art_cantidad=0;			
?>
		<tr>
			<td>
				<input type="hidden" id="art_id<?php echo $art_id; ?>" value="<?php echo $art_id; ?>">
				<input type="hidden" id="art_referencia<?php echo $art_id; ?>" value="<?php echo $art_referencia; ?>">
				<input type="hidden" id="nombre<?php echo $art_id; ?>" value="<?php echo $art_nombre; ?>">
				<input type="hidden" id="art_iva<?php echo $art_id; ?>" value="<?php echo $art_iva; ?>" >
				<input type="hidden" id="precio_costo<?php echo $art_id; ?>" value="<?php echo $art_precio_costo;?>">
				<input type="hidden" id="tipo<?php echo $art_id; ?>" value="producto">

				<?php echo mb_strtoupper(str_replace($buscar, "<strong><span style='color:".$resaltador."'>".$buscar."</span></strong>", $art_referencia ));?>
			</td>
			<td><?php echo mb_strtoupper(str_replace($buscar, "<strong><span style='color:".$resaltador."'>".$buscar."</span></strong>", $art_nombre ));?></td>
			<td><p style="text-align:right"><?php echo $art_cantidad; ?></p></td>
			<td><input type="text" class="form-control input-sm" style="text-align:left" id="cantidad<?php echo $art_id; ?>" value="1" ></td>
			<td><input type="text" class="form-control input-sm" style="text-align:right" id="descuento<?php echo $art_id;?>" value="0"></td>
			<td><input type="text" class="form-control input-sm" style="text-align:right" id="precio_venta<?php echo $art_id; ?>" value="<?php echo $pre_precio;?>" <?php echo $readonly; ?>></td>
			<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>
				<span class="pull-right"><a href="#" class="btn btn-xs btn-info" onclick="agregarservicio_producto('<?php echo $art_id ?>')"><i class="btn-icon-only icon-plus"></i></a></span>
			</td>
		</tr>
<?php } } ?>
		<tr>
			<td colspan="8" ><span class="pull-right">
				<?php echo paginate($reload, $page, $total_pages, $adjacents);?></span>
			</td>
		</tr>
<?php } } ?>


	</table>
</div>

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

<?php if ($bajo_cero_tat == 'Si') { ?>
<script>
function limitarCantidad(input) {
    const max = parseInt(input.max);
    let valor = parseInt(input.value) || 0;

    if (valor > max) {
        input.value = max;
    }
}
</script>
<?php } ?>
