<?php $r="../";
require_once($r."inc/funciones.php");
validNotSession($r);
$mysqli = connectDB($r);
$_GET['error'];
$_GET['msn'];
$spe=$_SESSION['perfil'];
if($spe!=$pru && $spe!=$psu){ exit(header("Location:".$r."dashboard.php?error=NO TIENES PERMISO PARA ESTA SECCION"));}
?>
<!DOCTYPE html>
<html lang="es">
  <?php include $r."inc/head.php"; ?>
  
<script type="text/javascript">
function EliminarFila(menos,id) {
    var n = id.toString();
    idx = array.indexOf(n);
    array.splice(idx, 1);
    console.log(array);
    $("#trow" + id).remove();
    total= parseInt(total) - parseInt(menos);
    $("#total").html(total);
}
</script>
<body>
      <?php include "nav.php"; ?>
  <div class="container-fluid">
      <button id="btnagregar" class="btn btn-primary btn-block <? if($spe!=$pcl){ ?>d-none<?}?>" data-toggle="modal" data-target="#exampleModal"><i class="fa fa-plus"></i> Agregar</button>
      <hr/>
      <form id="formulario" class="pedido" name="pedido" method="POST" action="acciones.php">
          <input type="hidden" name="pedir" value="pedir">
          <input type="hidden" name="idrutero" value="<? echo $idrutero?>">
        <div class="form-group row">
          <label for="cliente" class="col-sm-2 col-form-label">Cliente</label>
          <div class="col-sm-8">
              <select data-placeholder="Seleccionar Cliente" class="chosen-select col-sm-8" name="cliente" id="cliente">
                    <? $resultado = $mysqli->query("SELECT * FROM z_clientes WHERE eliminado=0 AND tipocliente=3");
                  do{echo '<option value="'.$fila["id"].'"> '.$fila["nombre"].'</option>';
                    }while ($fila = $resultado->fetch_assoc()); ?>
              </select>
               </div>
          <div class="col-sm-2" id="pedanterior"></div>
        </div>
        <style>
            .table td, .table th {padding-left: 0.125rem  !important;padding-right: 0.125rem !important;}
        </style>
        <table class="table">
          <thead>
            <tr>
              <th>Nombre Producto</th>
              <th>Cantidad</th>
              <th>Precio</th>
              <th>Total</th>
              <th>Accion</th>
            </tr>
          </thead>
          <tfoot>
            <tr>
                <td colspan="3" class="text-right h6"><b>TOTAL</b></td>
                <td class="text-danger h6">$ <span id="total">0</span> COP</td>
                <td></td>
           </tr>
          </tfoot>
          <tbody id="tabla"></tbody>
        </table>
        <div id="total"></div>
        <div class="form-group row">
          <label for="cliente" class="col-sm-2 col-form-label">Fecha de Entrega</label>
          <div class="col-sm-3"><? $fecha=date("Y-m-d"/*, strtotime("+1 days")*/); ?>
            <input type="date" class="form-control" name="fecha"  min="<? echo date("Y-m-d"); ?>" value="<? echo $fecha; ?>" required>
          </div>
          <label for="nota" class="col-sm-1 col-form-label">Nota</label>
          <div class="col-sm-6">
            <textarea type="text" class="form-control" name="nota"></textarea>
          </div>
        </div>
        <input type="submit" class="btn btn-primary btn-sm btn-block" value="Finalizar Pedido">
      </form>
                <!-- Logout Modal-->
          <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
             <div class="modal-content">
                <div id="mesage"></div>
              <div class="modal-header" style="padding-top:0px;padding-bottom:0px;">
                <h5 class="modal-title" id="exampleModalLabel">Agregar Producto</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              </div>
                <div class="modal-body">
                <form id="añadir" method="post" action="">
                  <div class="form-group row">
                    <label for="recipient-name" class="col-sm-3 col-form-label">Producto:</label>
                    <div class="col-sm-9">
                        <select data-placeholder="Choose a Country" class="chosen-select form-control" name="producto"  required>
                            <? $productos = $mysqli->query("SELECT * FROM z_productos WHERE tienda!=0"); 
                            echo '<option value="">Seleccione Un Producto</option>';
                            while ($pro = $productos->fetch_assoc()){echo '<option value="'.$pro["id"].'">'.$pro["codigo"].'-'.$pro["producto"].'</option>';
                            } ?>
                        </select>
                    </div>
                  </div>
                  <div class="form-group row">
                    <label for="cantidad" class="col-sm-3 col-form-label">Cantidad:</label>
                    <div class="col-sm-9"><input class="form-control" type="number" id="cantidad" name="cantidad" placeholder="cantidad" title="cantidad" min="1" required></div>
                  </div>
                  <div class="form-group">
                    <button type="button" class="btn float-left btn-danger btn-sm" data-dismiss="modal" aria-label="Close">CERRAR</button>
                    <button type="submit" value="Enviar" class="btn float-right btn-success btn-sm">AGREGAR</button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
        


    <!-- Modal -->
    <div class="modal fade" id="modalpedido" tabindex="-1" role="dialog" aria-labelledby="modalpedidoLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="modalpedidoLabel">Pedido anterior<span id="code"></span></h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <form id="memoria">
          </form>
        </div>
      </div>
    </div>
