<?php
$v = "?v=1";
if ($this->input->post('customer')) {
    $v .= "&customer=" . $this->input->post('customer');
}
if ($this->input->post('user')) {
    $v .= "&user=" . $this->input->post('user');
}
if ($this->input->post('start_date')) {
    $v .= "&start_date=" . $this->input->post('start_date');
}
if ($this->input->post('end_date')) {
    $v .= "&end_date=" . $this->input->post('end_date');
}
if ($this->input->post('status')) {
    $v .= "&status=" . $this->input->post('status');
}
if ($this->input->post('locals')) {
    $v .= "&locals=" . $this->input->post('locals');
}
if (($this->input->post('facturas'))) {
    $v .= "&facturas=" . ($this->input->post('facturas') == 'on' ? 1 : 0);
    $facturas = $this->input->post('facturas') == 'on' ? 1 : 0;
} else {
}
if ($this->input->post('boletas')) {
    $v .= "&boletas=" . ($this->input->post('boletas') == 'on' ? 1 : 0);
    $boletas = $this->input->post('boletas') == 'on' ? 1 : 0;
} else {
}
if ($this->input->post('notas_venta')) {
    $v .= "&notas_venta=" . ($this->input->post('notas_venta') == 'on' ? 1 : 0);
    $notas_venta = $this->input->post('notas_venta') == 'on' ? 1 : 0;
} else {
}
if (empty($_POST)) {
    $v .= "&start_date=" .  date('d/m/Y', strtotime(date('Y-m-d') . ' -3 months'));

    $v .= "&facturas= 1";
    $facturas = 1;
    $v .= "&boletas=1";
    $boletas = 1;
    $v .= "&notas_venta=1";
    $notas_venta = 1;
}
?>
<script>
    function centrar(n) {
        if (n !== null) {
            return '<div style="text-align:center">' + n + '</div>';
        }
        return '';
    }

    function method(n) {
        return (n == "PEN") ? '<center><span class="label label-primary">PEN</span></center>' : '<center><span class="label label-success">USD</span></center>';
    }

    $(document).ready(function() {
        $('#SLRData').DataTable({
            "aLengthMenu": [
                [10, 25, 50, 100, -1],
                [10, 25, 50, 100, '<?= lang('all'); ?>']
            ],
            "iDisplayLength": <?= $Settings->rows_per_page ?>,
            'bProcessing': true,
            'bServerSide': true,
            "bDestroy": true,
            "responsive": true,
            "order": [
                ['0', "ASC"]
            ],
            "ajax": {
                "url": '<?= site_url('reports/get_sales/' . $v) ?>',
                "type": "GET"
            }, // Se configura la fuente de datos AJAX para DataTables usando la URL almacenada en el elemento oculto "vurl"

            "columns": [{
                    "data": "fecha_venta"
                },
                {
                    "data": "tipo_comprobante"
                },
                {
                    "data": "nro_comprobante"
                },
                {
                    "data": "nombre_cliente"
                },
                {
                    "data": "moneda",
                    "render": function(data, type, row) {
                        return (data == "PEN") ? '<center><span class="label label-primary">PEN</span></center>' : '<center><span class="label label-success">USD</span></center>';
                    }
                },
                {
                    "data": "total"
                },
                {
                    "data": "IGV"
                },
                {
                    "data": "descuento"
                },
                {
                    "data": "total"
                },
                {
                    "data": "estado_reg"
                }
            ],
            columnDefs: [{
                orderable: false,
                targets: -1
            }],
            oLanguage: {
                sZeroRecords: "<center>No se encontraron resultados</center>"
            },
            sInfoThousands: ""
        });
        // $('#SLRData').dataTable({
        //     "aLengthMenu": [
        //         [10, 25, 50, 100, -1],
        //         [10, 25, 50, 100, '<?= lang('all'); ?>']
        //     ],
        //     "aaSorting": [
        //         [0, "desc"]
        //     ],
        //     "iDisplayLength": <?= $Settings->rows_per_page ?>,
        //     'bProcessing': true,
        //     'bServerSide': true,
        //     'sAjaxSource': '<?= site_url('reports/get_sales/' . $v) ?>',
        //     'fnServerData': function(sSource, aoData, fnCallback) {
        //         aoData.push({
        //             "name": "<?= $this->security->get_csrf_token_name() ?>",
        //             "value": "<?= $this->security->get_csrf_hash() ?>"
        //         });
        //         $.ajax({
        //             'dataType': 'json',
        //             'type': 'POST',
        //             'url': sSource,
        //             'data': aoData,
        //             'success': fnCallback
        //         });
        //     },
        //     "aoColumns": [{
        //         "mRender": hrld
        //     }, null, null, null, {
        //         "mRender": method
        //     }, {
        //         "mRender": currencyFormat
        //     }, {
        //         "mRender": currencyFormat
        //     }, {
        //         "mRender": currencyFormat
        //     }, {
        //         "mRender": currencyFormat
        //     }, {
        //         "mRender": centrar
        //     }]
        // });
    });
