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

class Master_lembur_karyawan_import extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('payroll/master_lembur/Master_lembur_karyawan_import_m', 'model');
        $this->load->library(array('PHPExcel/Excel', 'PHPExcel/PHPExcel', 'Uploadfile'));
    }

    public function index()
    {
        $data['judul']   = 'Master Lembur';
        $data['aktif']   = 'master_lembur';
        $data['menu']    = $this->load->view('main_menu', $data, true);
        $data['content'] = $this->load->view('payroll/master_lembur/karyawan/import/index', $data, true);
        $this->load->view('main_template', $data, false);
    }

    public function template_import()
    {
        $this->load->view('payroll/master_lembur/karyawan/import/modal');
    }

    public function list_data()
    {
        $master_lembur = $this->model->getMasterLembur();
        $data_gagal_import = $this->model->getDataGagalImport();
        $list = $this->model->get_datatables();
        $data = array();
        $no   = $_GET['start'];
        foreach ($list as $field) {
            $no++;
            $row = array();

            $row[] = $no;
            $row[] = ($field->nama ?: '-') . '<br><span class="text-light" style="font-size: 12px">' . $field->nik . '</span>';
            $row[] = $field->cabang . '<br>' . $field->departemen;
            $row[] = $master_lembur[$field->lembur_hari_kerja]['kode'] ?: $field->lembur_hari_kerja;
            $row[] = $master_lembur[$field->lembur_libur_off]['kode'] ?: $field->lembur_libur_off;
            $row[] = $master_lembur[$field->lembur_libur_nasional]['kode'] ?: $field->lembur_libur_nasional;
            $row[] = $master_lembur[$field->lembur_libur_khusus]['kode'] ?: $field->lembur_libur_khusus;

            $data[] = $row;
        }

        $output = array(
            "draw"              => $_GET['draw'],
            "recordsTotal"      => $this->model->count_all(),
            "recordsFiltered"   => $this->model->count_filtered(),
            "data"              => $data,
            "data_gagal_import" => $data_gagal_import,
        );

        $output = __response($this->MY_response, $output);

        echo json_encode($output);
    }

    function download_template_import($id_cabang = 'all', $id_departemen = 'all')
    {
        if ($id_cabang != 'all') {
            $nama_cabang = $this->db->select("nama")
                ->from("master_cabang")
                ->where("id_cabang", $id_cabang)
                ->where("id_company", $this->id_company)
                ->get()
                ->row("nama");
            $filename = "Template Import Master Lembur Karyawan Cabang " . $nama_cabang;
        } else {
            $filename = "Template Import Master Lembur Karyawan Semua Cabang ";
        }

        if ($id_departemen != 'all') {
            $nama_departemen = $this->db->select("nama")
                ->from("master_departemen")
                ->where("id_departemen", $id_departemen)
                ->where("id_company", $this->id_company)
                ->get()
                ->row("nama");
            $filename .= " Departemen " . $nama_departemen;
        } else {
            $filename .= " Semua Departemen";
        }

        $data['filename']      = $filename;
        $data['master_lembur'] = $this->model->getMasterLembur();
        $data['data']          = $this->model->getDataKaryawan($id_cabang, $id_departemen);
        $sb_view               = $this->load->view('payroll/master_lembur/karyawan/import/template_import', $data, true);
        // print_r($sb_view);
        // exit;
        $column_param = array(
            'A'    => ['width' => 5, 'align' => 'center', 'valign' => 'middle', 'lock' => true],
            'B'    => ['align' => 'center', 'valign' => 'middle', 'format' => 'text', 'lock' => true],
            'C'    => ['width' => 40, 'lock' => true],
            'D'    => ['width' => 20, 'lock' => true],
            'E'    => ['width' => 20, 'lock' => true],
            'F'    => ['align' => 'center', 'width' => 20],
            'G'    => ['align' => 'center', 'width' => 20],
            'H'    => ['align' => 'center', 'width' => 20],
            'I'    => ['align' => 'center', 'width' => 20],
        );

        $param = [
            'download'   => true,
            'cLength'    => 8,
            'file_name'  => strtoupper($filename),
            'paper_size' => 'A4',
            'font-size'  => 12,
            // 'pagebreak'		=> true,
            'page_margin' => ['top' => 0, 'right' => 0.75, 'left' => 0.75, 'botom' => 0],
            'orientation' => 'potrait',
            'header'      => [
                '1' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
                '2' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
            ],
            // 'freezecolumn'	   => ['D7'],
            'thead' => ['3', '4'],
            'tbody' => [
                'start'  => '3',
                'height' => 15,
                'wrap'   => ['B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
                'column' => $column_param,
            ],
        ];
        $this->excel->generateExcel($sb_view, $param);
    }

    function import_data_excel()
    {
        if (!empty($_FILES['file']['name'])) {
            $tahunbulan                   = date('Ym');
            $fileUpload['fname']          = 'file';
            $fileUpload['location']       = 'template_data_lembur/' . $tahunbulan;
            $fileUpload['allowed']        = 'xls|xlsx';
            $fileUpload['compress_image'] = false;

            $upload = $this->uploadfile->doUpload($fileUpload);
            if ($upload["success"] == true) {
                $dir_file = $this->config->item('base_upload') . $upload['url'];
            } else {
                $message = ["message" => $upload["message"]];
                return __response_save(false, $message);
            }
        } else {
            $message = ["message" => '<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Data gagal import</font>'];
            return __response_save(false, ["message" => $message]);
        }

        try {
            $inputFileType = PHPExcel_IOFactory::identify($dir_file);
            $objReader     = PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel   = $objReader->load($dir_file);
        } catch (Exception $e) {
            $message = ["message" => 'Error loading file "' . pathinfo($dir_file, PATHINFO_BASENAME) . '": ' . $e->getMessage()];
            return __response_save(false, ["message" => $message]);
        }

        $dataKaryawan             = $this->model->getDataKaryawan();
        $masterLembur             = $this->model->getMasterLembur(true);
        $highestRow               = $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
        $dataInsert               = array();
        $idLembur                 = $this->model->getNextId('payroll_lembur_m_temp', 'id_lembur_m_temp', $this->id_company, 4);
        for ($row = 5; $row < ($highestRow - 3); $row++) {
            $nik                   = $objPHPExcel->setActiveSheetIndex(0)->getCell("B" . $row)->getValue();
            $lembur_hari_kerja     = $objPHPExcel->setActiveSheetIndex(0)->getCell("F" . $row)->getValue();
            $lembur_libur_off      = $objPHPExcel->setActiveSheetIndex(0)->getCell("G" . $row)->getValue();
            $lembur_libur_nasional = $objPHPExcel->setActiveSheetIndex(0)->getCell("H" . $row)->getValue();
            $lembur_libur_khusus   = $objPHPExcel->setActiveSheetIndex(0)->getCell("I" . $row)->getValue();
            # untuk membedakan data yg tidak ditemukan
            if ($dataKaryawan[$nik]) {
                $id_karyawan = $dataKaryawan[$nik]['id_karyawan'];
            } else {
                $id_karyawan = '#' . $nik;
            }
            $dataInsert[] = [
                'id_lembur_m_temp'      => $idLembur,
                'id_karyawan'           => $id_karyawan,
                'lembur_hari_kerja'     => $lembur_hari_kerja ? ($masterLembur[$lembur_hari_kerja]['id_lembur_p'] ?: '#' . $lembur_hari_kerja) : '',
                'lembur_libur_off'      => $lembur_libur_off ? ($masterLembur[$lembur_libur_off]['id_lembur_p'] ?: '#' . $lembur_libur_off) : '',
                'lembur_libur_nasional' => $lembur_libur_nasional ? ($masterLembur[$lembur_libur_nasional]['id_lembur_p'] ?: '#' . $lembur_libur_nasional) : '',
                'lembur_libur_khusus'   => $lembur_libur_khusus ? ($masterLembur[$lembur_libur_khusus]['id_lembur_p'] ?: '#' . $lembur_libur_khusus) : '',
                'id_company'            => $this->id_company,
                'user_input'            => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                'tgl_input'             => date('Y-m-d H:i:s'),
            ];
            $last_id  = substr($idLembur, -4);
            $next_id  = (int)$last_id + 1;
            $idLembur = substr($idLembur, 0, -4) . sprintf("%04d", $next_id);
        }

        $this->db->trans_begin();
        $this->db->delete("payroll_lembur_m_temp", ["id_company" => $this->id_company]);
        $this->db->insert_batch('payroll_lembur_m_temp', $dataInsert);

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $message = ["message" => '<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>Data gagal diimport</font>'];
            return __response_save(false, $message);
        } else {
            unlink($dir_file);
            $this->db->trans_commit();
            $message = ["message" => '<font color="#009900"><i class="fa fa-check-square">&nbsp;</i>Data berhasil diimport</font>'];
            return __response_save(true, $message);
        }
    }

    public function publish_all_temp()
    {
        $list       = $this->model->get_datatables();
        $dataDelete = [];
        $dataInsert = [];
        $idLembur   = $this->model->getNextId('payroll_lembur_m', 'id_lembur_m', $this->id_company, 4);
        foreach ($list as $field) {
            $dataToCheck = [
                $field->nik,
                $field->lembur_hari_kerja,
                $field->lembur_libur_off,
                $field->lembur_libur_nasional,
                $field->lembur_libur_khusus
            ];
            $check  = preg_quote('#', '~');
            $result = preg_grep('~' . $check . '~', $dataToCheck);

            if (count($result) == 0) {
                $dataDelete[] = $field->id_karyawan;
                $dataInsert[] = [
                    'id_lembur_m'           => $idLembur,
                    'id_karyawan'           => $field->id_karyawan,
                    'lembur_hari_kerja'     => $field->lembur_hari_kerja,
                    'lembur_libur_off'      => $field->lembur_libur_off,
                    'lembur_libur_nasional' => $field->lembur_libur_nasional,
                    'lembur_libur_khusus'   => $field->lembur_libur_khusus,
                    'id_company'            => $this->id_company,
                    'user_input'            => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                    'tgl_input'             => date('Y-m-d H:i:s'),
                ];
                $last_id  = substr($idLembur, -4);
                $next_id  = (int)$last_id + 1;
                $idLembur = substr($idLembur, 0, -4) . sprintf('%04d', $next_id);
            }
        }

        $this->db->trans_begin();
        // hapus data sebelumnya
        $this->db->where_in('id_karyawan', $dataDelete);
        $this->db->where('id_company', $this->id_company);
        $this->db->delete('payroll_lembur_m');

        // hapus data temporary
        $this->db->where_in('id_karyawan', $dataDelete);
        $this->db->where('id_company', $this->id_company);
        $this->db->delete('payroll_lembur_m_temp');

        // insert data baru
        $this->db->insert_batch('payroll_lembur_m', $dataInsert);
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return __response_save(false);
        } else {
            $this->db->trans_commit();
            return __response_save(true);
        }
    }

    function delete_all_temp()
    {
        $query = $this->db->delete("payroll_lembur_m_temp", ["id_company" => $this->id_company]);
        if ($query === FALSE) {
            return __response_delete(false);
        } else {
            return __response_delete(true);
        }
    }
}
