<?php
	$seccion    = 'Marcas';
	$subseccion = 'Marca';
	$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');

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

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

    if(isset($_POST['id'])){
			$idMarca	= $_POST['id'];
		}
    $nombre				= addslashes(strip_tags($_POST['nombre']));
    $activo				= addslashes(strip_tags($_POST['activo']));

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

      //Save
      $Query = "
				INSERT INTO marcas (
					nombre, activo
				)VALUES(
					'$nombre', '$activo'
				)
			";
      $sQuery = mysqli_query($mysqli, $Query);
      $idMarca = mysqli_insert_id($mysqli);

    }
    //END Nueva Proveedor

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

      //Update
      $Query = "
      	UPDATE marcas
				SET
					nombre 				= '$nombre',
					activo				= '$activo'
				WHERE
					id = '$idMarca'
			";
      $sQuery = mysqli_query($mysqli, $Query);

    }
    //END Edita Proveedor

		//Guarda Proveedores de Marcas

		$Query = "
			DELETE
			FROM marcas_proveedores
			WHERE fk_marca = '$idMarca'
		";
		$sQuery = mysqli_query($mysqli, $Query);

		$pros = $_POST[pros];
		foreach ($pros AS $pro) {

			$Query = "
				INSERT INTO marcas_proveedores (
					fk_marca, fk_proveedor
				)VALUES(
					'$idMarca', '$pro'
				)
			";
      $sQuery = mysqli_query($mysqli, $Query);

		}
		//End Guarda Proveedores de Marcas

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

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

	    //Query's

	if(isset($_GET['id'])){

    //qrMarca
    $Query = "
			SELECT
				mar.id,
				mar.nombre,
				mar.activo
			FROM marcas mar
			WHERE mar.id = '$_GET[id]'
		";
    $rQuery  = mysqli_query($mysqli, $Query);
    $mar   = 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 Nuevo -->
										<button type="button" class="btn btn-white btn-sm" onclick="window.location.href='index.php'"><i class="fe-plus"></i>&nbsp; Nuevo</button>
										<!-- End Btn Nuevo -->

										<!-- 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 $mar[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>
										</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">

													<!-- 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 de Proveedor"
															value="<?php if(isset($mar['id'])){ echo $mar['nombre']; } ?>"
															required
															autocomplete="off"
														>
													</div>
													<!-- End Nombre -->

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

													<div class="form-group col-md-12">
														<label for="inputPu" class="col-form-label">Proveedores</label>
														<div id="Proveedores">
															<?php
																//Proveedores
																$Query = "
																	SELECT
																		pro.Id,
																		pro.fk_marca, pro.fk_proveedor
																	FROM marcas_proveedores pro
																	WHERE pro.fk_marca = '$mar[id]'
																";
																$ProsSel = $mysqli->query($Query);
																mysqli_data_seek($ProsSel, 0);
																while($ProSel = mysqli_fetch_array($ProsSel)) {
															?>
																<?php require('proveedor.php'); ?>
															<?php } ?>
														</div>
														<div style="margin-top:1em;">
															<!-- Btn Add Proveedor -->
															<button
																type="button"
																class="btn btn-white btn-sm BtnAddPro"
															>
																Agregar Proveedor &nbsp;
																<i class="fe-plus"></i>
															</button>
															<!-- End Btn Add Proveedor -->
														</div>
													</div>


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

										</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 Proveedor
			$(document.body).on('click', '.BtnAddPro' ,function(){
				console.log('test');
				$.post("proveedor.php", { action: 'add' }, function(data){
					console.log(data);
					$('#Proveedores').append(data);
				});
			});
			//End Add Proveedores

			//Del Proveedores
			$(document.body).on('click', '.BtnDelPro' ,function(){
				$(this).parents('.Proveedor').remove();
			});
			//End Del Proveedores

    </script>


  </body>

</html>
