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

class Barang_keluar_model extends CI_Model {

    private $table = 'barang_keluar';

    // Ambil semua data (urut terbaru di atas)
    public function get_all() {
        return $this->db
            ->order_by('tanggal', 'DESC')
            ->order_by('waktu_keluar', 'DESC')
            ->get($this->table)
            ->result();
    }

    // Ambil data berdasarkan ID
    public function get_by_id($id) {
        return $this->db->get_where($this->table, ['id' => $id])->row();
    }

    // Insert data baru
    public function insert($data) {
        return $this->db->insert($this->table, $data);
    }

    // Update data berdasarkan ID
    public function update($id, $data) {
        return $this->db->where('id', $id)->update($this->table, $data);
    }

    // Hapus data berdasarkan ID 
    public function delete($id) {
        return $this->db->delete($this->table, ['id' => $id]);
    }

    // Hitung semua data
    public function count_all() {
        return $this->db->count_all($this->table);
    }

    // Fungsi utama: Ambil data berdasarkan filter pencarian & tanggal (untuk export)
    public function get_data_with_filters($search = null, $tanggal = null) {
        $this->db->from($this->table);

        // Filter pencarian (PIC, Driver, Tujuan)
        if (!empty($search)) {
            $this->db->group_start();
            $this->db->like('pic', $search);
            $this->db->or_like('driver', $search);
             $this->db->or_like('origin', $search);
            $this->db->or_like('tujuan', $search);
            $this->db->group_end();
        }

        // Filter tanggal (menggunakan kolom DATETIME)
        if (!empty($tanggal)) {
            $this->db->where('DATE(tanggal)', $tanggal);
        }

        // Urutkan data terbaru di atas
        $this->db->order_by('tanggal', 'DESC');
        $this->db->order_by('waktu_keluar', 'DESC');

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