</script>

<script type="text/javascript">
    $(document).ready(function() {
        $('#form').hide();
        $('.toggle_form').click(function() {
            $("#form").slideToggle();
            return false;
        });
    });
</script>
<style>
    #form {
        border-radius: .35rem !important;
        box-shadow: 0 0 1px #5490be, 0 1px 3px #5490be !important;
        margin-bottom: 1rem !important;
    }
</style>
<section class="content">
    <div class="row">
        <div class="col-sm-12">
            <div class="box" style="border-top: 2.5px solid #004785;">
                <div class="row">
                    <div class="col-sm-10">
                        <div class="box-header">
                            <a href="#" class="btn btn-default btn-sm toggle_form pull-left"><?= lang("show_hide_filters"); ?></a>
                            <!--h3 class="box-title"><?= lang('customize_report'); ?></h3-->
                        </div>
                    </div>

                </div>
                <div class="box-body">
                    <div id="form" class="box" style="border-top: 0px solid;">
                        <div class="box-body">
                            <?= form_open("reports"); ?>

                            <div class="row">
                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label class="control-label" for="customer"><?= lang("customer"); ?></label>
                                        <?php
                                        $cu[0] = lang("select") . " " . lang("customer");
                                        foreach ($customers as $customer) {
                                            $cu[$customer->id] = $customer->name;
                                        }
                                        echo form_dropdown('customer', $cu, set_value('customer'), 'class="form-control select2" style="width:100%" id="customer"'); ?>
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label class="control-label" for="user"><?= lang("user"); ?></label>
                                        <?php
                                        $us[""] = "Todos";
                                        foreach ($users as $user) {
                                            $us[$user->id] = $user->first_name . " " . $user->last_name;
                                        }
                                        echo form_dropdown('user', $us, (isset($_POST['user']) ? $_POST['user'] : ""), 'class="form-control select2" id="user" style="width:100%;"');
                                        ?>
                                    </div>
                                </div>

                                <div class="col-sm-3">
                                    <div class="form-group">
                                        <label class="control-label" for="start_date"><?= lang("start_date"); ?></label>
                                        <?= form_input('start_date', set_value('start_date'), 'class="form-control datetimepicker" id="start_date" data-date-format="DD/MM/YYYY"'); ?>
                                    </div>
                                </div>
                                <div class="col-sm-3">
                                    <div class="form-group">
                                        <label class="control-label" for="end_date"><?= lang("end_date"); ?></label>
                                        <?= form_input('end_date', set_value('end_date'), 'class="form-control datetimepicker" id="end_date" data-date-format="DD/MM/YYYY"'); ?>
                                    </div>
                                </div>

                                <div class="col-sm-3">
                                    <div class="form-group">
                                        <label class="control-label" for="status"><?= lang("status"); ?></label>
                                        <?php
                                        $sa[1] = lang("active");
                                        $sa[2] = lang("Anulado");
                                        $sa[3] = lang("all");
                                        echo form_dropdown('status', $sa, set_value('status'), 'class="form-control select2" style="width:100%" id="status"'); ?>
                                    </div>
                                </div>

                                <div class="col-sm-3">
                                    <div class="form-group">
                                        <label class="control-label" for="locals">Local</label>
                                        <?php
                                        $arrayLocal[""] = "Seleccione local";
                                        foreach ($locals as $local) {
                                            $arrayLocal[$local->id] = $local->name;
                                        }
                                        echo form_dropdown('locals', $arrayLocal, set_value('locals'), 'class="form-control select2" style="width:100%" id="locals"'); ?>
                                    </div>
                                </div>
                                <?php if ($this->session->userdata('traders')) { ?>
                                    <div class="col-sm-3">
                                        <div class="form-group">
                                            <label class="control-label" for="traders_id">Vendedor</label>
                                            <?php
                                            $arrayTrader[""] = "todos";
                                            foreach ($traders as $trader) {
                                                $arrayTrader[$trader['id']] = $trader['last_name_1'] . ' ' . $trader['last_name_2'] . ', ' . $trader['name'];
                                            }
                                            echo form_dropdown('traders_id', $arrayTrader, set_value('traders_id'), 'class="form-control select2" style="width:100%" id="traders_id"'); ?>
                                        </div>
                                    </div>
                                <?php } ?>
                                <div class="col col-md-6">
                                    <fieldset class="fieldset-border">
                                        <legend class="legend-border">Tipo de comprobantes</legend>
                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <input type="checkbox" name="facturas" id="facturas" <?= (isset($facturas) && $facturas == 1) ? 'checked="checked"' : '' ?>>
                                                <label class="" for="">Facturas</label>
                                            </div>
                                        </div>
                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <input type="checkbox" name="boletas" id="boletas" <?= (isset($boletas) && $boletas == 1) ? 'checked="checked"' : '' ?>>
                                                <label class="" for="">Boletas</label>
                                            </div>
                                        </div>
                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <input type="checkbox" name="notas_venta" id="notas_venta" <?= (isset($notas_venta) && $notas_venta == 1) ? 'checked="checked"' : '' ?>>
                                                <label class="" for="">Notas de venta</label>
                                            </div>
                                        </div>
                                    </fieldset>
                                </div>
                            </div>
                            <div class="col-sm-12 text-right">
                                <button type="submit" class="btn btn-primary btn-sm">Filtrar</button>
                                <button class="btn btn-default  btn-sm" type="submit" id="exportar-excel"><strong><i class="fa fa-file-excel-o fa-lg" style="color:forestgreen"></i> </strong> Filtrar y exportar</button>
                                <!--<button class="dropdown-item btn btn-default btn-block" type="submit" id="exportar-txt"><strong><i class="fa fa-file-text-o fa-lg" style="color:forestgreen"></i> </strong>Descargar TXT</button>-->
                            </div>

                        </div>

                        <?= form_close(); ?>
                    </div>
                </div>
                <div class="clearfix"></div>
                <div class="row" style="padding-top: 10px;">
                    <div class="col-sm-12">
                        <div class="table-responsive">
                            <table id="SLRData" class="table table-striped table-bordered table-condensed table-hover">
                                <thead>
                                    <tr class="active">
                                        <th class="col-sm-2"><?= lang("date"); ?></th>
                                        <th class="col-sm-1"><?= lang("proof_type"); ?></th>
                                        <th class="col-sm-1">N° <?= lang("proof"); ?></th>
                                        <th class="col-sm-2"><?= lang("customer"); ?></th>
                                        <th style="text-align:center; width: 70px;"><?php echo $this->lang->line("currency_name"); ?></th>
                                        <th class="col-sm-1"><?= lang("total"); ?></th>
                                        <th class="col-sm-1"><?= lang("tax"); ?></th>
                                        <th class="col-sm-1"><?= lang("discount"); ?></th>
                                        <th class="col-sm-1"><?= lang("grand_total"); ?></th>
                                        <!-- <th class="col-sm-1"><?= lang("paid"); ?></th>
                                            <th class="col-sm-2"><?= lang("balance"); ?></th> -->
                                        <th class="col-sm-1"><?= lang("status"); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td colspan="8" class="dataTables_empty"><?= lang('loading_data_from_server'); ?></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <?php if ($this->input->post('customer') && $this->input->post('status') != 2) { ?>
                    <div class="row">
                        <div class="col-md-6"><button class="btn bg-purple btn-lg btn-block" style="cursor:default;"><strong><?= $total_sales ?></strong> <?= lang("total_sales"); ?></button></div>
                        <div class="col-md-6"><button class="btn btn-success btn-lg btn-block" style="cursor:default;"><strong><?= $total_sales_value ? $total_sales_value : 0; ?></strong> <?= lang("total_sales_value"); ?></button></div>
                    </div>
                <?php } ?>

            </div>
        </div>
    </div>
    </div>
