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

class Transferbarang 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('Transfer_model', 'transfer');
        $this->load->library('form_validation');
        $this->load->model('Barang_model', 'barang');
    }

    public function index()
    {
        $data['title'] = "Transfer Barang";
        $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)));

        $data['tglAwal'] = $tgl_awal;
        $data['tglAkhir'] = $tgl_akhir;

        // menampilkan daftar barang yang ditransfer, ditampilkan dalam cabang awal, dan cabang tujuan
        $data['transfer_barang'] = $this->transfer->getDataTransfer($tgl_awal, $tgl_akhir, $dt_user['cabang_id']);
        $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', 'transfer_barang/data', $data);
        } else {
            $tglAwal = $this->input->post('tgl_awal', true);
            $tglAkhir = $this->input->post('tgl_akhir', true);

            $data['tglAwal'] = $tglAwal;
            $data['tglAkhir'] = $tglAkhir;
            $data['transfer_barang'] = $this->transfer->getDataTransfer($tglAwal, $tglAkhir, $dt_user['cabang_id']);
            
            $this->template->load('templates/dashboard', 'transfer_barang/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']]);


        $this->db->order_by('a.tgl_transfer', 'ASC');
        if(empty($categori)) {
            $dt_all = $this->transfer->getDataTransfer($tglAwal, $tglAkhir, $dt_user['cabang_id']);        
        } else {
            $dt_all = $this->transfer->getDataTransfer($tglAwal, $tglAkhir, $dt_user['cabang_id'], $categori);
        }

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

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

    private function _validasi()
    {
        $this->form_validation->set_rules('tgl_transfer', 'Tanggal Transfer', 'required');
        $this->form_validation->set_rules('asal_cabang', 'Asal Cabang', 'required');
        $this->form_validation->set_rules('tujuan_cabang', 'Tujuan Cabang', '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'];
            date_default_timezone_set('Asia/Jakarta');
            $data['date_now'] = date("Y-m-d");

            $data['title'] = "Transfer Barang";
            $data['barang'] = $this->admin->getBarangByCabang($dt_user['cabang_id']);

            $data['supplier'] = $this->admin->get('supplier');
            $data['cabang'] = $this->admin->get('cabang');
            $data['barang_opt'] = $this->barang->getBarangOptTf($dt_user['cabang_id']);
            $data['user_pemilik'] = $this->admin->getUserByRole(3);

            // Mendapatkan dan men-generate kode transaksi transfer barang
            $kode = 'TR-' . date('ymd');
            $kode_terakhir = $this->admin->getMax('transfer_barang', 'kode_transfer', $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['kode_transfer'] = $kode . $number;

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

            if ($insert) {
                set_pesan('data berhasil disimpan.');
                redirect('transferbarang');
            } else {
                set_pesan('Opps ada kesalahan!');
                redirect('transferbarang/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'] = "Transfer Barang";
            $data['barang'] = $this->admin->getBarangByCabang($dt_user['cabang_id']);
            
            $data['supplier'] = $this->admin->get('supplier');
            $data['cabang'] = $this->admin->get('cabang');
            $data['user_pemilik'] = $this->admin->getUserByRole(3);


            $data['barang_opt'] = $this->barang->getBarangOptTf($dt_user['cabang_id']);
            $data['transfer'] = $this->admin->get('transfer_barang', ['id_transfer' => $id]);

            $d_brg = $this->transfer->getDetailBarangTransferById($id);

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

            // 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_masuk'],
                    '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', 'transfer_barang/edit', $data);
        } else {
            $input = $this->input->post(null, true);
            $insert = $this->transfer->editTransfer($id);

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

    public function delete($getId)
    {
        $id = encode_php_tags($getId);
        if ($this->transfer->delete('transfer_barang', 'id_transfer', $id)) {
            set_pesan('data berhasil dihapus.');
        } else {
            set_pesan('data gagal dihapus.', false);
        }
        redirect('transferbarang');
    }

    public function show_detailtransfer()
    {
        $id = $this->input->post('id');
        $data['transfer'] = $this->transfer->getTransferById($id);
        $data['detail_transfer'] = $this->transfer->getDetailBarangTransferById($id);

        $this->load->view('transfer_barang/detail_transferbarang', $data);
    }

    public function cetak_transfer($id)
    {
        $transfer = $this->transfer->getTransferById($id);
        $detail_transfer = $this->transfer->getDetailBarangTransferById($id);

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

        $pdf->AddPage();

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

        $pdf->Ln(10);
        $pdf->SetFont('Times', '', 9);
        $pdf->Cell(45, 2, ' Kode Transfer', 0, 0, 'L');
        $pdf->Cell(5, 2, ':', 0, 0, 'L');
        $pdf->Cell(45, 2, $transfer['kode_transfer'], 0, 1, 'L');
        $pdf->Ln();
        $pdf->Cell(45, 2, 'Tanggal', 0, 0, 'L');
        $pdf->Cell(5, 2, ':', 0, 0, 'L');
        $pdf->Cell(45, 2, $transfer['tgl_transfer'], 0, 1, 'L');
        $pdf->Ln();
        $pdf->Cell(45, 2, 'Asal Cabang', 0, 0, 'L');
        $pdf->Cell(5, 2, ':', 0, 0, 'L');
        $pdf->Cell(45, 2, $transfer['nama_asal'], 0, 1, 'L');
        $pdf->Ln();
        $pdf->Cell(45, 2, 'Tujuan Cabang', 0, 0, 'L');
        $pdf->Cell(5, 2, ':', 0, 0, 'L');
        $pdf->Cell(45, 2, $transfer['nama_tujuan'], 0, 1, 'L');
        $pdf->Ln();
        $pdf->Cell(45, 2, 'Admin', 0, 0, 'L');
        $pdf->Cell(5, 2, ':', 0, 0, 'L');
        $pdf->Cell(45, 2,  $transfer['nama'], 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 ($detail_transfer 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, $transfer['keterangan'], 0, 1, 'L');
        $pdf->Ln();

        $pdf->Output();
    }

    
}
