<?php
	$seccion    = 'Articulos';
	$subseccion = 'Articulo';
	$position   = '../../';

	require_once($position.'../switch/access.php');
	require_once($position.'assets/global.php');
	require_once($position.'assets/session.php');
	require_once($position.'assets/funciones.php');
	require_once($position.'assets/resize-class.php');

	$RootSite = $_SERVER['DOCUMENT_ROOT'];
	$UrlImg = "sandbox/switchpoint-app/articulos";

	if (isset($_GET['id'])){ $tipoAccion="editar"; }else{ $tipoAccion="nuevo"; }

	/* Usuario */
	if(isset($_POST['save'])== 'Ok'){

    if(isset($_POST['id'])){
			$idArticulo	= $_POST['id'];
		}
		$codigo				= addslashes(strip_tags($_POST['codigo']));
		$sku					= addslashes(strip_tags($_POST['sku']));
		$nombre				= addslashes(strip_tags($_POST['nombre']));
		$descripcion  = addslashes(strip_tags($_POST['descripcion']));
		$proveedor  	= addslashes(strip_tags($_POST['proveedor']));
		$marca		  	= addslashes(strip_tags($_POST['marca']));
		$categoria  	= addslashes(strip_tags($_POST['categoria']));
		$principal   	= addslashes(strip_tags($_POST['principal']));
		$activo				= addslashes(strip_tags($_POST['activo']));

		$Precios                    = $_POST['Precios'];
    $Precio                     = $_POST['Precio'];

    //Nueva Encuesta
    if( $_POST['action'] == 'nuevo' ){

      //Save
      $Query = "
				INSERT INTO articulos (
					codigo, sku,
					nombre, descripcion,
					fk_proveedor, fk_marca,
					fk_articulo_categoria,
					principal, activo
				)VALUES(
					'$codigo', '$sku',
					'$nombre', '$descripcion',
					'$proveedor', '$marca',
					'$categoria',
					'$principal', '$activo'
				)
			";
      $Result = mysqli_query($mysqli, $Query);
      $idArticulo = mysqli_insert_id($mysqli);

    }
    //END Nueva Encuesta

    //Edita Encuesta
    if( $_POST['action'] == 'editar' ){

      //Update
      $Query = "
      	UPDATE articulos
				SET
					codigo									= '$codigo',
					sku											= '$sku',
					nombre									= '$nombre',
					descripcion							= '$descripcion',
					fk_proveedor						= '$proveedor',
					fk_marca								= '$marca',
					fk_articulo_categoria		= '$categoria',
					principal  							= '$principal',
					activo									= '$activo'
				WHERE
					id = '$idArticulo'
			";
      $Result = mysqli_query($mysqli, $Query);

    }
    //END Edita Encuesta

		//Guarda Rangos de Precios
    //Update Precios Borrar
    $Query = "
      UPDATE articulos_precios
      SET
        borrar = '1'
      WHERE fk_articulo = '$idArticulo'
    ";
    $Result = mysqli_query($mysqli, $Query);

    foreach( $Precios AS $Pre ){

      $PreId  = $Precio[$Pre]['Id'];
      $Var    = $Precio[$Pre]['Variante'];
      $Preci  = $Precio[$Pre]['Precio'];
      $RangoA = $Precio[$Pre]['RangoA'];
      $RangoB = $Precio[$Pre]['RangoB'];
      $Action = $Precio[$Pre]['Action'];

      //New
      if( $Action == 'New' ){

        //Insert
        $Query = "
          INSERT INTO articulos_precios
          (
            fk_articulo,
            precio,
            rango_a, rango_b,
						borrar
          )
          VALUES (
            '$idArticulo',
            '$Preci',
            '$RangoA', '$RangoB',
						'0'
          )
        ";
        $Result = mysqli_query($mysqli, $Query);

      }
      //End New

      //Edit
      if( $Action == 'Edit' ){

        //Update
        $Query = "
          UPDATE articulos_precios
          SET
						precio = '$Preci',
            rango_a = '$RangoA', rango_b = '$RangoB',
            borrar = '0'
          WHERE id = '$PreId'
            AND fk_articulo = '$idArticulo'
        ";
        $Result = mysqli_query($mysqli, $Query);

      }
      //End Edit

    }

    //Borrar
    $Query = "
      DELETE FROM articulos_precios
      WHERE
				fk_articulo = '$idArticulo'
				AND Borrar = '1'
    ";
    $Result = mysqli_query($mysqli, $Query);

    //End Guarda Rangos de Precios

		//Carga Imagen
		$Imagen = "logo";
    if(empty($_FILES[$Imagen]['name'])){}else{
      $_FILES[$Imagen]["name"];
      $allowedExts = array("JPEG", "jpeg", "jpg", "JPG");
      $temp = explode(".", $_FILES[$Imagen]["name"]);
      $extension = end($temp);
      if((
      ($_FILES[$Imagen]["type"] == "image/jpeg")
      || ($_FILES[$Imagen]["type"] == "image/jpg")
      || ($_FILES[$Imagen]["type"] == "image/JPEG")
      || ($_FILES[$Imagen]["type"] == "image/JPG")
      )
      && ($_FILES[$Imagen]["size"] < 10000000)
      && in_array($extension, $allowedExts)) {
      if ($_FILES[$Imagen]["error"] > 0) {
      }else{

        //RootSite del Sitio Seleccionado
				// echo "<hr>";
        $ImageUp 	= $RootSite.'/'.$UrlImg."/".$idArticulo.".jpg";
				$ImageUpM = $RootSite.'/'.$UrlImg."/".$idArticulo."-m.jpg";
				// echo "<hr>";

        if ( move_uploaded_file($_FILES[$Imagen]["tmp_name"], $ImageUp) ){
          //echo "Img Up";
          chmod($ImageUp, 0777);
          //Ajuste de tamaño
          $width = getWidth($ImageUp);
          $height = getHeight($ImageUp);
          $max_width = "1800";
          if ($width > $max_width){
            $scale = $max_width/$width;
            $resizeObj = new resize($ImageUp);
            $resizeObj -> resizeImage(500, 500, 'crop');
            $resizeObj -> saveImage($ImageUp, 70);
          }else{
            $scale = 1;
            $resizeObj = new resize($ImageUp);
            $resizeObj -> resizeImage(500, 500, 'crop');
            $resizeObj -> saveImage($ImageUp, 70);
          }

					if ( copy($ImageUp, $ImageUpM) ){
						chmod($ImageUpM, 0777);
	          //Ajuste de tamaño
	          $width = getWidth($ImageUpM);
	          $height = getHeight($ImageUpM);
	          $max_width = "1800";
	          if ($width > $max_width){
	            $scale = $max_width/$width;
	            $resizeObj = new resize($ImageUpM);
	            $resizeObj -> resizeImage(200, 200, 'crop');
	            $resizeObj -> saveImage($ImageUpM, 70);
	          }else{
	            $scale = 1;
	            $resizeObj = new resize($ImageUpM);
	            $resizeObj -> resizeImage(200, 200, 'crop');
	            $resizeObj -> saveImage($ImageUpM, 70);
	          }
					}


        }else{
          //echo "Img Not<br>";
          print_r(error_get_last());
        }

      }}else{
      }
    }
		//End Carga Imagen

		if( $idArticulo && $_POST['action'] == 'nuevo' ){
			echo '<script type="text/javascript">document.location.href="index.php?id='.$idArticulo.'&sv=1"</script>';
		}
		if( $idArticulo && $_POST['action'] == 'editar' ){
			$sv = 1;
		}

	}//End if save
	/* END Usuario  */

	//Query's
	if(isset($_GET['id'])){

    //Articulo
    $Query = "
			SELECT
				art.id,
				art.nombre,
				art.codigo,
				art.sku,
				art.descripcion,
				art.fk_proveedor, art.fk_marca,
				art.fk_articulo_categoria,
				art.principal, art.activo
			FROM articulos art
			WHERE art.id = '$_GET[id]'
		";
    $rQuery  = mysqli_query($mysqli, $Query);
    $Art   = mysqli_fetch_assoc($rQuery);

	}