</section>

<script src="<?= $assets ?>plugins/bootstrap-datetimepicker/js/moment.min.js" type="text/javascript"></script>
<script src="<?= $assets ?>plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script type="text/javascript" src="<?= $assets ?>plugins/datatables/datatable.min.js"></script>
<script type="text/javascript">
    $(function() {
        $('.datetimepicker').datetimepicker({
            format: 'DD/MM/YYYY'
        });
    });
    $("#exportar-excel").click(function() {
        var csrfName = '<?php echo $this->security->get_csrf_token_name(); ?>';
        var csrfHash = '<?php echo $this->security->get_csrf_hash(); ?>';
        var data = {
            '<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>',
        };
        data.fecha_inicio = $("#start_date").val();
        data.fecha_fin = $("#end_date").val();
        data.cliente = $("#customer").val();
        data.usuario = $("#user").val();
        data.estado = $("#status").val();
        data.local = $("#locals").val();
        data.traders_id = $("#traders_id").val();
        data.facturas = $("#facturas").is(':checked') ? 1 : 0;
        data.boletas = $("#boletas").is(':checked') ? 1 : 0;
        data.notas_venta = $("#notas_venta").is(':checked') ? 1 : 0;
        data.notas_credito = $("#notas_credito").is(':checked') ? 1 : 0;
        $.ajax({
            url: base_url + "reports/exportarExcelVentas",
            destroy: true,
            type: 'POST',
            dataType: 'json',
            data: data,
            async: false,
        }).done(function(data) {
            if (data.result == 'ok') {
                var $a = $("<a>");
                $a.attr("href", data.file);
                $("body").append($a);
                $a.attr("download", data.filename);
                $a[0].click();
                $a.remove();
            }
        });

    });

    $(document).ready(function() {
        // Inicializar campos de fecha
        <?php if (empty($_POST)) { ?>
            var currentDate = moment();
            $('#start_date').val(currentDate.subtract(3, 'months').format('DD/MM/YYYY'));
            $('#end_date').val(moment().format('DD/MM/YYYY'));
        <?php } ?>

        $('#facturas').on('change', function() {
            if (!$('#notas_venta').is(':checked') && !$('#boletas').is(':checked')) {
                $(this).prop('checked', true);
            }

        });

        // Manejador de eventos para el cambio en el checkbox 'boletas'
        $('#boletas').change(function() {
            if (!$('#notas_venta').is(':checked') && !$('#facturas').is(':checked')) {
                $(this).prop('checked', true);
            }
        });

        // Manejador de eventos para el cambio en el checkbox 'notas_venta'
        $('#notas_venta').change(function() {
            if (!$('#facturas').is(':checked') && !$('#boletas').is(':checked')) {
                $(this).prop('checked', true);
            }
        });
    });
</script>