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

class Kasir_model_update extends CI_Model {
    public function cari_barang($keyword) {
        $this->db->select('id, barcode_ecer, nama_barang, harga_jual_ecer, 
                          harga_grosir_lv1, harga_grosir_lv2, harga_grosir_lv3, harga_grosir_lv4,
                          min_grosir_lv1, min_grosir_lv2, min_grosir_lv3, min_grosir_lv4');
        $this->db->like('nama_barang', $keyword);
        return $this->db->get('tb_barang')->result();
    }

    public function get_barang_by_barcode($barcode) {
        $this->db->select('id, barcode_ecer, nama_barang, harga_jual_ecer, 
                          harga_grosir_lv1, harga_grosir_lv2, harga_grosir_lv3, harga_grosir_lv4,
                          min_grosir_lv1, min_grosir_lv2, min_grosir_lv3, min_grosir_lv4');
        $this->db->where('barcode_ecer', $barcode);
        return $this->db->get('tb_barang')->row();
    }
    
    public function get_level_harga($id_barang) {
        $this->db->select('harga_grosir_lv1, harga_grosir_lv2, harga_grosir_lv3, harga_grosir_lv4,
                          min_grosir_lv1, min_grosir_lv2, min_grosir_lv3, min_grosir_lv4');
        $this->db->where('id', $id_barang);
        return $this->db->get('tb_barang')->row();
    }

    public function simpan_transaksi($transaksi, $detail) {
        $this->db->trans_start();
        
        // Simpan transaksi
        $this->db->insert('tb_transaksi', $transaksi);
        $id_transaksi = $this->db->insert_id();
        
        // Simpan detail
        foreach ($detail as $item) {
            $data_detail = [
                'id_barang' => $item['id'],
                'harga_beli' => $item['harga_beli'],
                'harga_jual' => $item['harga_jual'],
                'jumlah' => $item['qty'],
                'harga_total' => $item['harga_total'],
                'id_transaksi' => $id_transaksi
            ];
            $this->db->insert('tb_jual_detail', $data_detail);
        }
        
        $this->db->trans_complete();
        return $this->db->trans_status();
    }
}