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

// Include librari PhpSpreadsheet
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
class Impor 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->model('Transfer_model', 'transfer');
        $this->load->library('form_validation');
    }

    public function laporan($stts)
    {
        $data['title'] = "Impor ".get_stts_impor($stts);
        $this->db->where_in('stts', $stts);
        $data['impor'] = $this->admin->get('impor');
        $data['id_stts'] = $stts;
        $this->template->load('templates/dashboard', 'impor/data', $data);
    }

    public function detail($id_impor) 
    {
        $data['dt_user'] = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
        $dt_impor = $this->admin->get('impor', ['id_impor' => $id_impor]);

        $data['title'] = "Detail Import ".get_stts_impor($dt_impor['stts']);

        $data['tglAkhir'] = date("Y-m-d");
        $data['tglAwal'] = date('Y-m-d', strtotime('-30 days', strtotime($data['tglAkhir'])));

        $data['dt_category'] = $this->admin->get('jenis');  
        if($dt_impor['stts'] == 1) {
            // barang masuk
            $data['barangmasuk'] = $this->admin->getBarangMasukByCabang($data['dt_user']['cabang_id'], null, null, $id_impor);
            $data['stts_impor'] = 1;
            $this->template->load('templates/dashboard', 'barang_masuk/data', $data);
        } else if($dt_impor['stts'] == 2) {
            $data['stts_impor'] = 1;
            $data['barangkeluar'] = $this->admin->getBarangKeluarByCabang($data['dt_user']['cabang_id'], null, null, $id_impor);
            $this->template->load('templates/dashboard', 'barang_keluar/data', $data);
        } else if($dt_impor['stts'] == 3) {
            $data['stts_impor'] = 1;
            $data['transfer_barang'] = $this->transfer->getDataTransfer(null, null, $data['dt_user']['cabang_id'], null, $id_impor);
            $this->template->load('templates/dashboard', 'transfer_barang/data', $data);
        } else if($dt_impor['stts'] == 4) {
            $data['stts_impor'] = 1;
            $data['barangkeluar'] = $this->barang->getStockOpNameByCabang($data['dt_user']['cabang_id'], null, null, $id_impor);
            $this->template->load('templates/dashboard', 'stock_op_name/data', $data);
        }
    }

    private function _validasi()
    {
        $this->form_validation->set_rules('file_impor', 'File Impor', 'callback_file_impor_check');
    }

    public function file_impor_check($str)
    {
        if (isset($_FILES['file_impor']) && $_FILES['file_impor']['size'] > 0) {
            return TRUE; // ada file
        } else {
            $this->form_validation->set_message('file_impor_check', '{field} wajib diupload');
            return FALSE; // tidak ada file
        }
    }

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

        $data['stts'] = $id_stts;

        if ($this->form_validation->run() == false) {
            $data['title'] = "Form Impor Data " .get_stts_impor($id_stts);
            $data['id_stts'] = $id_stts;
            $this->template->load('templates/dashboard', 'impor/add', $data);
        } else {
            $dt_user = $this->admin->get('user', ['id_user' => $this->session->userdata('login_session')['user']]);
            $dt_cabang = $this->admin->get('cabang', ['id_cabang' => $dt_user['cabang_id']]);

            date_default_timezone_set('Asia/Jakarta');
            $now = date("Y-m-d H:i:s");

            $tgl_sekarang = date('YmdHis'); // Ini akan mengambil waktu sekarang dengan format yyyymmddHHiiss
            $nama_file_baru = 'dt_impor_stts_'. $id_stts .'_' . $tgl_sekarang . '.xlsx';
            
            $destination_path = FCPATH . 'assets/file/impor/' . $nama_file_baru;
            // Cek apakah terdapat file data.xlsx pada folder tmp
            if (is_file( $destination_path)) // Jika file tersebut ada
                unlink( $destination_path); // Hapus file tersebut
                
            $ext = pathinfo($_FILES['file_impor']['name'], PATHINFO_EXTENSION); // Ambil ekstensi filenya apa
            $tmp_file = $_FILES['file_impor']['tmp_name'];
                        
                
            // Cek apakah file yang diupload adalah file Excel 2007 (.xlsx)
            if ($ext == "xlsx") {
                // Upload file yang dipilih ke folder tmp
                // dan rename file tersebut menjadi data{tglsekarang}.xlsx
                // {tglsekarang} diganti jadi tanggal sekarang dengan format yyyymmddHHiiss
                // Contoh nama file setelah di rename : data20210814192500.xlsx
                
                move_uploaded_file($tmp_file, $destination_path);
                $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
                $spreadsheet = $reader->load($destination_path); // Load file yang tadi diupload ke folder tmp
                $sheet = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
                
                $numrow = 1;
                $data_import = array();
                $tmp_group = array(); // penampung sementara
                foreach ($sheet as $row) { 

                    if($id_stts == 1) {
                        // barang masuk
                        if ($numrow > 1) { // Mulai dari baris kedua
                            if ($row['A'] == null && $row['B'] == null && $row['C'] == null && $row['D'] == null) {
                                // echo 'tidak';
                            } else {
                                $dt_user_pemilik = $this->admin->get('user', ['username' => $row['B']]);
                                $dt_barang = $this->admin->get('barang', ['id_barang' => $row['C']]);
                                // continue; // Lewat data pada baris ini (masuk ke looping selanjutnya / baris
                                // key gabungan (tgl + username)
                                $key = date('Y-m-d', strtotime($row['A'])) . '_' . $row['B'];

                                // buat jika belum ada
                                if(!isset($tmp_group[$key])) {
                                    $tmp_group[$key] = array(
                                        'tgl' => date('Y-m-d', strtotime($row['A'])),
                                        'username' => $row['B'],
                                        'id_user_pemilik' => $dt_user_pemilik['id_user'],
                                        'id_user' => $dt_user['id_user'],
                                        'cabang_id' => $dt_user['cabang_id'],
                                        'nama_cabang' => $dt_cabang['nama_cabang'],
                                        'status'      => $row['I'],
                                        'movement'    => $row['J'],
                                        'ket'         => $row['K'],
                                        'dt_array'    => array()
                                    );
                                }

                                // masukkan detail barang ke dalam dt_array
                                $tmp_group[$key]['dt_array'][] = array(
                                    'id_barang'   => $row['C'],
                                    'nama_barang' => $dt_barang['nama_barang'],
                                    'jumlah'      => intval($row['D']),
                                    'merk'        => $row['E'],
                                    'spesifikasi' => $row['F'],
                                    'barcode'     => $row['G'],
                                    'sn'          => $row['H'],
                                );  
                            }
                        }

                    } else if($id_stts == 2) {
                        // mengumpulkan data barang keluar dari impor
                        // barang keluar
                        if ($numrow > 1) { // Mulai dari baris kedua
                            if ($row['A'] == null && $row['B'] == null && $row['C'] == null && $row['D'] == null) {
                                // echo 'tidak';
                            } else {
                                $dt_user_pemilik = $this->admin->get('user', ['username' => $row['B']]);
                                $dt_barang = $this->admin->get('barang', ['id_barang' => $row['C']]);
                                // continue; // Lewat data pada baris ini (masuk ke looping selanjutnya / baris
                                // key gabungan (tgl + username)
                                $key = date('Y-m-d', strtotime($row['A'])) . '_' . $row['B'];

                                // buat jika belum ada
                                if(!isset($tmp_group[$key])) {
                                    $tmp_group[$key] = array(
                                        'tgl' => date('Y-m-d', strtotime($row['A'])),
                                        'username' => $row['B'],
                                        'id_user' => $dt_user['id_user'],
                                        'cabang_id' => $dt_user['cabang_id'],
                                        'nama_cabang' => $dt_cabang['nama_cabang'],
                                        'ket'         => $row['E'],
                                        'dt_array'    => array()
                                    );
                                }

                                // masukkan detail barang ke dalam dt_array
                                $tmp_group[$key]['dt_array'][] = array(
                                    'id_user_pemilik' => $dt_user_pemilik['id_user'],
                                    'id_barang'   => $row['C'],
                                    'nama_barang' => $dt_barang['nama_barang'],
                                    'jumlah'      => intval($row['D']),
                                );  
                            }
                        }

                    } else if($id_stts == 3) {
                        // barang transfer
                        if ($numrow > 1) { // Mulai dari baris kedua
                            if ($row['A'] == null && $row['B'] == null && $row['C'] == null && $row['D'] == null && $row['E'] == null) {
                                // echo 'tidak';
                            } else {
                                $dt_user_pemilik = $this->admin->get('user', ['username' => $row['C']]);
                                $dt_barang = $this->admin->get('barang', ['id_barang' => $row['D']]);
                                $dt_cabang_tujuan = $this->admin->get('cabang', ['id_cabang' => $row['B']]);
                                // continue; // Lewat data pada baris ini (masuk ke looping selanjutnya / baris
                                // key gabungan (tgl + username)
                                $key = date('Y-m-d', strtotime($row['A'])) . '_' . $row['B'];

                                // buat jika belum ada
                                if(!isset($tmp_group[$key])) {
                                    $tmp_group[$key] = array(
                                        'tgl' => date('Y-m-d', strtotime($row['A'])),
                                        'username' => $row['C'],
                                        'id_user' => $dt_user['id_user'],
                                        'asal_cabang' => $dt_user['cabang_id'],
                                        'asal_nm_cabang' => $dt_cabang['nama_cabang'],
                                        'tujuan_cabang' => $row['B'],
                                        'tujuan_nm_cabang' => $dt_cabang_tujuan['nama_cabang'],
                                        'ket'         => $row['F'],
                                        'dt_array'    => array()
                                    );
                                }

                                // masukkan detail barang ke dalam dt_array
                                $tmp_group[$key]['dt_array'][] = array(
                                    'id_user_pemilik' => $dt_user_pemilik['id_user'],
                                    'id_barang'   => $row['D'],
                                    'nama_barang' => $dt_barang['nama_barang'],
                                    'jumlah'      => intval($row['E']),
                                );  
                            }
                        }

                    } else if($id_stts == 4) {
                        if ($numrow > 1) { // Mulai dari baris kedua
                            if ($row['A'] == null && $row['B'] == null && $row['C'] == null && $row['D'] == null) {
                                // echo 'tidak';
                            } else {
                                $dt_user_pemilik = $this->admin->get('user', ['username' => $row['B']]);
                                $dt_barang = $this->admin->get('barang', ['id_barang' => $row['C']]);
                                // continue; // Lewat data pada baris ini (masuk ke looping selanjutnya / baris
                                // key gabungan (tgl + username)
                                $key = date('Y-m-d', strtotime($row['A'])) . '_' . $row['B'];

                                // buat jika belum ada
                                if(!isset($tmp_group[$key])) {
                                    $tmp_group[$key] = array(
                                        'tgl' => date('Y-m-d', strtotime($row['A'])),
                                        'username' => $row['B'],
                                        'id_user' => $dt_user['id_user'],
                                        'cabang_id' => $dt_user['cabang_id'],
                                        'nama_cabang' => $dt_cabang['nama_cabang'],
                                        'ket'         => $row['E'],
                                        'dt_array'    => array()
                                    );
                                }

                                // masukkan detail barang ke dalam dt_array
                                $tmp_group[$key]['dt_array'][] = array(
                                    'id_user_pemilik' => $dt_user_pemilik['id_user'],
                                    'id_barang'   => $row['C'],
                                    'nama_barang' => $dt_barang['nama_barang'],
                                    'jumlah'      => intval($row['D']),
                                );  
                            }
                        }
                    }

                    $numrow++; // Tambah 1 setiap kali looping
                }
                
                $data_import = array_values($tmp_group);

                unlink( $destination_path); // Hapus file tersebut

                // mendapatkan data sheet
                $dt_impor = [
                    "tgl" => $now,
                    "id_cabang" => $dt_user['cabang_id'],
                    "file" => $nama_file_baru,
                    "stts" => $id_stts,
                    'dt_impor' => $data_import,
                ];

                $res_dt_impor = base64_encode(json_encode($dt_impor));

                // halaman direview
                set_pesan("Mohon cek ulang data, sebelum disimpan!.");
                redirect('impor/review_impor/'.$res_dt_impor);
            } else {
                set_pesan("ekstensi file harus format xlsx");
                redirect('impor/add/'.$id_stts);
            }
        }
    }

    public function review_impor($dt_result)
    {
        $data['dt_res'] = json_decode(base64_decode($dt_result));
        $stts = $data['dt_res']->stts;

        $this->form_validation->set_rules('tgl_save', 'Tanggal', 'required');
        if ($this->form_validation->run() == false) {

            $data['errors'] = validation_errors();

            $data['title'] = "Review data Impor ". get_stts_impor($stts);
            $data['now'] = date('Y-m-d');
            $data['user_pemilik'] = $this->admin->getUserByRole('user');

            if($stts == 1) {
                // barang masuk
                $this->template->load('templates/dashboard', 'impor/review', $data);
            } else if($stts == 2 || $stts == 3 || $stts == 4) {

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

        } else {

            $dt_impor = array(
                "tgl" => $data['dt_res']->tgl,
                "file" => $data['dt_res']->file,
                "stts" => $data['dt_res']->stts,
                "id_cabang" => $data['dt_res']->id_cabang,
            );

            $id_import = $this->admin->process_impor($dt_impor);

            if($stts == 1) {
                // menyimpan data transaksi barang masuk
                $this->barang->insertBarangMasukImport($id_import, $data['dt_res']->dt_impor);
            } else if($stts == 2) {

                // menyusun data
                $cabang_id = $this->input->post('cabang_id[]', true);
                $id_user = $this->input->post('user_id[]', true);
                $tgl = $this->input->post('tgl[]', true);
                $ket = $this->input->post('ket[]', true);


                $id_detail_bm = $this->input->post('id_detail_bm[]', true);
                $user_id_pemilik = $this->input->post('user_id_pemilik[]', true);
                $id_barang = $this->input->post('id_barang[]', true);
                $jumlah = $this->input->post('jumlah[]', true);

                $tmp_group = array();
                $i = 0;
                foreach($id_detail_bm as $row_det) {
                    
                    $key = date('Y-m-d', strtotime($tgl[$i])) . '_' . $user_id_pemilik[$i];

                    // buat jika belum ada
                    if(!isset($tmp_group[$key])) {
                        $tmp_group[$key] = array(
                            'tgl' => date('Y-m-d', strtotime($tgl[$i])),
                            'id_user' => $id_user[$i],
                            'cabang_id' => $cabang_id[$i],
                            'ket'         => $ket[$i],
                            'dt_array'    => array(),
                        );
                    }

                    // masukkan detail barang ke dalam dt_array
                    $tmp_group[$key]['dt_array'][] = array(
                        'id_detail'   => $row_det,
                        'id_user_pemilik' => $user_id_pemilik[$i],
                        'id_barang'   => $id_barang[$i],
                        'jumlah'      => intval($jumlah[$i]),
                    );  

                    $i++;
                }

                $data_impor = array_values($tmp_group);

                // menyimpan data transaksi barang keluar
                $this->barang->insertBarangKeluarImport($id_import, $data_impor);
            } else if($stts == 3) {
                // menyimpan data transaksi barang transfer barang
                $asal_cabang = $this->input->post('asal_cabang[]', true);
                $tujuan_cabang = $this->input->post('tujuan_cabang[]', true);
                $id_user = $this->input->post('user_id[]', true);
                $tgl = $this->input->post('tgl[]', true);
                $ket = $this->input->post('ket[]', true);


                $id_detail_bm = $this->input->post('id_detail_bm[]', true);
                $user_id_pemilik = $this->input->post('user_id_pemilik[]', true);
                $id_barang = $this->input->post('id_barang[]', true);
                $jumlah = $this->input->post('jumlah[]', true);

                $tmp_group = array();
                $i = 0;
                foreach($id_detail_bm as $row_det) {
                    
                    $key = date('Y-m-d', strtotime($tgl[$i])) . '_' . $tujuan_cabang[$i];

                    // buat jika belum ada
                    if(!isset($tmp_group[$key])) {
                        $tmp_group[$key] = array(
                            'tgl' => date('Y-m-d', strtotime($tgl[$i])),
                            'id_user' => $id_user[$i],
                            'asal_cabang' => $asal_cabang[$i],
                            'tujuan_cabang' => $tujuan_cabang[$i],
                            'ket'         => $ket[$i],
                            'dt_array'    => array(),
                        );
                    }

                    // masukkan detail barang ke dalam dt_array
                    $tmp_group[$key]['dt_array'][] = array(
                        'id_detail'   => $row_det,
                        'id_user_pemilik' => $user_id_pemilik[$i],
                        'id_barang'   => $id_barang[$i],
                        'jumlah'      => intval($jumlah[$i]),
                    );  

                    $i++;
                }

                $data_impor = array_values($tmp_group);

                // menyimpan data transaksi barang keluar
                $id_import = $this->transfer->insertTransferImpor($id_import, $data_impor);
            } else if($stts == 4) {
                // menyimpan data transaksi stock opname

                $cabang_id = $this->input->post('cabang_id[]', true);
                $id_user = $this->input->post('user_id[]', true);
                $tgl = $this->input->post('tgl[]', true);
                $ket = $this->input->post('ket[]', true);


                $id_detail_bm = $this->input->post('id_detail_bm[]', true);
                $user_id_pemilik = $this->input->post('user_id_pemilik[]', true);
                $id_barang = $this->input->post('id_barang[]', true);
                $jumlah = $this->input->post('jumlah[]', true);

                $tmp_group = array();
                $i = 0;
                foreach($id_detail_bm as $row_det) {
                    
                    $key = date('Y-m-d', strtotime($tgl[$i])) . '_' . $user_id_pemilik[$i];

                    // buat jika belum ada
                    if(!isset($tmp_group[$key])) {
                        $tmp_group[$key] = array(
                            'tgl' => date('Y-m-d', strtotime($tgl[$i])),
                            'id_user' => $id_user[$i],
                            'cabang_id' => $cabang_id[$i],
                            'ket'         => $ket[$i],
                            'dt_array'    => array(),
                        );
                    }

                    // masukkan detail barang ke dalam dt_array
                    $tmp_group[$key]['dt_array'][] = array(
                        'id_detail'   => $row_det,
                        'id_user_pemilik' => $user_id_pemilik[$i],
                        'id_barang'   => $id_barang[$i],
                        'jumlah'      => intval($jumlah[$i]),
                    );  

                    $i++;
                }

                $data_impor = array_values($tmp_group);


                $id_import = $this->barang->insertStockOpNameImpor($id_import, $data_impor);
            } 

            if ($id_import) {
                set_pesan('data berhasil disimpan');
                redirect('impor/laporan/'.$stts);
            } else {
                set_pesan('data gagal disimpan', false);
                redirect('impor/add/'.$stts);
            }
        }
    }

    public function delete($getId)
    {
        $id = encode_php_tags($getId);


        $dt_impor = $this->admin->get('impor', ['id_impor' => $id]);
        $stts = $dt_impor['stts'];
        if($stts == 1) {
            // mendapatkan data impor by id
            $dt_bm_by_impor = $this->admin->get('barang_masuk',[], ['id_impor' => $id]);
            foreach($dt_bm_by_impor as $row) {
                $this->barang->delete('barang_masuk', 'id_barang_masuk', $row['id_barang_masuk']);
            }
        } else if($stts == 2) {
            // barang keluar
            $dt_bk_by_impor = $this->admin->get('barang_keluar',[], ['id_impor' => $id]);
            foreach($dt_bk_by_impor as $row) {
                $this->barang->delete('barang_keluar', 'id_barang_keluar', $row['id_barang_keluar']);
            }
        } else if($stts == 3) {
            // transfer barang
            $dt_tf_by_impor = $this->admin->get('transfer_barang',[], ['id_impor' => $id]);
            foreach($dt_tf_by_impor as $row) {
                $this->barang->delete('transfer_barang', 'id_transfer', $row['id_transfer']);
            }
        } else if($stts == 4) {
            // transfer barang
            $dt_tf_by_impor = $this->admin->get('stock_op_name',[], ['id_impor' => $id]);
            foreach($dt_tf_by_impor as $row) {
                $this->barang->delete('stock_op_name', 'id_stock_op_name', $row['id_stock_op_name']);
            }
        }

        if($dt_impor) {
            if ($this->admin->delete('impor', 'id_impor', $id)) {
                set_pesan('data berhasil dihapus.');
            } else {
                set_pesan('data gagal dihapus.', false);
            }
        } else {
            set_pesan('Jenis sudah digunakan!', false);
        }
        redirect('impor/laporan/'.$stts);
    }

    public function excel_template($stts)
    {
        $this->load->helper('download');

        if($stts == 1) {
            $file = FCPATH . 'assets/file/file_template/import_data_barang_masuk.xlsx';
        } else if($stts == 2) {
            $file = FCPATH . 'assets/file/file_template/import_data_barang_keluar.xlsx';
        } else if($stts == 3) {
            $file = FCPATH . 'assets/file/file_template/import_data_barang_transfer.xlsx';
        } else if($stts == 4) {
            $file = FCPATH . 'assets/file/file_template/import_data_barang_stock_opname.xlsx';
        } 

        if (file_exists($file)) {
            force_download($file, NULL); // langsung download
        } else {
            show_404();
        }
    }
}
