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

class Barang extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        cek_login();
        date_default_timezone_set('Asia/Jakarta');
        $this->load->model('Menu_model', 'menu');
        $id = $this->menu->aksesUser($this->session->userdata('login_session')['role']);
        
        $this->load->model('Admin_model', 'admin');
        $this->load->model('Barang_model', 'barang');
        $this->load->library('form_validation');
    }

    public function index()
    {
        $data['title'] = "Barang";
        $data['barang'] = $this->admin->getBarang();

        $this->template->load('templates/dashboard', 'barang/data', $data);
    }

    private function _validasi()
    {
        $this->form_validation->set_rules('nama_barang', 'Nama Barang', 'required|trim');
        $this->form_validation->set_rules('jenis_id', 'Jenis Barang', 'required');
        $this->form_validation->set_rules('satuan_id', 'Satuan Barang', 'required');
    }

    private function _validasi_saldo()
    {
        $this->form_validation->set_rules('cabang_id', 'Gudang', 'required|trim');
    }

    public function add()
    {
        $this->_validasi();

        if ($this->form_validation->run() == false) {
            $data['now'] = date("Y-m-d");

            $data['title'] = "Barang";
            $data['jenis'] = $this->admin->get('jenis');
            $data['satuan'] = $this->admin->get('satuan');
          
            // Mengenerate ID Barang
            $kode_terakhir = $this->admin->getMax('barang', 'id_barang');
            $kode_tambah = substr($kode_terakhir, -6, 6);
            $kode_tambah++;
            $number = str_pad($kode_tambah, 6, '0', STR_PAD_LEFT);
            $data['id_barang'] = 'B' . $number;

            $this->template->load('templates/dashboard', 'barang/add', $data);
        } else {
            // $input = $this->input->post(null, true);
            $insert = $this->barang->insertDataBarang();

            if ($insert) {
                set_pesan('data berhasil disimpan');
                redirect('barang');
            } else {
                set_pesan('gagal menyimpan data');
                redirect('barang/add');
            }
        }
    }

    public function edit($getId)
    {
        $id = encode_php_tags($getId);
        $this->_validasi();

        if ($this->form_validation->run() == false) {
            $data['title'] = "Barang";
            $data['jenis'] = $this->admin->get('jenis');
            $data['satuan'] = $this->admin->get('satuan');
            $data['barang'] = $this->admin->get('barang', ['id_barang' => $id]);
            $this->template->load('templates/dashboard', 'barang/edit', $data);
        } else {
            $input = $this->input->post(null, true);
            $update = $this->admin->update('barang', 'id_barang', $id, $input);

            if ($update) {
                set_pesan('data berhasil disimpan');
                redirect('barang');
            } else {
                set_pesan('gagal menyimpan data');
                redirect('barang/edit/' . $id);
            }
        }
    }

    public function delete($getId)
    {
        // cek ada di tabel
        $id = encode_php_tags($getId);
        $barang_masuk =$this->admin->get('detail_barang_masuk', ['id_barang' => $id]);
        $transfer_barang =$this->admin->get('detail_transfer_barang', ['id_barang' => $id]);
        $retur_barang =$this->admin->get('detail_retur', ['id_barang' => $id]);

        if(is_null($barang_masuk) && is_null($transfer_barang) && is_null($retur_barang)) {
            if ($this->admin->delete('barang', 'id_barang', $id)) {
                set_pesan('data berhasil dihapus.');
            } else {
                set_pesan('data gagal dihapus.', false);
            }
        } else {
            set_pesan('Barang ini sudah digunakan transaksi!', false);
        }

        redirect('barang');
    }













    public function get_barang_by_user()
    {
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
        $id_cabang = $dt_user['cabang_id'];
        $dt_cabang = $this->admin->getDataCabangByUser($dt_user['cabang_id']);

        $data['title'] = "Barang ".$dt_cabang['nama_cabang']; 

        $id_user = $dt_user['id_user'];

        $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
        $tgl_akhir = date('Y-m-d');

        // daftar barang masuk by id
        $dtBarangMasuk = $this->barang->getDetailBarangMasukByIdUser($id_user, $id_cabang);

        // mencari stok terakhir berdasarkan id_barang_masuk
        $result = array();
        foreach($dtBarangMasuk as $row) {
            // 
            $stokakhir = $this->barang->_saldo_awal_barang_by_user_pemilik($id_user, $row['id_barang'], $tgl_awal, $tgl_akhir, $row['id_detail']);

            if($stokakhir != 0) {

                $res_kirim_data = array(
                    'id_barang' => $row['id_barang'],
                    'id_user_pemilik' => $row['id_user_pemilik'],
                    'no_transaksi' => $row['id_barang_masuk'],
                );

                $result[] = array(
                    'id_detail' => $row['id_detail'],
                    'id_barang_masuk' => $row['id_barang_masuk'],
                    'tanggal_masuk' => $row['tanggal_masuk'],
                    'id_barang' => $row['id_barang'],
                    'saldo_akhir' => $stokakhir,
                    'nama_barang' => $row['nama_barang'],
                    'nama_jenis' => $row['nama_jenis'],
                    'nama_satuan' => $row['nama_satuan'],
                    'merk' => $row['merk'],
                    'spesifikasi' => $row['spesifikasi'],
                    'barcode' => $row['barcode'],
                    'sn' => $row['sn'],
                    'res_send_data' => base64_encode(json_encode($res_kirim_data)),
                );
            }

        }

        $data['barang'] = $result;

        $this->template->load('templates/dashboard', 'barang/get_barang_by_user', $data);
    }

    public function mutasi_barang_by_user_pemilik($result)
    {
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);

        $data['title'] = "Mutasi Barang";

        // memproses dari result yang dikirim
        $res = json_decode(base64_decode($result));
        $id_barang = $res->id_barang;

        $data['barang'] = $this->admin->get('barang', ['id_barang' => $res->id_barang]);
        $data['satuan'] = $this->admin->get('satuan', ['id_satuan' => $data['barang']['satuan_id']]);

        $tgl_satu = date('Y-m-01', strtotime(date("Y-m-d")));
        $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
        $tgl_akhir = date('Y-m-d', strtotime('-1 days', strtotime($tgl_satu)));

        // pencarian user pemilik siapa saja yang mempunyai berdasarkan dari barang masuknya masingmasing user
        $this->db->where('b.user_id_pemilik', $res->id_user_pemilik);
        $dt_user_pemilik = $this->barang->getUserPemilikFormBarangMasukByIdBarang($id_barang);

        $data['tglAwal'] = $tgl_satu;
        $data['tglAkhir'] = date("Y-m-d");
        $data['result_mutasi'] = array();
        foreach($dt_user_pemilik as $row) {
            $mutasi_barang = $this->barang->getMutasiBarangByDateAndPemilik($res->id_user_pemilik, $id_barang, $dt_user['cabang_id'], $data['tglAwal'], $data['tglAkhir'], $row['id_detail']);

            if($mutasi_barang[0]['no'] == $res->no_transaksi) {

                $data['result_mutasi'][] = array(
                    'id_user_pemilik' => $res->id_user_pemilik,
                    'nm_user_pemilik' => $row['nm_user_pemilik'],
                    'nama_barang' => $row['nama_barang'],
                    'nama_satuan' => $row['nama_satuan'],
                    'stok_awal' => $this->barang->_saldo_awal_barang_by_user_pemilik($res->id_user_pemilik, $id_barang, $tgl_awal, $tgl_akhir, $row['id_detail']),
                    'mutasi_barang' => $mutasi_barang,
                );
            }
        }     
        
        $this->form_validation->set_rules('tgl_awal', 'Tanggal Awal', 'required');
        $this->form_validation->set_rules('tgl_akhir', 'Tanggal Akhir', 'required');
        if($this->form_validation->run() == false) {
            $this->template->load('templates/dashboard', 'barang/mutasi_barang_by_id', $data);
        } else {
            $tglAwal = $this->input->post('tgl_awal', true);
            $tglAkhir = $this->input->post('tgl_akhir', true);

            $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
            $tgl_akhir = date('Y-m-d', strtotime('-1 days', strtotime($tglAwal)));
            
            // pencarian user pemilik siapa saja yang mempunyai berdasarkan dari barang masuknya masingmasing user
            $this->db->where('b.user_id_pemilik', $res->id_user_pemilik);
            $dt_user_pemilik = $this->barang->getUserPemilikFormBarangMasukByIdBarang($id_barang);

            $data['tglAwal'] = $tglAwal;
            $data['tglAkhir'] = $tglAkhir;
            $data['result_mutasi'] = array();
            foreach($dt_user_pemilik as $row) {
                $mutasi_barang = $this->barang->getMutasiBarangByDateAndPemilik($res->id_user_pemilik, $id_barang, $dt_user['cabang_id'], $tglAwal, $tglAkhir, $row['id_detail']);

                if($mutasi_barang[0]['no'] == $res->no_transaksi) {

                    $data['result_mutasi'][] = array(
                        'id_user_pemilik' => $res->id_user_pemilik,
                        'nm_user_pemilik' => $row['nm_user_pemilik'],
                        'nama_barang' => $row['nama_barang'],
                        'nama_satuan' => $row['nama_satuan'],
                        'stok_awal' => $this->barang->_saldo_awal_barang_by_user_pemilik($res->id_user_pemilik, $id_barang, $tgl_awal, $tgl_akhir, $row['id_detail']),
                        'mutasi_barang' => $mutasi_barang
                    );
                }
            } 

            $this->template->load('templates/dashboard', 'barang/mutasi_barang_by_id', $data);
        }


    }


    // saldo awal
    public function barang_by_cabang()
    {
        // mencari cabang by id user 
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
        $dt_cabang = $this->admin->getDataCabangByUser($dt_user['cabang_id']);

        $data['title'] = "Barang ".$dt_cabang['nama_cabang']; 
        $dt_barang = $this->admin->getBarang(); 

        $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
        $tgl_akhir = date('Y-m-d');

        $data['barang'] = array(); 
        foreach($dt_barang as $row){

            $stok_akhir = $this->barang->_saldo_awal_barang($row['id_barang'], $tgl_awal, $tgl_akhir);

            $data['barang'][] = array(
                'id_barang' => $row['id_barang'],
                'tgl' => $row['tgl'],
                'id_barang' => $row['id_barang'],
                'nama_barang' => $row['nama_barang'],
                'nama_jenis' => $row['nama_jenis'],
                'saldo_akhir' => $stok_akhir,
                'nama_satuan' => $row['nama_satuan'],
            );
        }

        $this->template->load('templates/dashboard', 'barang/saldoawal', $data);
    }

    public function detail_barang_by_cabang($id_barang) 
    {
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);

        $data['title'] = "Daftar Pemilik Aset Berdasarkan Barang";
        $data['barang'] = $this->admin->get('barang', ['id_barang' => $id_barang]);
        $data['satuan'] = $this->admin->get('satuan', ['id_satuan' => $data['barang']['satuan_id']]);

        // saldo akhir 30 hari terakhir

        $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
        $tgl_akhir = date('Y-m-d');

        // pencarian user pemilik siapa saja yang mempunyai berdasarkan dari barang masuknya masingmasing user
        $dt_user_pemilik = $this->barang->getUserPemilikFormBarangMasukByIdBarang($id_barang);

        $data['tglAwal'] = $tgl_awal;
        $data['tglAkhir'] = date("Y-m-d");  
        $data['result_mutasi'] = $this->getUserUniq($dt_user_pemilik, $tgl_awal, $tgl_akhir);
        
        $this->form_validation->set_rules('tgl_awal', 'Tanggal Awal', 'required');
        $this->form_validation->set_rules('tgl_akhir', 'Tanggal Akhir', 'required');
        if($this->form_validation->run() == false) {
            $this->template->load('templates/dashboard', 'barang/detail_pemilik_by_id', $data);
        } else {
            $id_sa = $id;
            $tglAwal = $this->input->post('tgl_awal', true);
            $tglAkhir = $this->input->post('tgl_akhir', true);

            $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
            $tgl_akhir = date('Y-m-d', strtotime('-1 days', strtotime($tglAwal)));
            $data['sa_brg'] = $this->admin->get('sa_barang', ['id_sa' => $id]);
            $data['barang'] = $this->admin->get('barang', ['id_barang' => $data['sa_brg']['barang_id']]);
            $data['satuan'] = $this->admin->get('satuan', ['id_satuan' => $data['barang']['satuan_id']]);

            $data['stok_awal'] = $this->_saldo_awal_barang($id, $tgl_awal, $tgl_akhir);
            $data['tglAwal'] = $tglAwal;
            $data['tglAkhir'] = $tglAkhir;
            $data['mutasi_barang'] = $this->barang->getMutasiBarangByDate($data['sa_brg']['barang_id'], $data['sa_brg']['cabang_id'], $data['tglAwal'], $data['tglAkhir']);

            $this->template->load('templates/dashboard', 'barang/detail_pemilik_by_id', $data);
        }
    }

    function getUserUniq($dt_user_pemilik, $tgl_awal, $tgl_akhir)
    {
        $result_mutasi = array();
        foreach($dt_user_pemilik as $row) {
            $userId   = $row['user_id_pemilik'];
            $barangId = $row['id_barang'];

            $stok = $this->barang->_saldo_awal_barang_by_user_pemilik(
                $row['user_id_pemilik'],
                $barangId,
                $tgl_awal,
                $tgl_akhir,
                $row['id_detail']
            );

            // buat key unik gabungan user + barang
            $key = $userId . '_' . $barangId;

            if (!isset($data['result_mutasi'][$key])) {
                // pertama kali ditemukan → isi data
                $data['result_mutasi'][$key] = [
                    'id_user_pemilik' => $userId,
                    'nm_user_pemilik' => $row['nm_user_pemilik'],
                    'id_barang'       => $barangId,
                    'nama_barang'     => $row['nama_barang'],
                    'nama_satuan'     => $row['nama_satuan'],
                    'stok_akhir'      => $stok,
                ];
            } else {
                // kalau sudah ada → tambahkan stok
                $data['result_mutasi'][$key]['stok_akhir'] += $stok;
            }
        }   
        return array_values($data['result_mutasi']);;
    }

    public function mutasi_barang_cabang_by_user($result)
    {
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);

        $data['title'] = "Mutasi Barang";

        // memproses dari result yang dikirim
        $res = json_decode(base64_decode($result));
        $id_barang = $res->id_barang;

        $data['barang'] = $this->admin->get('barang', ['id_barang' => $res->id_barang]);
        $data['satuan'] = $this->admin->get('satuan', ['id_satuan' => $data['barang']['satuan_id']]);

        $tgl_satu = date('Y-m-01', strtotime(date("Y-m-d")));
        $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
        $tgl_akhir = date('Y-m-d', strtotime('-1 days', strtotime($tgl_satu)));

        // pencarian user pemilik siapa saja yang mempunyai berdasarkan dari barang masuknya masingmasing user
        $this->db->where('b.user_id_pemilik', $res->id_user_pemilik);
        $dt_user_pemilik = $this->barang->getUserPemilikFormBarangMasukByIdBarang($id_barang);

        $data['tglAwal'] = $tgl_satu;
        $data['tglAkhir'] = date("Y-m-d");
        $data['result_mutasi'] = array();
        foreach($dt_user_pemilik as $row) {

            $data['result_mutasi'][] = array(
                'id_user_pemilik' => $row['user_id_pemilik'],
                'nm_user_pemilik' => $row['nm_user_pemilik'],
                'nama_barang' => $row['nama_barang'],
                'nama_satuan' => $row['nama_satuan'],
                'stok_awal' => $this->barang->_saldo_awal_barang_by_user_pemilik($row['user_id_pemilik'], $id_barang, $tgl_awal, $tgl_akhir, $row['id_detail']),
                'mutasi_barang' => $this->barang->getMutasiBarangByDateAndPemilik($row['user_id_pemilik'], $id_barang, $dt_user['cabang_id'], $data['tglAwal'], $data['tglAkhir'], $row['id_detail'])
            );
        }     
        
        $this->form_validation->set_rules('tgl_awal', 'Tanggal Awal', 'required');
        $this->form_validation->set_rules('tgl_akhir', 'Tanggal Akhir', 'required');
        if($this->form_validation->run() == false) {
            $this->template->load('templates/dashboard', 'barang/mutasi_barang_by_id', $data);
        } else {
            $tglAwal = $this->input->post('tgl_awal', true);
            $tglAkhir = $this->input->post('tgl_akhir', true);

            $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
            $tgl_akhir = date('Y-m-d', strtotime('-1 days', strtotime($tglAwal)));
            
            // pencarian user pemilik siapa saja yang mempunyai berdasarkan dari barang masuknya masingmasing user
            $this->db->where('b.user_id_pemilik', $res->id_user_pemilik);
            $dt_user_pemilik = $this->barang->getUserPemilikFormBarangMasukByIdBarang($id_barang);

            $data['tglAwal'] = $tglAwal;
            $data['tglAkhir'] = $tglAkhir;
            $data['result_mutasi'] = array();
            foreach($dt_user_pemilik as $row) {

                $data['result_mutasi'][] = array(
                    'id_user_pemilik' => $row['user_id_pemilik'],
                    'nm_user_pemilik' => $row['nm_user_pemilik'],
                    'nama_barang' => $row['nama_barang'],
                    'nama_satuan' => $row['nama_satuan'],
                    'stok_awal' => $this->barang->_saldo_awal_barang_by_user_pemilik($row['user_id_pemilik'], $id_barang, $tgl_awal, $tgl_akhir, $row['id_detail']),
                    'mutasi_barang' => $this->barang->getMutasiBarangByDateAndPemilik($row['user_id_pemilik'], $id_barang, $dt_user['cabang_id'], $tglAwal, $tglAkhir, $row['id_detail'])
                );
            } 

            $this->template->load('templates/dashboard', 'barang/mutasi_barang_by_id', $data);
        }
    }

    public function mutasi_barang_cabang($id_barang)
    {
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);

        $data['title'] = "Mutasi Barang";
        $data['barang'] = $this->admin->get('barang', ['id_barang' => $id_barang]);
        $data['satuan'] = $this->admin->get('satuan', ['id_satuan' => $data['barang']['satuan_id']]);

        // saldo akhir 30 hari terakhir

        $tgl_satu = date('Y-m-01', strtotime(date("Y-m-d")));
        $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
        $tgl_akhir = date('Y-m-d', strtotime('-1 days', strtotime($tgl_satu)));


        // pencarian user pemilik siapa saja yang mempunyai berdasarkan dari barang masuknya masingmasing user
        $dt_user_pemilik = $this->barang->getUserPemilikFormBarangMasukByIdBarang($id_barang);

        $data['tglAwal'] = $tgl_satu;
        $data['tglAkhir'] = date("Y-m-d");
        $data['result_mutasi'] = array();
        foreach($dt_user_pemilik as $row) {

            $data['result_mutasi'][] = array(
                'id_user_pemilik' => $row['user_id_pemilik'],
                'nm_user_pemilik' => $row['nm_user_pemilik'],
                'nama_barang' => $row['nama_barang'],
                'nama_satuan' => $row['nama_satuan'],
                'stok_awal' => $this->barang->_saldo_awal_barang_by_user_pemilik($row['user_id_pemilik'], $id_barang, $tgl_awal, $tgl_akhir, $row['id_detail']),
                'mutasi_barang' => $this->barang->getMutasiBarangByDateAndPemilik($row['user_id_pemilik'], $id_barang, $dt_user['cabang_id'], $data['tglAwal'], $data['tglAkhir'], $row['id_detail'])
            );
            
        }     
        
        // echo json_encode($data['result_mutasi']);
        // die;
        
        $this->form_validation->set_rules('tgl_awal', 'Tanggal Awal', 'required');
        $this->form_validation->set_rules('tgl_akhir', 'Tanggal Akhir', 'required');
        if($this->form_validation->run() == false) {
            $this->template->load('templates/dashboard', 'barang/mutasi_barang_by_id', $data);
        } else {
            $tglAwal = $this->input->post('tgl_awal', true);
            $tglAkhir = $this->input->post('tgl_akhir', true);


            $tgl_satu = date('Y-m-d', strtotime($tglAwal));
            $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
            $tgl_akhir = date('Y-m-d', strtotime('-1 days', strtotime($tgl_satu)));

            // pencarian user pemilik siapa saja yang mempunyai berdasarkan dari barang masuknya masingmasing user
            $dt_user_pemilik = $this->barang->getUserPemilikFormBarangMasukByIdBarang($id_barang);

            
            $data['tglAwal'] = $tgl_satu;
            $data['tglAkhir'] = $tglAkhir;
            $data['result_mutasi'] = array();
            foreach($dt_user_pemilik as $row) {

                $data['result_mutasi'][] = array(
                    'id_user_pemilik' => $row['user_id_pemilik'],
                    'nm_user_pemilik' => $row['nm_user_pemilik'],
                    'nama_barang' => $row['nama_barang'],
                    'nama_satuan' => $row['nama_satuan'],
                    'stok_awal' => $this->barang->_saldo_awal_barang_by_user_pemilik($row['user_id_pemilik'], $id_barang, $tgl_awal, $tgl_akhir, $row['id_detail']),
                    'mutasi_barang' => $this->barang->getMutasiBarangByDateAndPemilik($row['user_id_pemilik'], $id_barang, $dt_user['cabang_id'], $data['tglAwal'], $data['tglAkhir'], $row['id_detail'])
                );
                
            }     

            $this->template->load('templates/dashboard', 'barang/mutasi_barang_by_id', $data);
        }
    }


    // perhitungan
    public function _saldo_awal_barang($id_barang, $tgl_awal, $tgl_akhir)
    {
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);

        $getBarangById = $this->admin->get('barang', ['id_barang' => $id_barang]);
        $mutasi_barang = $this->barang->getMutasiBarangByDate($id_barang, $dt_user['cabang_id'], $tgl_awal, $tgl_akhir);

        $sisa_stok = $getBarangById['stokawal'];
        foreach ($mutasi_barang as $b) :

            switch ($b['jenis']) {
                case "in_tr":
                    $jenis = 'Mutasi Barang Masuk ke ' . $b['trs_cbg'];
                    break;
                case "out_tr":
                    $jenis = 'Mutasi Barang Keluar ke ' . $b['trs_cbg'];
                    break;
                case "in":
                    $jenis = 'Barang Masuk';
                    break;
                case "in_retur":
                    $jenis = 'Barang Retur dari ' . $b['nama_cabang'];
                    break;
                case "stkpn":
                    $jenis = 'Stok Op Name dari ' . $b['nama_cabang'];
                    break;
                default:
                    $jenis = 'Barang Keluar';
            }

            if($b['jenis'] == 'in' || $b['jenis'] == 'in_retur') {
                 $sisa_stok += $b['jml']; 
            } else if($b['jenis'] == 'in_tr' ) { 
                 $sisa_stok += $b['jml']; 
            } else if($b['jenis'] == 'stkpn' ) { 
                $sisa_stok += $b['jml']; 
            } else { 
                $sisa_stok -= $b['jml']; 
            } 
        endforeach;

        return $sisa_stok;
    }

   



































    private function _validasi_saldo_awal()
    {
        $this->form_validation->set_rules('tgl', 'Tanggal', 'required');
        $this->form_validation->set_rules('barang_id', 'Barang', 'required');
        $this->form_validation->set_rules('stok_awal', 'Stok Awal', 'required');
    }

    public function add_saldoawal()
    {
        $this->_validasi_saldo_awal();

        if ($this->form_validation->run() == false) {
            $data['now'] = date("Y-m-d");

            $data['title'] = "Tambah Saldo Barang Barang";
            $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
            $data['dt_cabang'] = $this->admin->getDataCabangByUser($dt_user['cabang_id']);

            $data['cabang'] = $this->admin->get('cabang');
            $dt_barang_all = $this->admin->get('barang');

            $dt_barang = $this->admin->getBarangByCabang($dt_user['cabang_id']);
            $usedValues = array();
            foreach($dt_barang as $row_) {
                $usedValues[] = $row_['id_barang'];
            }

            $data['barang'] = array();
            foreach($dt_barang_all as $row) {
                if(in_array($row['id_barang'], $usedValues)) {
                    $data['barang'][] = array(
                        'id_barang' => $row['id_barang'],
                        'nama_barang' => $row['nama_barang'],
                        'stts1' => 'disabled',
                        'stts2' => '(Sudah diset)',
                    );
                } else {
                    $data['barang'][] = array(
                        'id_barang' => $row['id_barang'],
                        'nama_barang' => $row['nama_barang'],
                        'stts1' => '',
                        'stts2' => '',
                    );
                }
            }
            
            // Mengenerate ID Barang
            $this->template->load('templates/dashboard', 'barang/add_saldoawal', $data);
        } else {
            $insert = $this->barang->insertSaldoAwal();

            if ($insert) {
                set_pesan('data berhasil disimpan');
                redirect('barang/barang_by_cabang');
            } else {
                set_pesan('gagal menyimpan data');
                redirect('barang/add_saldoawal');
            }
        }
    }

    public function edit_saldoawal($getId)
    {
        $id = encode_php_tags($getId);
        $this->_validasi_saldo_awal();

        if ($this->form_validation->run() == false) {
            // memperoleh data by id saldo awal
            $data['sa_brg'] = $this->admin->get('sa_barang', ['id_sa' => $id]);

            $data['title'] = "Update Saldo Awal Barang";
            $data['cabang'] = $this->admin->get('cabang');
            $data['barang'] = $this->admin->get('barang');

            $this->template->load('templates/dashboard', 'barang/edit_saldoawal', $data);
        } else {
            $input = $this->input->post(null, true);
            $update = $this->barang->updateSaldoAwal();
            
            if ($update) {
                set_pesan('data berhasil disimpan');
                redirect('barang/barang_by_cabang');
            } else {
                set_pesan('gagal menyimpan data');
                redirect('barang/edit_saldoawal/' . $id);
            }
        }
    }

    public function delete_saldoawal($getId)
    {
        $id = encode_php_tags($getId);
        if ($this->admin->delete('sa_barang', 'id_sa', $id)) {
            set_pesan('data berhasil dihapus.');
        } else {
            set_pesan('data gagal dihapus.', false);
        }

        redirect('barang/barang_by_cabang');
    }

    // tutup saldo awal

    public function getstok($getId, $id_cabang)
    {
        $id = encode_php_tags($getId);
        $query = $this->admin->cekStok($id, $id_cabang);
        output_json($query);
    }

    public function getStokDataBarang($id_barang)
    {
        $dtBarangById = $this->admin->get('barang', ['id_barang' => $id_barang]);
        $dtSatuanById = $this->admin->get('satuan', ['id_satuan' => $dtBarangById['satuan_id']]);

        $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
        $tgl_akhir = date('Y-m-d');

        try {
            $stok_terakhir = $this->_saldo_awal_barang($id_barang, $tgl_awal, $tgl_akhir);
            $result = array(
                'id_barang' => $id_barang,
                'stok' => $stok_terakhir,
                'nama_satuan' => $dtSatuanById['nama_satuan'],
            );
            output_json($result);
        } catch (Exception $e) {
            output_json(['error' => $e->getMessage()]);
        }
    }

    public function getstoktransfer($getId, $awal_cabang, $akhir_cabang)
    {
        $id = encode_php_tags($getId);
        $query = $this->admin->cekStokTransfer($id, $awal_cabang, $akhir_cabang);
        output_json($query);
    }

    public function mutasi_barang($id)
    {
        $data['title'] = "Mutasi Barang";
        $data['barang'] = $this->admin->get('barang', ['id_barang' => $id]);

        $data['satuan'] = $this->admin->get('satuan', ['id_satuan' => $data['barang']['satuan_id']]);
        $data['mutasi_barang'] = $this->barang->getMutasiBarang($id);

        $this->template->load('templates/dashboard', 'barang/mutasi_barang', $data);
    }
}
