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

class Barangkeluar extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        cek_login();
        date_default_timezone_set('Asia/Jakarta');
        $this->load->model('Menu_model', 'menu');
        $this->menu->aksesUser($this->session->userdata('login_session')['role']);

        $this->load->model('Admin_model', 'admin');
        $this->load->library('form_validation');
        $this->load->model('Barang_model', 'barang');
    }

    public function index()
    {
        $data['title'] = "Barang keluar";
        $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['barangkeluar'] = $this->admin->getBarangKeluarByCabang($data['dt_user']['cabang_id'], $range);

        // echo json_encode($data['barangkeluar']);
        // die;


        $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_keluar/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['barangkeluar'] = $this->admin->getBarangKeluarByCabang($data['dt_user']['cabang_id'], $range);

            $this->template->load('templates/dashboard', 'barang_keluar/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('bmk.tanggal_keluar', 'ASC');
        if(empty($categori)) {
            $dt_all = $this->admin->getBarangKeluarByCabang($dt_user['cabang_id'], $range);        
        } else {
            $dt_all = $this->admin->getBarangKeluarByCabang($dt_user['cabang_id'], $range, $categori);
        }

        $dt_header = array(
            'judul' => 'Laporan Barang Keluar',
            '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-keluar_'.date('dmY'),
        );

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

    private function _validasi()
    {
        $this->form_validation->set_rules('tanggal_keluar', 'Tanggal Keluar', 'required|trim');
        $this->form_validation->set_rules('cabang_id', 'Lokasi', '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 Keluar";
            $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 keluar
            $kode = 'BK-' . date('ymd');
            $kode_terakhir = $this->admin->getMax('barang_keluar', 'id_barang_keluar', $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_keluar'] = $kode . $number;

            $this->template->load('templates/dashboard', 'barang_keluar/add', $data);
        } else {

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

            if ($insert) {
                set_pesan('data berhasil disimpan.');
                redirect('barangkeluar');
            } else {
                set_pesan('Opps ada kesalahan!');
                redirect('barangkeluar/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 Keluar";
            $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();
            
            $data['brg'] = $this->barang->getBarangKeluarById($id);
            
            
            if($dt_user['nama'] != $data['brg']['nm_user']) { 
                set_pesan('Edit data gagal. Data milik '.$data['brg']['nama']);
                redirect('barangkeluar');
            }
            
            
            $d_brg = $this->barang->getDetailBarangKeluarById($id);

            $tgl_awal = date('Y-m-d', strtotime('1/1/1971'));
            $tgl_akhir = date('Y-m-d', strtotime('-1 days', strtotime($data['brg']['tanggal_keluar'])));

            // memperoleh data stok terbaru
            $data['d_brg'] = array();
            foreach($d_brg as $row) {
                $stok_awal = $this->barang->_saldo_awal_barang_by_user_pemilik($row['id_user_pemilik'], $row['id_barang'], $tgl_awal, $tgl_akhir);

                $data['d_brg'][] = array(
                    'id_detail' => $row['id_detail'],
                    'id_barang' => $row['id_barang'],
                    'id_user_pemilik' => $row['id_user_pemilik'],
                    'user_pemilik' => $row['nm_user_pemilik'],
                    'tanggal_masuk' => $row['tanggal_masuk'],
                    'merk' => $row['merk'],
                    'spesifikasi' => $row['spesifikasi'],
                    'barcode' => $row['barcode'],
                    'sn' => $row['sn'],
                    'nama_barang' => $row['nama_barang'],
                    'jumlah' => $row['jumlah'],
                    'stok_real' => $stok_awal+$row['jumlah'],
                );
            }
            
            $this->template->load('templates/dashboard', 'barang_keluar/edit', $data);
        } else {
            $insert = $this->barang->editBarangKeluar($id);

            if ($insert) {
                set_pesan('data berhasil disimpan.');
                redirect('barangkeluar');
            } else {
                set_pesan('Opps ada kesalahan!');
                redirect('barangkeluar/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->getBarangKeluarById($id);
        if($dt_user['nama'] != $data['brg']['nm_user']) { 
            set_pesan('Data gagal diHapus. Data milik '.$data['brg']['nama']);
            redirect('barangkeluar');
        }
        
        
        if ($this->barang->delete('barang_keluar', 'id_barang_keluar', $id)) {
            set_pesan('data berhasil dihapus.');
        } else {
            set_pesan('data gagal dihapus.', false);
        }
        redirect('barangkeluar');
    }

    public function show_barangkeluar()
    {
        $data['dt_user'] = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
        $id_barangkeluar = $this->input->post('id');
        $data['brg'] = $this->barang->getBarangKeluarById($id_barangkeluar);
        $data['d_brg'] = $this->barang->getDetailBarangKeluarById($id_barangkeluar);

        $this->load->view('barang_keluar/detail_barangkeluar', $data);
    }

    public function cetak_bkluar($id_barangkeluar)
    {
        $brg = $this->barang->getBarangKeluarById($id_barangkeluar);
        $d_brg = $this->barang->getDetailBarangKeluarById($id_barangkeluar);

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

        $pdf->AddPage();

        $pdf->SetFont('Times', 'B', 16);
        $pdf->Cell(190, 7, 'Invoice Barang Keluar', 0, 1, 'C');


        $pdf->Ln(10);
        $pdf->SetFont('Times', '', 9);
        $pdf->Cell(45, 2, 'Id Barang Keluar', 0, 0, 'L');
        $pdf->Cell(5, 2, ':', 0, 0, 'L');
        $pdf->Cell(45, 2, $brg['id_barang_keluar'], 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_keluar'], 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(60, 7, 'Pemilik Aset', 1, 0, 'C');
        $pdf->Cell(30, 7, 'Id Barang', 1, 0, 'C');
        $pdf->Cell(60, 7, 'Nama Barang', 1, 0, 'C');
        $pdf->Cell(30, 7, 'Stok', 1, 0, 'C');
        $pdf->SetWidths(array(10, 60, 30, 60, 30));
        $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['nm_user_pemilik'], $d['id_barang'], $d['nama_barang'], $d['jumlah'] . ' ' . $d['nama_satuan']));
        }
        $pdf->Ln(2);
        $pdf->SetFont('Times', '', 9);
        $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();
    }

}
