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

class Barangmasuk extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        cek_login();
        $this->load->model('Menu_model', 'menu');
        $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 Masuk";
        $data['dt_user'] = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);

        $tgl_akhir = date("Y-m-d");
        $tgl_awal = date('Y-m-d', strtotime('-30 days', strtotime($tgl_akhir)));
        $range = array(
            'mulai' => $tgl_awal,
            'akhir' => $tgl_akhir,
        );
        $data['tglAwal'] = $tgl_awal;
        $data['tglAkhir'] = $tgl_akhir;
        $data['barangmasuk'] = $this->admin->getBarangMasukByCabang($data['dt_user']['cabang_id'], $range, null);


        $data['dt_category'] = $this->admin->get('jenis');        

        $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_masuk/data', $data);
        } else {
            $tglAwal = $this->input->post('tgl_awal', true);
            $tglAkhir = $this->input->post('tgl_akhir', true);

            // memperoleh data by tanggal
            $range = array(
                'mulai' => $tglAwal,
                'akhir' => $tglAkhir,
            );
            $data['tglAwal'] = $tglAwal;
            $data['tglAkhir'] = $tglAkhir;
            $data['barangmasuk'] = $this->admin->getBarangMasukByCabang($data['dt_user']['cabang_id'], $range, null);

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

    public function print()
    {
        $tglAwal  = date("Y-m-d", strtotime($this->input->post('tgl_awal', true)));
        $tglAkhir = date("Y-m-d", strtotime($this->input->post('tgl_akhir', true)));
        $categori = $this->input->post('id_categori', true);

        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
        
        $range = array(
            'mulai' => $tglAwal,
            'akhir' => $tglAkhir,
        );


        $this->db->order_by('bmsk.tanggal_masuk', 'ASC');
        if(empty($categori)) {
            $dt_all = $this->admin->getBarangMasukByCabang($dt_user['cabang_id'], $range);        
        } else {
            $dt_all = $this->admin->getBarangMasukByCabang($dt_user['cabang_id'], $range, $categori);
        }

        $dt_header = array(
            'judul' => 'Laporan Barang Masuk',
            'profile' => $this->db->get_where('profile', ['id_profile' => 1])->row_array(),
            'cabang' => $this->db->get_where('cabang', ['id_cabang' => $dt_user['cabang_id']])->row_array(),
            'periode' => convertIndoDate($tglAwal) . ' s/d ' . convertIndoDate($tglAkhir),
            'nm_file' => 'laporan-barang-masuk_'.date('dmY'),
        );

        if(isset($_POST['pdf'])) {
            $this->load->library('PDF_MC_Table');
            $this->admin->cetak_laporan($dt_header, $dt_all, 1);
        }
    }

    private function _validasi()
    {
        $this->form_validation->set_rules('tanggal_masuk', 'Tanggal Masuk', 'required|trim');
        $this->form_validation->set_rules('user_id_pemilik', 'User Pemilik', 'required');
    }

    public function add()
    {
        $this->_validasi();
        if ($this->form_validation->run() == false) {
            $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
            $data['cabang_id'] = $dt_user['cabang_id'];

            $data['title'] = "Barang Masuk";
            $data['barang'] = $this->admin->getBarang();

            // $this->db->where('cabang_id',$dt_user['cabang_id']);
            $data['user_pemilik'] = $this->admin->getUserByRole(3);
            $data['cabang'] = $this->admin->get('cabang');
            $data['barang_opt'] = $this->barang->getBarangOpt();


            // Mendapatkan dan men-generate kode transaksi barang masuk
            $kode = 'BM-' . date('ymd');
            $kode_terakhir = $this->admin->getMax('barang_masuk', 'id_barang_masuk', $kode);

            // cek apakah ada hasil dari getMax
            if ($kode_terakhir) {
                $kode_tambah = substr($kode_terakhir, -5); // ambil 5 digit terakhir
                $kode_tambah = (int)$kode_tambah; // paksa jadi integer
            } else {
                $kode_tambah = 0; // kalau belum ada data, mulai dari 0
            }

            $kode_tambah++;
            $number = str_pad($kode_tambah, 5, '0', STR_PAD_LEFT);

            $data['id_barang_masuk'] = $kode . $number;


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

            $insert = $this->barang->insertBarangMasuk();

            if ($insert) {
                set_pesan('data berhasil disimpan.');
                redirect('barangmasuk');
            } else {
                set_pesan('Opps ada kesalahan!');
                redirect('barang_masuk/add');
            }
        }
    }

    public function edit($id)
    {
        $this->_validasi();
        if ($this->form_validation->run() == false) {
            $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
            $data['cabang_id'] = $dt_user['cabang_id'];

            $data['title'] = "Barang Masuk";
            $data['barang'] = $this->admin->getBarang();

            // $this->db->where('cabang_id',$dt_user['cabang_id']);
            $data['user_pemilik'] = $this->admin->getUserByRole(3);
            $data['cabang'] = $this->admin->get('cabang');
            $data['barang_opt'] = $this->barang->getBarangOpt();
            
            // pengecekan dahulu apakah ini data yang diinputkan
        
            $data['brg'] = $this->barang->getBarangMasukById($id);
            $data['d_brg'] = $this->barang->getDetailBarangMasukById($id);
            
            if($dt_user['nama'] != $data['brg']['nm_user']) { 
                set_pesan('Edit data gagal. Data milik '.$data['brg']['nama']);
                redirect('barangmasuk');
            }

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

            // memperoleh data stok terbaru
            $data['detail_brg'] = array();
            $data['total_beli'] = 0;
            foreach($data['d_brg'] as $row) {
                $getBarangById = $this->barang->getMutasiBarang($row['id_barang']);

                $stok_terkini = 0;
                foreach($getBarangById as $row_){

                    if($row_['jenis'] == 'in'){
                        // barang masuk
                        $stok_terkini += $row_['jml']; 
                    } else if($row_['jenis'] == 'out'){ 
                        // barang keluar
                        $stok_terkini -= $row_['jml']; 
                    } 
                }


                $data['detail_brg'][] = array(
                    'id_barang' => $row['id_barang'],
                    'stok_real' => $row['stokawal'] + $stok_terkini,
                    'stok_terkini' => $stok_terkini,
                    'jumlah' => $row['jumlah'],
                    'nama_barang' => $row['nama_barang'],
                    'nama_satuan' => $row['nama_satuan'],
                    'merk' => $row['merk'],
                    'spesifikasi' => $row['spesifikasi'],
                    'barcode' => $row['barcode'],
                    'sn' => $row['sn'],
                );


                $data['total_beli'] =  $row['jumlah'];
            }


            $this->template->load('templates/dashboard', 'barang_masuk/edit', $data);
        } else {
            // $input = $this->input->post(null, true);
            // $input = array_except($input, 'cabang_id');

            $insert = $this->barang->editBarangMasuk($id);

            if ($insert) {
                set_pesan('data berhasil disimpan.');
                redirect('barangmasuk');
            } else {
                set_pesan('Opps ada kesalahan!');
                redirect('barang_masuk/edit');
            }
        }
    } 

    public function delete($getId)
    {
        $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
        $id = encode_php_tags($getId);
        $data['brg'] = $this->barang->getBarangMasukById($id);
        if($dt_user['nama'] != $data['brg']['nm_user']) { 
            set_pesan('Data gagal diHapus. Data milik '.$data['brg']['nama']);
            redirect('barangmasuk');
        }
            
        if ($result = $this->barang->delete('barang_masuk', 'id_barang_masuk', $id)) {
            set_pesan('data berhasil dihapus.');
        } else {
            set_pesan('data gagal dihapus.', false);
        }
        redirect('barangmasuk');
    }

    public function show_barangmasuk()
    {
        $data['dt_user'] = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
        $id_barangmasuk = $this->input->post('id');
        $data['brg'] = $this->barang->getBarangMasukById($id_barangmasuk);
        $data['d_brg'] = $this->barang->getDetailBarangMasukById($id_barangmasuk);

        $this->load->view('barang_masuk/detail_barangmasuk', $data);
    }

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

        $id_barang = $this->input->post('id_barang');
        $id_user_pemilik = $this->input->post('id_user_pemilik');
        $tgl = $this->input->post('tgl');
        $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
        $tgl_akhir = date('Y-m-d', strtotime($tgl));

        // echo json_encode($tgl);
        // die;

        // mencari stok akhir barang berdasarkan id barang dan cabang
        $dt_barang = $this->admin->get('barang', ['id_barang' => $id_barang]);
        $dt_satuan = $this->admin->get('satuan', ['id_satuan' => $dt_barang['satuan_id']]);
        $stokakhir = $this->barang->_stokakhir_barang_by_user_pemilik($id_user_pemilik, $id_barang, $tgl_awal, $tgl_akhir);


        if ($stokakhir) {
            echo json_encode([
                'status' => true,
                'data' => [
                    'nama_barang' => $dt_barang['nama_barang'],
                    'nama_satuan' => $dt_satuan['nama_satuan'],
                    'stok_akhir' => $stokakhir,

                ]
            ]);
        } else {
            echo json_encode(['status' => false]);
        }
    }

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

        $id_user = $this->input->post('user_id');
        $tgl = $this->input->post('tgl');

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

        // 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($row['id_user_pemilik'], $row['id_barang'], $tgl_awal, $tgl_akhir, $row['id_detail']);

            if($stokakhir != 0) {
                $res_kirim_data = array(
                    'id_detail' => $row['id_detail'],
                    'id_barang_masuk' => $row['id_barang_masuk'],
                    'tanggal_masuk' => $row['tanggal_masuk'],
                    'id_user_pemilik' => $row['id_user_pemilik'],
                    'user_pemilik' => $row['nm_user_pemilik'],
                    'id_barang' => $row['id_barang'],
                    'saldo_stok' => $stokakhir,
                    'nama_barang' => $row['nama_barang'],
                    'nama_satuan' => $row['nama_satuan'],
                    'merk' => $row['merk'],
                    'spesifikasi' => $row['spesifikasi'],
                    'barcode' => $row['barcode'],
                    'sn' => $row['sn'],
                );

                $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_stok' => $stokakhir,
                    'nama_barang' => $row['nama_barang'],
                    'merk' => $row['merk'],
                    'spesifikasi' => $row['spesifikasi'],
                    'barcode' => $row['barcode'],
                    'sn' => $row['sn'],
                    'res_send_data' => base64_encode(json_encode($res_kirim_data)),
                );
            }

        }

        echo json_encode($result);
    }

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

        $id_user = $this->input->post('user_id');
        $tgl = $this->input->post('tgl');
        $id_barang = $this->input->post('barangId');

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

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

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

            if($stokakhir != 0) {
                $res_kirim_data = array(
                    'id_detail' => $row['id_detail'],
                    'id_barang_masuk' => $row['id_barang_masuk'],
                    'tanggal_masuk' => $row['tanggal_masuk'],
                    'id_user_pemilik' => $row['id_user_pemilik'],
                    'user_pemilik' => $row['nm_user_pemilik'],
                    'id_barang' => $row['id_barang'],
                    'saldo_stok' => $stokakhir,
                    'nama_barang' => $row['nama_barang'],
                    'nama_satuan' => $row['nama_satuan'],
                    'merk' => $row['merk'],
                    'spesifikasi' => $row['spesifikasi'],
                    'barcode' => $row['barcode'],
                    'sn' => $row['sn'],
                );

                $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_stok' => $stokakhir,
                    'nama_barang' => $row['nama_barang'],
                    'merk' => $row['merk'],
                    'spesifikasi' => $row['spesifikasi'],
                    'barcode' => $row['barcode'],
                    'sn' => $row['sn'],
                    'res_send_data' => base64_encode(json_encode($res_kirim_data)),
                );
            }

        }

        echo json_encode($result);
    }

    public function cetak_bmasuk($id)
    {
        $brg = $this->barang->getBarangMasukById($id);
        $d_brg = $this->barang->getDetailBarangMasukById($id);

        // $data['brg'] = $this->barang->getBarangMasukById($id_barangmasuk);
        // $data['d_brg'] = $this->barang->getDetailBarangMasukById($id_barangmasuk);

        $this->load->library('PDF_MC_Table');
        $pdf = new PDF_MC_Table();

        $pdf->AddPage();
     
        $pdf->SetFont('Times', 'B', 16);
        $pdf->Cell(190, 7, 'Invoice Barang Masuk', 0, 1, 'C');
     
 
        $pdf->Ln(10);
        $pdf->SetFont('Times', '', 9);
        $pdf->Cell(45, 2, 'Id Barang Masuk', 0, 0, 'L');
        $pdf->Cell(5, 2, ':', 0, 0, 'L');
        $pdf->Cell(45, 2, $brg['id_barang_masuk'], 0, 1, 'L');
        $pdf->Ln();
        $pdf->Cell(45, 2, 'Tanggal', 0, 0, 'L');
        $pdf->Cell(5, 2, ':', 0, 0, 'L');
        $pdf->Cell(45, 2, $brg['tanggal_masuk'], 0, 1, 'L');
        $pdf->Ln();
        $pdf->Cell(45, 2, 'Nama User Pemilik', 0, 0, 'L');
        $pdf->Cell(5, 2, ':', 0, 0, 'L');
        $pdf->Cell(45, 2, $brg['nm_user_pemilik'], 0, 1, 'L');
        $pdf->Ln();
        $pdf->Cell(45, 2, 'Nama Cabang', 0, 0, 'L');
        $pdf->Cell(5, 2, ':', 0, 0, 'L');
        $pdf->Cell(45, 2, $brg['nama_cabang'], 0, 1, 'L');
        $pdf->Ln();
        $pdf->Cell(45, 2, 'Admin', 0, 0, 'L');
        $pdf->Cell(5, 2, ':', 0, 0, 'L');
        $pdf->Cell(45, 2, $brg['nm_user'], 0, 1, 'L');
        $pdf->Ln();
        $pdf->SetFont('Times', 'B', 8);
        $pdf->Cell(10, 7, 'No.', 1, 0, 'C');
        $pdf->Cell(15, 7, 'Id Barang', 1, 0, 'C');
        $pdf->Cell(40, 7, 'Nama Barang', 1, 0, 'C');
        $pdf->Cell(20, 7, 'Stok', 1, 0, 'C');
        $pdf->Cell(20, 7, 'Merk', 1, 0, 'C');
        $pdf->Cell(45, 7, 'Spesifikasi', 1, 0, 'C');
        $pdf->Cell(20, 7, 'Barcode', 1, 0, 'C');
        $pdf->Cell(20, 7, 'Serial Number', 1, 0, 'C');
        $pdf->SetWidths(array(10, 15, 40, 20, 20, 45, 20, 20));
        $pdf->Ln();
        //Table with 20 rows and 4 columns
        $pdf->SetFont('Times', '', 8);
        $pdf->SetLineHeight(7);
        $no = 1;
        foreach ($d_brg as $d) {
            $pdf->Row(array($no++,  $d['id_barang'], $d['nama_barang'], $d['jumlah'].' '.$d['nama_satuan'], $d['merk'], $d['spesifikasi'], $d['barcode'], $d['sn']));
        }
        $pdf->Ln(2);
        $pdf->SetFont('Times', '', 9);
        $pdf->Cell(45, 2, 'Status', 0, 0, 'L');
        $pdf->Cell(5, 2, ':', 0, 0, 'L');
        $pdf->Cell(45, 2, $brg['stts_perolehan'], 0, 1, 'L');
        $pdf->Ln();
        $pdf->Cell(45, 2, 'Movement', 0, 0, 'L');
        $pdf->Cell(5, 2, ':', 0, 0, 'L');
        $pdf->Cell(45, 2, $brg['stts_penggunaan'], 0, 1, 'L');
        $pdf->Ln();
        $pdf->Cell(45, 2, 'Keterangan', 0, 0, 'L');
        $pdf->Cell(5, 2, ':', 0, 0, 'L');
        $pdf->Cell(45, 2, $brg['ket'], 0, 1, 'L');
        $pdf->Ln();

        $pdf->Output();
    }

}
