<?php
session_start();
if (!isset($_SESSION['user_login_status']) and $_SESSION['user_login_status'] != 1) {
    header("location: ../../login.php");
    exit;
}
/* Connect To Database*/
require_once "../db.php"; //Contiene las variables de configuracion para conectar a la base de datos
require_once "../php_conexion.php"; //Contiene funcion que conecta a la base de datos
//Inicia Control de Permisos
include "../permisos.php";
$user_id = $_SESSION['id_users'];
get_cadena($user_id);
$modulo = "Productos";
permisos($modulo, $cadena_permisos);
//Finaliza Control de Permisos
$count      = mysqli_query($conexion, "select MAX(codigo_producto) as codigo from productos");
$rw         = mysqli_fetch_array($count);
$product_id = $rw['codigo'] + 1;

$query = "SELECT id_producto, nombre_producto FROM productos";
$resultado = $conexion->query($query);

$productos_options = "";
while ($fila = $resultado->fetch_assoc()) {
    $productos_options .= "<option value='{$fila['id_producto']}'>{$fila['nombre_producto']}</option>";
}
?>

<?php require 'includes/header_start.php';?>

<?php require 'includes/header_end.php';?>

<!-- Begin page -->
<div id="wrapper" class="forced enlarged"> <!-- DESACTIVA EL MENU -->

	<?php require 'includes/menu.php';?>

	<!-- ============================================================== -->
	<!-- Start right Content here -->
	<!-- ============================================================== -->
	<div class="content-page">
		<!-- Start content -->
		<div class="content">
			<div class="container">
<?php if ($permisos_ver == 1) {
    ?>
				<div class="col-lg-12">
					<div class="portlet">
						<div class="portlet-heading bg-primary">
							<h3 class="portlet-title">
								Gestion de Combos
							</h3>
							<div class="portlet-widgets">
								<a href="javascript:;" data-toggle="reload"><i class="ion-refresh"></i></a>
								<span class="divider"></span>
								<a data-toggle="collapse" data-parent="#accordion1" href="#bg-primary"><i class="ion-minus-round"></i></a>
								<span class="divider"></span>
								<a href="#" data-toggle="remove"><i class="ion-close-round"></i></a>
							</div>
							<div class="clearfix"></div>
						</div>
						<div id="bg-primary" class="panel-collapse collapse show">
							<div class="portlet-body">

<?php
if ($permisos_editar == 1) {
        include '../modal/registro_combo.php';
        include "../modal/editar_combo.php";
        include "../modal/eliminar_producto.php";
    }
    ?>

								<form class="form-horizontal" role="form" id="datos_cotizacion">
									<div class="form-group row">
										<div class="col-md-4">
											<div class="input-group">
												<input type="text" class="form-control" id="q" placeholder="Código o Nombre" onkeyup='load(1);'>
												<span class="input-group-btn">
													<button type="button" class="btn btn-info waves-effect waves-light" onclick='load(1);'>
														<span class="fa fa-search" ></span> Buscar</button>
													</span>
												</div>
											</div>
                                            <div class="col-md-3">
												<div class="btn-group pull-right">
												<button type="button" class="btn btn-success waves-effect waves-light" data-toggle="modal" data-target="#nuevoProducto"><i class="fa fa-plus"></i> Agregar Combo</button>
												</div>

											</div>
											<div class="col-md-3">
												<span id="loader"></span>
											</div>
										</div>
									</form>
									<div class="datos_ajax_delete"></div><!-- Datos ajax Final -->
									<div class='outer_div'></div><!-- Carga los datos ajax -->



								</div>
							</div>
						</div>
					</div>
					<?php
} else {
    ?>
		<section class="content">
			<div class="alert alert-danger" align="center">
				<h3>Acceso denegado! </h3>
				<p>No cuentas con los permisos necesario para acceder a este módulo.</p>
			</div>
		</section>
		<?php
}
?>

				</div>
				<!-- end container -->
			</div>
			<!-- end content -->

			<?php require 'includes/pie.php';?>

		</div>
		<!-- ============================================================== -->
		<!-- End Right content here -->
		<!-- ============================================================== -->


	</div>
	<!-- END wrapper -->

	<?php require 'includes/footer_start.php'
