<?php
/*-------------------------
Autor: Delmar Lopez
Web: www.softwys.com
Mail: softwysop@gmail.com
---------------------------*/
include 'is_logged.php'; //Archivo verifica que el usario que intenta acceder a la URL esta logueado
/* 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
//Archivo de funciones PHP
require_once "../funciones.php";
//Inicia Control de Permisos
include "../permisos.php";
$user_id = $_SESSION['id_users'];
$cargo_users = $_SESSION['cargo_users'];
$sucursal_users = $_SESSION['sucursal_users'];
get_cadena($user_id);
$modulo = "Ventas";
permisos($modulo, $cadena_permisos);
//Finaliza Control de Permisos
$simbolo_moneda = get_row('perfil', 'moneda', 'id_perfil', 1);
$action = (isset($_REQUEST['action']) && $_REQUEST['action'] != null) ? $_REQUEST['action'] : '';
if ($action == 'ajax') {
    // escaping, additionally removing everything that could be (html/javascript-) code
    $q      = mysqli_real_escape_string($conexion, (strip_tags($_REQUEST['q'], ENT_QUOTES)));
    $id_suc = intval($_REQUEST['id_sucursal']);
    $daterange      = mysqli_real_escape_string($conexion, (strip_tags($_REQUEST['range'], ENT_QUOTES)));
    if ($cargo_users == 1) {
        $id_suc = intval($_REQUEST['id_sucursal']);
    } else {
        $id_suc = $sucursal_users;
    }
    $sTable = "	facturas_traslados, users";
    $sWhere = "";
    $sWhere .= " WHERE facturas_traslados.id_vendedor=users.id_users";
    if ($user_id != 1) {
        $sWhere .= " and users.id_users= $user_id";
    } else {
        $sWhere .= "";
    }
    if ($id_suc > 0) {
        $sWhere .= " and id_sucursal2 = '" . $id_suc . "' ";
    }
    if ($_GET['q'] != "") {
        $sWhere .= " and  (facturas_traslados.numero_factura like '%$q%')";
    }
    if (!empty($daterange)) {
        list($f_inicio, $f_final)                    = explode(" - ", $daterange); //Extrae la fecha inicial y la fecha final en formato espa?ol
        list($dia_inicio, $mes_inicio, $anio_inicio) = explode("/", $f_inicio); //Extrae fecha inicial
        $fecha_inicial                               = "$anio_inicio-$mes_inicio-$dia_inicio 00:00:00"; //Fecha inicial formato ingles
        list($dia_fin, $mes_fin, $anio_fin)          = explode("/", $f_final); //Extrae la fecha final
        $fecha_final                                 = "$anio_fin-$mes_fin-$dia_fin 23:59:59";

        $sWhere .= " and 	facturas_traslados.fecha_factura between '$fecha_inicial' and '$fecha_final' ";
    }

    $sWhere .= " order by 	facturas_traslados.id_factura desc";
    include 'pagination.php'; //include pagination file
    //pagination variables
    $page      = (isset($_REQUEST['page']) && !empty($_REQUEST['page'])) ? $_REQUEST['page'] : 1;
    $per_page  = 10; //how much records you want to show
    $adjacents = 4; //gap between pages after number of adjacents
    $offset    = ($page - 1) * $per_page;
    //Count the total number of row in your table*/
    $count_query = mysqli_query($conexion, "SELECT count(*) AS numrows FROM $sTable  $sWhere");
    $row         = mysqli_fetch_array($count_query);
    $numrows     = $row['numrows'];
    $total_pages = ceil($numrows / $per_page);
    $reload      = '../reportes/facturas.php';
    //main query to fetch the data
    $sql   = "SELECT * FROM  $sTable $sWhere LIMIT $offset,$per_page";
    $query = mysqli_query($conexion, $sql);
    //loop through fetched data
    if ($numrows > 0) {
        echo mysqli_error($conexion);
?>
        <div class="table-responsive">
            <table class="table table-sm table-striped">
                <tr class="info">
                    <th>FACTURA</th>
                    <th>FECHA</th>
                    <th>DESTINO</th>
                    <th>ESTADO</th>
                    <th>EMPLEADO</th>
                    <th class='text-center'>IMPORTE</th>
                    <th>ORIGEN</th>
                    <th class='text-center'>ACCIONES</th>

                </tr>
                <?php
                $total_gen = 0;
                while ($row = mysqli_fetch_array($query)) {
                    $id_factura       = $row['id_factura'];
                    $numero_factura   = $row['numero_factura'];
                    $fecha            = date("d/m/Y", strtotime($row['fecha_factura']));
                    $nombre_vendedor  = $row['nombre_users'] . " " . $row['apellido_users'];
                    $estado_factura   = $row['estado_factura'];
                    $condicion        = $row['condiciones'];
                    $suc_destino   = $row['id_sucursal2'];
                    $suc_origen   = $row['id_sucursal'];
                    $total_venta    = $row['monto_factura'];
                    $total_gen = $total_gen + $total_venta;
                    if ($estado_factura == 1) {
                        $text_estado = "Recibido";
                        $label_class = 'badge-success';
                    } else {
                        $text_estado = "Pendiente";
                        $label_class = 'badge-danger';
                    }
                    if ($condicion != 4) {
                        $tip = "CONTADO";
                    } else {
                        $tip = "CREDITO";
                    }
                    $sql_suc = mysqli_query($conexion, "select nombre_sucursal from sucursales where id_sucursal='$suc_destino'");
                    $rw  = mysqli_fetch_array($sql_suc);
                    $nom_sucursal2 = $rw['nombre_sucursal'];
                    $sql_suc = mysqli_query($conexion, "select nombre_sucursal from sucursales where id_sucursal='$suc_origen'");
                    $rw  = mysqli_fetch_array($sql_suc);
                    $nom_sucursal1 = $rw['nombre_sucursal'];
                ?>
                    <tr>
                        <td><label class='badge badge-purple'><?php echo $numero_factura; ?></label></td>
                        <td><?php echo $fecha; ?></td>
                        <td><span class='badge badge-primary'><?php echo $nom_sucursal2; ?></span></td>
                        <td><span class="badge <?php echo $label_class; ?>"><?php echo $text_estado; ?></span></td>
                        <td><?php echo $nombre_vendedor; ?></td>
                        <td class='text-left'><b><?php echo $simbolo_moneda . '' . number_format($total_venta, 4); ?></b></td>
                        <td><span class='badge badge-pink'><?php echo $nom_sucursal1 ?></span></td>
                        <td class="text-center">
                            <div class="btn-group dropdown">
                                <button type="button" class="btn btn-warning btn-sm dropdown-toggle waves-effect waves-light" data-toggle="dropdown" aria-expanded="false"> <i class='fa fa-cog'></i> <i class="caret"></i> </button>
                                <div class="dropdown-menu dropdown-menu-right">
                                    <?php if ($permisos_editar == 1) { ?>
                                        <a class="dropdown-item" href="editar_traslado.php?id_factura=<?php echo $id_factura; ?>"><i class='fa fa-edit'></i> Editar</a>
                                        <a class="dropdown-item" href="#" onclick="printOrder('<?php echo $id_factura; ?>');"><i class='fa fa-print'></i> Imprimir Factura</a>
                                    <?php }
                                    if ($permisos_eliminar == 1) { ?>
                                        <a class="dropdown-item" href="#" data-toggle="modal" data-target="#dataDelete" data-id="<?php echo $row['id_factura']; ?>"><i class='fa fa-trash'></i> Anular Traslado</a>
                                        <!--<a class="dropdown-item" href="#" data-toggle="modal" data-target="#dataDelete" data-id="<?php echo $row['id_factura']; ?>"><i class='fa fa-trash'></i> Eliminar</a>-->
                                    <?php } ?>


                                </div>
                            </div>

                        </td>

                    </tr>
                <?php
                }
                ?>
                <tr>
                    <td colspan=9><span class="pull-right"><?php
                                                            echo paginate($reload, $page, $total_pages, $adjacents);
                                                            ?></span></td>
                </tr>
            </table>
        </div>
        <div class="alert alert-info alert-dismissible" role="alert" align="center">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <strong>
                <h3> TOTAL VENTAS: <?php echo $simbolo_moneda . ' ' . number_format($total_gen, 4) ?> </h3>
            </strong>
        </div>
    <?php
    }
    //Este else Fue agregado de Prueba de prodria Quitar
    else {
    ?>
        <div class="alert alert-warning alert-dismissible" role="alert" align="center">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <strong>Aviso!</strong> No hay Registro de Facturas
        </div>
<?php
    }

    // fin else
}
?>