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

class Merma_model extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    public function addMerma($data) {
        if ($this->db->insert('sma_mermas', $data)) {
            return $this->db->insert_id();
        }
        return false;
    }
public function addMermaAndDiscount($data) {
    $this->db->trans_start();

    // Guardar la merma
    $this->db->insert('sma_mermas', $data);

    // Descontar inventario (usando sucursal/warehouse)
    $this->db->set('quantity', 'quantity - ' . (float)$data['quantity'], false);
    $this->db->where('product_id', $data['product_id']);
    $this->db->where('warehouse_id', $data['sucursal']); // <- este campo lo ligamos al ticket
    $this->db->update('sma_warehouses_products');

    $this->db->trans_complete();

    return $this->db->trans_status();
}

    public function updateMerma($id, $data) {
        return $this->db->update('sma_mermas', $data, ['id' => $id]);
    }

    public function deleteMerma($id) {
        return $this->db->delete('sma_mermas', ['id' => $id]);
    }

    public function getMermaByID($id) {
        $q = $this->db->get_where('sma_mermas', ['id' => $id], 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }

    public function getAllMermas() {
        $q = $this->db->get('sma_mermas');
        if ($q->num_rows() > 0) {
            return $q->result();
        }
        return false;
    }
public function getTicketByID($id) {
    $this->db->select('id, reference_no, customer, warehouse_id');
    $this->db->from('sma_sales'); // tabla de tickets/ventas
    $this->db->where('id', $id);
    $q = $this->db->get();
    if ($q->num_rows() > 0) {
        return $q->row();
    }
    return false;
}
    // 🔹 MÉTODOS NUEVOS PARA EL FORMULARIO MODAL
    public function getProducts() {
        $q = $this->db->get('sma_products');
        if ($q->num_rows() > 0) {
            return $q->result();
        }
        return [];
    }

    public function getAllCustomers() {
        $q = $this->db->get('sma_companies');
        if ($q->num_rows() > 0) {
            return $q->result();
        }
        return [];
    }

    public function getAllWarehouses() {
        $q = $this->db->get('sma_warehouses');
        if ($q->num_rows() > 0) {
            return $q->result();
        }
        return [];
    }


}
