<?php
class Transaksi_model extends CI_Model {
    // public function simpan($data, $details) {
    //     $this->db->insert('tb_transaksi', $data);
    //     $id = $this->db->insert_id();
    //     foreach ($details as $d) {
    //         $d['id_transaksi'] = $id;
    //         $this->db->insert('tb_jual_detail', $d);
    //     }
    //     return $id;
    // }

     public function generate_id_transaksi() {
        $date = date('Ymd');
        $prefix = "TRX-" . $date . "-";
        
        $this->db->select_max('id_transaksi');
        $this->db->like('id_transaksi', $prefix, 'after');
        $query = $this->db->get('tb_transaksi');
        
        $last_id = $query->row()->id_transaksi;
        
        if($last_id) {
            $last_num = (int) substr($last_id, strlen($prefix));
            $next_num = $last_num + 1;
        } else {
            $next_num = 1;
        }
        
        return $prefix . str_pad($next_num, 4, '0', STR_PAD_LEFT);
    }

    // Cari barang by barcode atau nama
    public function cari_barang($keyword) {
        $this->db->select('tb_barang.*, tb_stok.stok_aplikasi');
        $this->db->from('tb_barang');
        $this->db->join('tb_stok', 'tb_stok.id_barang = tb_barang.id');
        $this->db->like('tb_barang.barcode_ecer', $keyword);
        $this->db->or_like('tb_barang.nama_barang', $keyword);
        $this->db->limit(10);
        return $this->db->get()->result();
        // $this->db->select('tb_barang.*, tb_stok.stok_aplikasi');
        // $this->db->from('tb_barang');
        // $this->db->join('tb_stok', 'tb_stok.id_barang = tb_barang.id_barang', 'left');
        // $this->db->group_start();
        // $this->db->like('tb_barang.barcode_ecer', $keyword);
        // $this->db->or_like('tb_barang.nama_barang', $keyword);
        // $this->db->group_end();
        // $this->db->limit(10);

        // return $this->db->get()->result();

    }
    public function get_barang_by_barcode($barcode) {
        return $this->db->get_where('tb_barang', ['barcode_ecer' => $barcode])->row();
    }

    // Simpan transaksi
    public function simpan_transaksi($data_transaksi, $detail_transaksi) {
        // Mulai transaksi database
        $this->db->trans_start();
        
        // Simpan data transaksi
        $this->db->insert('tb_transaksi', $data_transaksi);
        //history
        $this->db->insert('tb_history_barang_in_out', $history_transaksi);
        // Simpan detail transaksi
        $this->db->insert_batch('tb_jual_detail', $detail_transaksi);
        
        // Selesaikan transaksi database
        $this->db->trans_complete();
        
        return $this->db->trans_status();
    }
}