?>
	<!-- ============================================================== -->
	<!-- Todo el codigo js aqui-->
	<!-- ============================================================== -->

	<script type="text/javascript" src="../../js/combos.js"></script>
	<script>
 function precio_venta(){
    var profit = $("#utilidad").val();
    var buying_price = $("#costo").val();

    var parametros = {"utilidad":profit,"costo":buying_price};
    $.ajax({
        dataType: "json",
        type:"POST",
        url:'../ajax/precio.php',
        data: parametros,
         success:function(data){
          //$("#datos").html(data).fadeIn('slow');
         $.each(data, function(index, element) {
          var precio= element.precio;
          $("#precio").val(precio);
                });


        }
      })
  }
   function precio_venta_edit(){
    var profit = $("#mod_utilidad").val();
    var buying_price = $("#mod_costo").val();

    var parametros = {"mod_utilidad":profit,"mod_costo":buying_price};
    $.ajax({
        dataType: "json",
        type:"POST",
        url:'../ajax/precio.php',
        data: parametros,
         success:function(data){
          //$("#datos").html(data).fadeIn('slow');
         $.each(data, function(index, element) {
          var mod_precio= element.mod_precio;
          $("#mod_precio").val(mod_precio);
                });


        }
      })
  }

  </script>
  <script>
       $(document).ready( function () {
        $(".UpperCase").on("keypress", function () {
         $input=$(this);
         setTimeout(function () {
          $input.val($input.val().toUpperCase());
         },50);
        })
       })
      </script>
     <!-- Primera función: upload_image -->
<script>
function upload_image(product_id) {
	$("#load_img").text('Cargando...');
	var inputFileImage = document.getElementById("imagefile");
	var file = inputFileImage.files[0];
	var data = new FormData();
	data.append('imagefile', file);

	$.ajax({
		url: "../ajax/imagen_product_ajax.php",
		type: "POST",
		data: data,
		contentType: false,
		cache: false,
		processData: false,
		success: function(data) {
			$("#load_img").html(data);
		}
	});
}
</script>

<!-- Segunda función: upload_image_mod -->
<script>
function upload_image_mod(id_producto) {
	$("#load_img_mod").text('Cargando...');
	var inputFileImage = document.getElementById("imagefile_mod");
	var file = inputFileImage.files[0];
	var data = new FormData();
	data.append('imagefile_mod', file);
	data.append('id_producto', id_producto);

	$.ajax({
		url: "../ajax/imagen_product_ajax2.php",
		type: "POST",
		data: data,
		contentType: false,
		cache: false,
		processData: false,
		success: function(data) {
			$("#load_img_mod").html(data);
		}
	});
}
</script>

<!-- Tercera función: carga_img -->
<script>
function carga_img(id_producto) {
	$(".outer_img").load("../ajax/img.php?id_producto=" + id_producto);
}
</script>

		
	<script type="text/javascript">
  	$(function(){

  $('.number-only').keyup(function(e) {
        if(this.value!='-')
          while(isNaN(this.value))
            this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
                                   .split('').reverse().join('');
    })
    .on("cut copy paste",function(e){
        e.preventDefault();
    });

});

let productosOptions = `<?php echo $productos_options; ?>`;

$("#agregarProducto").click(function () {
    let fila = `
    <div class="row mb-3 align-items-center producto-item">
        <div class="col-md-6">
            <select class="form-control select2" name="producto[]">
                <option value="">Seleccione un producto</option>
                ${productosOptions}
            </select>
        </div>
        <div class="col-md-4">
            <input type="number" class="form-control" name="cantidad[]" placeholder="Cantidad" min="1">
        </div>
        <div class="col-md-2">
            <button type="button" class="btn btn-danger eliminarProducto"><i class="fa fa-trash"></i></button>
        </div>
    </div>
    `;

    // Agregar la fila al contenedor
    $("#productos").append(fila);

    // Inicializar Select2 en el nuevo <select>
    $('.select2').last().select2({
        placeholder: "Buscar producto...",
        allowClear: true,
        width: '100%'
    });
});

// Eliminar producto dinámicamente
$(document).on("click", ".eliminarProducto", function () {
	$(this).closest(".producto-item").remove();
});

  </script>
	<?php require 'includes/footer_end.php'
?>