</div>
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready( function() {   // Esta parte del código se ejecutará automáticamente cuando la página esté lista.
var total = 0;
var totid = 0;
var array = ['0'];
var id = '';
var pro = '';
var pre = '';
var can = '';
var bod = '';
    $( "#añadir" ).submit(function( event ) {
        
        var idcliente=document.getElementById("cliente").value;
      event.preventDefault();
      var formData = $(this).serialize();
       var url = "/admin/pedido/producto.php"; // El script a dónde se realizará la petición.
    $.ajax({
           type: "POST",
           url: url,
           data: $("#añadir").serialize(), // Adjuntar los campos del formulario enviado.
           success: function(response)
           {   
               var jsonData = JSON.parse(response);
                /*for (var i = 0; i < jsonData.counters.length; i++) {
                    var counter = jsonData.counters[i];
                    console.log(counter.counter_name);
                }*/
                var id = jsonData[0].rid;
                var pro = jsonData[0].rpro;
                var pre = jsonData[0].rpre;
                var can = parseInt(jsonData[0].rcan);
                var iva = jsonData[0].riva;
                var bod = parseInt(jsonData[0].rbod);
                var totid = jsonData[0].rtotid;
                 if (array.indexOf(id) === -1) {
                        array.push(id);
                //alert(response[i].rid);
                /*console.log(response);*/
                //alert("Hello! I am an alert box!!"+ id + pro +pre+ can);
                        array.push(id);
                        var tr_str = '<tr id="trow'+id+'">' +
                        '<td><input type="hidden" value="' + id + '" name="iden'+id+'"/>' + pro + '</td>' +
                        '<td><input type="hidden" value="' + can + '" name="cant'+id+'"/>' + can + '</td>' +
                        '<td><input  type="hidden" value="' + pre + '" name="prec'+id+'"/>' + pre + '</td>' +
                        '<td><input type="hidden" value="' + iva + '" name="iva'+id+'"/>' + totid + '</td>' +
                        '<td><a  title="Borrar" onclick="EliminarFila('+ totid + ',' + id + ');"><i class="fa text-danger fa-trash fa-2x fa-lg"></i></a></td>' +
                        '</tr>';
                        $("#tabla").append(tr_str);
                        total = total+totid;
                        $("#total").html(total);
                         $("#nada").remove();}else if (array.indexOf(id) > -1) {
                        $("#mesage").html('<div class="alert alert-success padding" role="alert">Este Articulo Ya se Encentra A&ntilde;adido!</div>').slideDown(400);
                        
                    }
                $('#anadir')[0].reset();  
           }
         });

    return false; // Evitar ejecutar el submit del formulario.
     
      
    });  
    
    $('#cliente').on('change', function() {
        var formData = $(this).serialize();
        $.ajax({
            type: "POST",
            url: "/admin/pedido/anterior.php",
            dataType: 'JSON',
            data: formData,
            success: function(response){
                var memori = response.length;
                for(var i=0; i<memori; i++){
                    var boton = response[i].rbtn;
                    var modal = response[i].rmodal;
                    var code = response[i].rcode;
                }
                $("#pedanterior").html(boton);
                $("#memoria").html(modal);
                $("#code").html(code);
                $("#btnagregar").removeClass( "d-none" ).addClass( "btn-block " );

            }
        });
    });
    $(document).ready(function() {
     // Formulario Jovenes
    var formularios = $('#formulario');
    var mensage = $('#msn-alert');
    $(formularios).submit(function(f) {
        $(mensage).slideUp(750);
        $(mensage).hide();
        f.preventDefault();
        var action = $(this).attr('action');
        var type = $(this).attr('method');
        var form = $(this);
        var formdata = false;
        if (window.FormData){
            formdata = new FormData(form[0]);
        }
        $.ajax({
            url: action,
            type: type,
        data        : formdata ? formdata : form.serialize(),
        cache       : false,
        contentType : false,
        processData : false,
	    success     : function(data, textStatus, jqXHR){
                    if (data.match('.php') != null){window.location.replace(data);}
	        }
        }).done(function(response) {
            $(mensage).html(response).slideDown(400);
            setTimeout(function(){$(mensage).html(this).slideUp(700);}, 5000);
        });
    });
    
    
    
    
    var formularios = $('#gasto');
    var mensage = $('#msn-alert');
    $("#gasto").on("submit", function() {
     var action = $(this).attr('action');
     
        f.preventDefault();
    $.ajax({
        url: action, // point to server-side PHP script 
        dataType: 'text',  // what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data:  new FormData(this),
        type: "POST",
        success: function(data){
                    if (data.match('.php') != null){window.location.replace(data);}
	        }
        }).done(function(response) {
            $(mensage).html(response).slideDown(400);
            setTimeout(function(){$(mensage).html(this).slideUp(700);}, 5000);
        });
     });
});

});
</script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <!-- Custom scripts for all pages-->
    <script src="../vendor/base/js/sb-admin.min.js"></script> 
    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
    <!-- Page level plugin JavaScript-->
    <script src="../vendor/chart/Chart.min.js"></script>
    <script src="../vendor/datatables/jquery.dataTables.js"></script>
    <script src="../vendor/datatables/dataTables.bootstrap4.js"></script>
    <!-- Form JavaScript-->
    <!-- Custom scripts for this page-->
    <script src="../vendor/base/js/sb-admin-datatables.min.js"></script>
    <script src="../vendor/base/js/sb-admin-charts.min.js"></script>
    <script src="../vendor/sweet/sweetalert.js"></script>
    <script src="../vendor/chosen/chosen.jquery.min.js"></script>
    <script>
      $(function() {
        $('.chosen-select').chosen();
        $('.chosen-select-deselect').chosen({ allow_single_deselect: true });
      });
    </script>
</body>
</html>