?>
<!DOCTYPE html>
<html lang="es_MX">
  <?php require_once($position.'head.php'); ?>


  <body class="loading" data-layout='{"mode": "light", "width": "fluid", "menuPosition": "fixed", "sidebar": { "color": "dark", "size": "default", "showuser": false}, "topbar": {"color": "light"}, "showRightSidebarOnPageLoad": false}'>

    <!-- Pagina de inicio -->
    <div id="wrapper">

      <!-- ========== Inicio nav-izq ========== -->
      <?php include_once($position.'assets/nav.php'); ?>
      <!-- Fin nav-izq -->

      <!-- ============================================================== -->
      <!-- Incio de Contenido -->
      <!-- ============================================================== -->

      <div class="content-page">
        <div class="content">

          <!-- Topbar -->
          <?php include_once($position.'assets/topbar.php'); ?>
          <!-- /Topbar -->

            <!-- Content-->
            <div class="container-fluid">
              <form method="post" enctype="multipart/form-data" class="parsley-examples" novalidate>

								<!-- page title -->
								<div class="row">
								  <div class="col-12">
								    <div class="page-title-box">
								      <h4 class="page-title"><?php echo $seccion; ?></h4>
								      <div class="page-title-right">
								        <ol class="breadcrumb m-0">
								          <?php
								            foreach ($SecLine as $i => $value) {
								          ?>
								            <li class="breadcrumb-item">
								              <a href="<?php echo $SecPos[$i]; ?>">
								                <?php echo $value; ?>
								              </a>
								            </li>
								          <?php } ?>
								        </ol>
								      </div>
								    </div>
								  </div>
								</div>
								<!-- /page title -->

								<!-- Botones -->
								<div class="row">
									<div class="col-12 text-right">

										<!-- Btn Regresar -->
										<button type="button" class="btn btn-white btn-sm" onclick="window.location.href='../'"><i class="fe-arrow-left"></i>&nbsp; Regresar</button>
										<!-- End Btn Regresar -->

										<!-- Btn Guardar -->
										<button type="submit" class="btn btn-success btn-sm">Guardar <i class="fe-check"></i></button>
										<!-- End Btn Guardar -->

										<input type="hidden" class="form-control" name="save" value="Ok">
										<input type="hidden" class="form-control" name="id" value="<?php echo $Art[id]; ?>">
										<input type="hidden" class="form-control" name="action" value="<?php echo $tipoAccion; ?>">

									</div>
									<div class="col-12" style="height: 5px;">&nbsp;</div>
								</div>
								<!-- End Botones -->

								<!-- Row -->
                <div class="row">
                  <div class="col-md-12">

										<!-- Nav tabs -->
										<ul class="nav nav-tabs tabcontent-border" role="tablist">
											<li class="nav-item">
												<a class="nav-link active" data-toggle="tab" href="#Informacion" role="tab">
													<span class="hidden-sm-up"><i class="ti-user"></i></span>
													<span class="hidden-xs-down">Información</span>
												</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-toggle="tab" href="#Imagen" role="tab">
													<span class="hidden-sm-up"><i class="ti-user"></i></span>
													<span class="hidden-xs-down">Imagen</span>
												</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-toggle="tab" href="#Precios" role="tab">
													<span class="hidden-sm-up"><i class="ti-user"></i></span>
													<span class="hidden-xs-down">Precios</span>
												</a>
											</li>
										</ul>
										<!-- End Nav tabs -->

										<!-- Tabs Content -->
										<div class="tab-content tabcontent-border">

											<!-- Tab Información -->
											<div class="tab-pane card-body active" id="Informacion" role="tabpanel">
												<div class="row">

													<!-- Codigo -->
													<div class="form-group col-md-12">
														<label for="inputPu" class="col-form-label">Código<span class="text-danger">*</span></label>
														<input
															type="text"
															class="form-control"
															name="codigo"
															placeholder="codigo"
															value="<?php if(isset($Art['id'])){ echo $Art['codigo']; } ?>"
															required
															autocomplete="off"
														>
													</div>
													<!-- End Codigo -->

													<!-- Sku -->
													<div class="form-group col-md-12">
														<label for="inputPu" class="col-form-label">Sku<span class="text-danger">*</span></label>
														<input
															type="text"
															class="form-control"
															name="sku"
															placeholder="codigo"
															value="<?php if(isset($Art['id'])){ echo $Art['sku']; } ?>"
															autocomplete="off"
														>
													</div>
													<!-- End Sku -->

													<!-- Nombre -->
													<div class="form-group col-md-12">
														<label for="inputPu" class="col-form-label">Nombre<span class="text-danger">*</span></label>
														<input
															type="text"
															class="form-control"
															name="nombre"
															placeholder="Nombre"
															value="<?php if(isset($Art['id'])){ echo $Art['nombre']; } ?>"
															required
															autocomplete="off"
														>
													</div>
													<!-- End Nombre -->

													<!-- Descripcion -->
													<div class="form-group col-md-12">
														<label for="inputPu" class="col-form-label">Descripción<span class="text-danger">*</span></label>
														<textarea
															type="text"
															class="form-control"
															name="descripcion"
															placeholder="descripcion"
															required
															autocomplete="off"
														><?php if(isset($Art['id'])){ echo $Art['descripcion']; } ?></textarea>
													</div>
													<!-- End Descripcion -->

													<!-- Categoria -->
													<div class="form-group col-md-12">
														<label for="inputPu" class="col-form-label">Categoría<span class="text-danger">*</span></label>
														<select name="categoria" class="form-control chosen-select">
										          <option></option>
										          <?php
										            //Proveedores
										            $Query = "
										              SELECT
										                cat.id, cat.categoria
										              FROM cat_articulos_categorias cat
										              ORDER BY cat.categoria ASC
										            ";
										            $Cats = $mysqli->query($Query);
										            mysqli_data_seek($Cats, 0);
										            while($Cat = mysqli_fetch_array($Cats)) {
										          ?>
										            <option
										              <?php
										                if( $Cat['id'] == $Art['fk_articulo_categoria'] ){
										                  echo 'selected="selected"';
										                }
										              ?>
										              value="<?php echo $Cat['id']; ?>"
										            >
										            <?php echo $Cat['categoria']; ?>
										            </option>
										          <?php } ?>
										        </select>
													</div>
													<!-- End Categoria -->

													<!-- Proveedor -->
													<div class="form-group col-md-12">
														<label for="inputPu" class="col-form-label">Proveedor<span class="text-danger">*</span></label>
														<select name="proveedor" class="form-control chosen-select Sel_Pro">
										          <option></option>
										          <?php
										            //Proveedores
										            $Query = "
										              SELECT
										                pro.id, pro.nombre
										              FROM proveedores pro
										              ORDER BY pro.nombre ASC
										            ";
										            $Pros = $mysqli->query($Query);
										            mysqli_data_seek($Pros, 0);
										            while($Pro = mysqli_fetch_array($Pros)) {
										          ?>
										            <option
										              <?php
										                if( $Pro['id'] == $Art['fk_proveedor'] ){
										                  echo 'selected="selected"';
										                }
										              ?>
										              value="<?php echo $Pro['id']; ?>"
										            >
										            <?php echo $Pro['nombre']; ?>
										            </option>
										          <?php } ?>
										        </select>
													</div>
													<!-- End Proveedor -->

													<!-- Marca -->
													<div class="form-group col-md-12">
														<label for="inputPu" class="col-form-label">Marca<span class="text-danger">*</span></label>
														<select name="marca" class="form-control chosen-select Sel_Pro">
										          <option></option>
										          <?php
										            //Marcas
										            $Query = "
										              SELECT
										                mar.id, mar.nombre
										              FROM marcas mar
																	LEFT JOIN marcas_proveedores pro ON pro.fk_marca = mar.id
																	WHERE pro.fk_proveedor = '$Art[fk_proveedor]'
										              ORDER BY mar.nombre ASC
										            ";
										            $Mars = $mysqli->query($Query);
										            mysqli_data_seek($Mars, 0);
										            while($Mar = mysqli_fetch_array($Mars)) {
										          ?>
										            <option
										              <?php
										                if( $Mar['id'] == $Art['fk_marca'] ){
										                  echo 'selected="selected"';
										                }
										              ?>
										              value="<?php echo $Mar['id']; ?>"
										            >
										            <?php echo $Mar['nombre']; ?>
										            </option>
										          <?php } ?>
										        </select>
													</div>
													<!-- End Marca -->

													<!-- Principal -->
													<div class="form-group col-md-12">
														<label for="inputNo" class="col-form-label">Principal<span class="text-danger">*</span></label>
														<select name="principal" class="form-control" required>
																<option <?php if( $Art['id']){ if( $Art['principal'] == 1 ){ echo "selected='selected'"; } } ?> value="1">Si</option>
																<option <?php if( $Art['id']){ if( $Art['principal'] == 0 ){ echo "selected='selected'"; } } ?> value="0">No</option>
														</select>
													</div>
													<!-- End Principal -->

													<!-- Activo -->
													<div class="form-group col-md-12">
														<label for="inputNo" class="col-form-label">Activo<span class="text-danger">*</span></label>
														<select name="activo" class="form-control" required>
																<option <?php if( $Art['id']){ if( $Art['activo'] == 1 ){ echo "selected='selected'"; } } ?> value="1">Si</option>
																<option <?php if( $Art['id']){ if( $Art['activo'] == 0 ){ echo "selected='selected'"; } } ?> value="0">No</option>
														</select>
													</div>
													<!-- End Activo -->

												</div>
											</div>
											<!-- End Tab Información -->

											<!-- Tab Imagen -->
											<div class="tab-pane card-body" id="Imagen" role="tabpanel">
												<h4 class="card-title">Imagen</h4>
												<div class="row">
													<div class="col-sm-6">
														<?php
															$ImageFirm = $RootSite.'/sandbox/switchpoint-app/articulos/'.$Art[id].'.jpg';
															// if (file_exists($ImageFirm)) {
														?>
															<div
																style="
																	border:1px solid #999;
																	position: relative;
																"
															>
																<img
																	class="ImgLogo img-responsive"
																	style="max-width: 300px;"
																	src="<?php echo $position; ?>../articulos/<?php echo $Art[id]; ?>.jpg"
																/>
																<img
																	class="ImgLogo img-responsive"
																	style="max-width: 150px;"
																	src="<?php echo $position; ?>../articulos/<?php echo $Art[id]; ?>-m.jpg"
																/>
															</div>

														<?php //} ?>
														<label>
															La imagen debe estan en formato jpg a 500 px de ancho por 500 px de alto.
														</label>
														<input class="form-control /*dropify*/" type="file" name="logo" />
													</div>
												</div>
											</div>
											<!-- End Tab Imagen -->

											<!-- Tab Precios -->
											<div class="tab-pane card-body" id="Precios" role="tabpanel">
												<div class="row">

													<div class="col-sm-12 Precios">
														<?php
	                            //Rangos de Precios
	                            $Query = "
	                              SELECT
	                                pre.id, pre.precio,
	                                pre.rango_a, pre.rango_b
	                              FROM articulos_precios pre
	                              WHERE pre.fk_articulo = '$Art[id]'
	                              ORDER BY pre.rango_a ASC
	                            ";
	                            $Precios = $mysqli->query($Query);
	                            mysqli_data_seek($Precios, 0);
	                            while($Precio = mysqli_fetch_array($Precios)) {
	                              $Action = 'Edit';
	                          ?>
	                            <?php require('precios.php'); ?>
	                          <?php } ?>
													</div>

													<div class="col-sm-12">
														<button
															type="button"
															class="btn btn-sm btn-white BtnAddPrecio"
														>
															Agregar Precio
															<i class="fa fa-plus"></i>
														</button>
													</div>

												</div>
											</div>
											<!-- End Tab Precios -->

										</div>
										<!-- End Tabs Content -->

                  </div>
                </div>
								<!-- End Row -->

              </form>
            </div> <!-- /Content -->

          </div> <!-- /content -->

          <!-- Footer -->
          <?php include_once($position.'assets/footer.php'); ?>
          <!-- /Footer -->

        </div>

      <!-- ============================================================== -->
      <!-- Fin de Contenido -->
      <!-- ============================================================== -->

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

  	<?php require_once($position.'scripts.php'); ?>

    <!-- save -->
    <script>
      <?php if( $_GET['sv'] == '1' || $sv == '1' ){ ?>
        $( document ).ready(function(){
	        Swal.fire({
            //position:"top-end",
            type:"success",
            title:"Elemento guardado correctamente.",
            showConfirmButton:!1,timer:2500
	        });
        });
      <?php } ?>
      <?php if( $_GET['sv'] == '2' ){ ?>
        $( document ).ready(function(){
	        Swal.fire({
	            type:"error",
	            title:"Oops...",
	            text:"El No. Telefónico ya fue registrado con anterioridad, ingresa un nuevo teléfono de contacto",
	            confirmButtonClass:"btn btn-confirm mt-2",
	            //footer:'<a href="">Why do I have this issue?</a>'
	        });
        });
      <?php } ?>

			//Add Pregunta
			var segcontpregs = <?php if( $SegPre ){ echo $SegPre; }else{ echo '0'; } ?>;
			$(document.body).on('click', '.BtnAddPregunta' ,function(){
				var Preguntas = $('.Preguntas');
				var cont = $(this).val();
				// $('#FormPer').parsley().destroy();
				segcontpregs = segcontpregs + 1;
				action = 'New';
				$.post("pregunta.php", { seg: segcontpregs, cont: cont, action: action }, function(data){
					Preguntas.append(data);
					// $(".chosen-select").chosen();
					// $('.chosen-select').trigger("chosen:updated");
					// $('#FormPer').parsley();
				});
			});
			//End Add Pregunta

			//DelPregunta
			$(document.body).on('click', '.DelPregunta' ,function(){
				$(this).parents('.Pregunta').remove();
			});
			//End DelPregunta

			//Cambio de Tipo de Pregunta
			$(document.body).on('change', '.PreguntaTipo' ,function(){
				Pregunta = $(this);
				$("option:selected", this).each(function () {
				  opc = $(this).val();
				  if( opc == '2' || opc == '3' ){
				    Pregunta.parents('.Pregunta').find('.Opciones').show();
				    Pregunta.parents('.Pregunta').find('.BtnAddOpcion').show();
				  }else{
						Pregunta.parents('.Pregunta').find('.Opciones').hide();
				    Pregunta.parents('.Pregunta').find('.BtnAddOpcion').hide();
					}
				});
			});
			//End Cambio de Tipo de Pregunta

			//Add Opciones
			$(document.body).on('click', '.BtnAddOpcion' ,function(){
				var idpreg = $(this).data('id');
				Opciones = $(this).parents('.Pregunta').find('.Opciones');
				$.post("opcion.php", { idpreg: idpreg }, function(data){
					Opciones.append(data);
				});
			});
			//End Add Opciones

			//DelOpcion
			$(document.body).on('click', '.DelOpcion' ,function(){
				$(this).parents('.Opcion').remove();
			});
			//End DelOpcion

			//Agregar Rango de Precios
      var idcontpre = <?php if( $MaxIdPrecios[Id] ){ echo $MaxIdPrecios[Id]; }else{ echo '0'; } ?>;
      $(document.body).on('click', '.BtnAddPrecio' ,function(){
        // $('#FormPer').parsley().destroy();
        idcontpre = idcontpre + 1;
        action = 'New';
        Rute = "precios.php";
        $.post(Rute, { val: idcontpre, art: '<?php echo $Art[Id]; ?>', action: action }, function(data){
          $('.Precios').append(data);
          // $(".chosen-select").chosen();
          // $('.chosen-select').trigger("chosen:updated");
          // $('#FormPer').parsley();
        });
      });
      //Agregar Rango de Precios

			//Retira ItemOpc
      $(document.body).on('click', '.DelItemOpc' ,function(){
        console.log('....');
        // $('#FormPer').parsley().destroy();
        $(this).parents('.ItemOpc').remove();
        // $('#FormPer').parsley();
      });
      //End Retira ItemOpc

    </script>


  </body>

</html>
