<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<div class="modal-dialog modal-lg">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-2x">&times;</i></button>
            <h4 class="modal-title"><?= lang('add_merma'); ?></h4>
        </div>
        <?php
        $attrib = ['data-toggle' => 'validator', 'role' => 'form', 'id' => 'add-merma-form'];
        echo admin_form_open('merma/add', $attrib);
        ?>
        <div class="modal-body">
            <p><?= lang('enter_info'); ?></p>
            <div class="row">
                <div class="col-md-6">

                    <!-- Referencia del ticket -->
                    <div class="form-group">
                        <?= lang('reference_no', 'reference_no'); ?>
                        <input type="text" name="reference_no" id="reference_no" class="form-control" required="required" readonly
                               value="<?= isset($reference_no) ? $reference_no : '' ?>">
                    </div>

                    <!-- Cliente -->
                    <div class="form-group">
                        <?= lang('customer', 'customer_id'); ?>
                        <?php
                        $c[''] = lang('select') . ' ' . lang('customer');
                        foreach ($customers as $customer) {
                            $c[$customer->id] = $customer->name;
                        }
                        echo form_dropdown('customer_id', $c, '', 'class="form-control select" id="customer_id" style="width:100%;" required="required"');
                        ?>
                    </div>

                    <!-- Producto -->
                    <div class="form-group">
                        <?= lang('product', 'product_id'); ?>
                        <?php
                        $p[''] = lang('select') . ' ' . lang('product');
                        foreach ($products as $prod) {
                            $p[$prod->id] = $prod->name;
                        }
                        echo form_dropdown('product_id', $p, '', 'class="form-control select" id="product_id" style="width:100%;" required="required"');
                        ?>
                    </div>

                    <!-- Cantidad -->
                    <div class="form-group">
                        <?= lang('quantity', 'quantity'); ?>
                        <input type="number" name="quantity" class="form-control" id="quantity" required="required" step="any">
                    </div>

                    <!-- Costo -->
                    <div class="form-group">
                        <?= lang('cost', 'cost'); ?>
                        <input type="number" name="cost" class="form-control" id="cost" required="required" step="any" readonly>
                    </div>

                    <!-- Sucursal -->
                    <div class="form-group">
                        <?= lang('sucursal', 'warehouse_id'); ?>
                        <?php
                        $wh[''] = lang('select') . ' ' . lang('sucursal');
                        foreach ($warehouses as $w) {
                            $wh[$w->id] = $w->name;
                        }
                        echo form_dropdown('warehouse_id', $wh, '', 'class="form-control select" id="warehouse_id" style="width:100%;" required="required" readonly');
                        ?>
                    </div>

                </div>
                <div class="col-md-6">

                    <!-- Usuario -->
                    <div class="form-group">
                        <?= lang('user', 'user_id'); ?>
                        <input type="text" class="form-control" value="<?= $this->session->userdata('username'); ?>" readonly>
                    </div>

                    <!-- Fecha y hora -->
                    <div class="form-group">
                        <?= lang('date', 'date'); ?>
                        <input type="text" name="date" class="form-control datetimepicker" id="date" required="required"
                               value="<?= date('Y-m-d H:i:s') ?>">
                    </div>

                    <!-- Geolocalización -->
                    <div class="form-group">
                        <label><?= lang('latitude', 'latitude'); ?></label>
                        <input type="text" name="latitude" id="latitude" class="form-control" readonly>
                    </div>
                    <div class="form-group">
                        <label><?= lang('longitude', 'longitude'); ?></label>
                        <input type="text" name="longitude" id="longitude" class="form-control" readonly>
                    </div>
                    <div class="form-group text-center">
                        <button type="button" class="btn btn-info" onclick="getLocation()"><?= lang('get_current_location'); ?></button>
                    </div>

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

        <div class="modal-footer">
            <?php echo form_submit('add_merma', lang('add_merma'), 'class="btn btn-primary"'); ?>
        </div>
        <?php echo form_close(); ?>
    </div>
</div>

<script type="text/javascript">
$(document).ready(function () {
    $('select.select').select2({minimumResultsForSearch: 7});
    $('.datetimepicker').datetimepicker({format: 'YYYY-MM-DD HH:mm:ss'});

    // Al seleccionar producto, traer costo y sucursal
    $('#product_id').on('change', function () {
        var product_id = $(this).val();
        if (product_id) {
            $.ajax({
                url: '<?= admin_url('merma/getProductInfo') ?>/' + product_id,
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    $('#cost').val(data.cost);
                    $('#warehouse_id').val(data.warehouse_id).trigger('change');
                }
            });
        } else {
            $('#cost').val('');
            $('#warehouse_id').val('').trigger('change');
        }
    });
});

// Geolocalización
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError, { enableHighAccuracy: true, timeout: 10000 });
    } else {
        alert("Tu navegador no soporta geolocalización.");
    }
}
function showPosition(position) {
    $('#latitude').val(position.coords.latitude);
    $('#longitude').val(position.coords.longitude);
    alert("Ubicación obtenida correctamente.");
}
function showError(error) {
    switch(error.code){
        case error.PERMISSION_DENIED: alert("Permiso denegado."); break;
        case error.POSITION_UNAVAILABLE: alert("Ubicación no disponible."); break;
        case error.TIMEOUT: alert("Tiempo de espera excedido."); break;
        case error.UNKNOWN_ERROR: alert("Error desconocido."); break;
    }
}
</script>
