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

class Merma extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('admin/merma_model');
        $this->load->model('admin/products_model');
    }

    public function index()
    {
        $data['mermas'] = $this->merma_model->getAllMermas();
        $this->load->view('admin/merma/index', $data);
    }

    public function add()
    {
        if ($this->input->post()) {
            $data = [
                'date'         => date('Y-m-d H:i:s'),
                'reference_no' => $this->input->post('reference_no'),
                'warehouse_id' => $this->input->post('warehouse_id'),
                'note'         => $this->input->post('note'),
                'created_by'   => $this->session->userdata('user_id')
            ];

            $products = $this->input->post('products');

            if ($merma_id = $this->merma_model->addMerma($data, $products)) {
                $this->session->set_flashdata('message', 'Merma guardada con éxito');
                redirect('admin/merma');
            } else {
                $this->session->set_flashdata('error', 'Error al guardar la merma');
                redirect('admin/merma/add');
            }
        } else {
            $data['products']   = $this->products_model->getAllProducts(); // Para buscador
            $data['warehouses'] = $this->merma_model->getWarehouses();
            $this->load->view('admin/merma/add', $data);
        }
    }
}
