<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Merma extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();

        if (!$this->loggedIn) {
            $this->session->set_userdata('requested_page', $this->uri->uri_string());
            $this->sma->md('login');
        }

        $this->lang->admin_load('merma', $this->Settings->user_language);
        $this->load->library('form_validation');
        $this->load->admin_model('merma_model');
    }

    public function index()
    {
        $this->sma->checkPermissions();

        $this->data['merma'] = $this->merma_model->getAllMermas();

        $bc   = [['link' => base_url(), 'page' => lang('home')], ['link' => '#', 'page' => lang('merma')]];
        $meta = ['page_title' => lang('merma'), 'bc' => $bc];
        $this->page_construct('merma/index', $meta, $this->data);
    }

    public function add() {
    $this->form_validation->set_rules('ticket_reference', 'Ticket', 'required');
    $this->form_validation->set_rules('product_id', 'Producto', 'required');
    $this->form_validation->set_rules('cantidad', 'Cantidad', 'required|greater_than[0]');
    
    if ($this->form_validation->run() == true) {
        $data = [
            'ticket_reference' => $this->input->post('ticket_reference'),
            'customer_id'      => $this->input->post('customer_id'),
            'user_id'          => $this->input->post('user_id'),
            'warehouse_id'     => $this->input->post('warehouse_id'),
            'product_id'       => $this->input->post('product_id'),
            'cantidad'         => $this->input->post('cantidad'),
            'costo'            => $this->input->post('costo'),
            'latitud'          => $this->input->post('latitud'),
            'longitud'         => $this->input->post('longitud'),
            'observacion'      => $this->input->post('observacion'),
            'fecha_hora'       => $this->input->post('fecha_hora') ?: date('Y-m-d H:i:s')
        ];

        // Guardar la merma
        if ($merma_id = $this->Merma_model->addMerma($data)) {

            // Descontar del inventario según la sucursal
            $this->db->set('quantity', 'quantity - ' . (int)$data['cantidad'], false);
            $this->db->where('id', $data['product_id']);
            $this->db->where('warehouse_id', $data['warehouse_id']); // toma en cuenta la sucursal
            $this->db->update('sma_warehouses_products'); // tabla de stock por sucursal

            $this->session->set_flashdata('message', 'Merma registrada correctamente');
            redirect($_SERVER['HTTP_REFERER']);
        } else {
            $this->session->set_flashdata('error', 'No se pudo registrar la merma');
            redirect($_SERVER['HTTP_REFERER']);
        }

    } else {
        $this->session->set_flashdata('error', validation_errors());
        redirect($_SERVER['HTTP_REFERER']);
    }
}



    public function delete($id = null)
    {
        if ($id && $this->merma_model->deleteMerma($id)) {
            $this->session->set_flashdata('message', 'Merma eliminada.');
        } else {
            $this->session->set_flashdata('error', 'No se pudo eliminar la merma.');
        }
        admin_redirect('merma');
    }

    public function getMerma()
    {
        $this->sma->checkPermissions('index');

        $this->load->library('datatables');
        $this->datatables
            ->select('id, created_at, reference_no, customer_id, product_id, quantity, cost, status, action')
            ->from('sma_mermas')
            ->add_column('Actions', "<div class=\"text-center\">
                <a class=\"tip\" title='" . $this->lang->line('edit_merma') . "' href='" . admin_url('merma/edit/$1') . "' data-toggle='modal' data-target='#myModal'><i class=\"fa fa-edit\"></i></a> 
                <a href='#' class='tip po' title='<b>" . $this->lang->line('delete_merma') . "</b>' data-content=\"<p>" . lang('r_u_sure') . "</p><a class='btn btn-danger po-delete' href='" . admin_url('merma/delete/$1') . "'>" . lang('i_m_sure') . "</a> <button class='btn po-close'>" . lang('no') . "</button>\" rel='popover'><i class=\"fa fa-trash-o\"></i></a>
            </div>", 'id');

        echo $this->datatables->generate();
    }

    public function getProductInfo($id)
    {
        $product = $this->merma_model->getProductByID($id);
        echo json_encode([
            'cost'         => $product ? $product->cost : 0,
            'warehouse_id' => $product ? $product->warehouse_id : null
        ]);
    }
public function getTicketByID($id)
{
    $this->sma->checkPermissions(false, true);

    // Obtener el ticket de la tabla de ventas
    $ticket = $this->db->get_where('sma_sales', ['id' => $id])->row();
    if(!$ticket){
        echo json_encode(['error' => 'Ticket no encontrado']);
        return;
    }

    // Obtener cliente
    $customer = $this->db->get_where('sma_companies', ['id' => $ticket->customer_id])->row();

    // Obtener sucursal (warehouse)
    $warehouse = $this->db->get_where('sma_warehouses', ['id' => $ticket->warehouse_id])->row();

    echo json_encode([
        'customer_id' => $customer->id,
        'customer_name' => $customer->company ?: $customer->first_name . ' ' . $customer->last_name,
        'sucursal_id' => $warehouse->id,
        'sucursal_name' => $warehouse->name,
        'ticket_id' => $ticket->id
    ]);
}

}
