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

class Data_komponen_import extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('payroll/data_komponen_kehadiran/Data_komponen_import_m', 'model');
        $this->load->library(array('PHPExcel/Excel', 'PHPExcel/PHPExcel', 'Uploadfile'));
    }

    public function index()
    {
        $data['judul']   = 'Import Data Komponen Kehadiran';
        $data['aktif']   = 'data_komponen_kehadiran';
        $data['menu']    = $this->load->view('main_menu', $data, true);
        $data['content'] = $this->load->view('payroll/data_komponen_kehadiran/import/home', $data, true);
        $this->load->view('main_template', $data, false);
    }

    public function form_template_import()
    {
        $this->load->view('payroll/data_komponen_kehadiran/import/form_template_import');
    }

    public function view_data()
    {
        $data['master'] = json_decode($this->model->master_komponen(), true);
        $this->load->view('payroll/data_komponen_kehadiran/import/list_data', $data);
    }

    public function list_data()
    {
        $get_pend = json_decode($this->model->tambah_pendapatan(), true);
        $list     = $this->model->get_datatables();
        $data     = array();
        $no       = $_GET['start'];
        foreach ($list as $field) {
            $no++;
            $row   = array();
            $row[] = $no;
            $row[] = ($field->id_karyawan) ? $field->id_karyawan : '-';
            $row[] = $field->nm_karyawan . "<br><b>" . $field->nik . "</b>";
            $row[] = $field->cabang;
            $row[] = $field->departemen;
            $row[] = $field->jabatan;
            $row[] = number_format($field->gapok, 0, ',', '.');

            if (count($get_pend[$field->id_karyawan]) > 0) {
                foreach ($get_pend[$field->id_karyawan] as $komponen) {
                    $row[] = number_format($komponen['nominal_tunjangan'], 0, ',', '.');
                }
            }

            $data[] = $row;
        }

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

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

        echo json_encode($output);
    }

    function download_template($id_cabang = "-", $id_departemen = "-")
    {
        if ($id_cabang != "-") {
            $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 Data Komponen Kehadiran Cabang" . $nama_cabang;
        } else {
            $filename = "Template Import Data Komponen Kehadiran Semua Cabang";
        }

        if ($id_departemen != "-") {
            $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['nama']       = $filename;
        $data['data']       = $this->model->getDataKaryawan($id_cabang, $id_departemen);
        $data['master']     = json_decode($this->model->master_komponen(), true);
        $data['pendapatan'] = json_decode($this->model->tambah_pendapatan(false), true);
        $data['is_excel']   = true;
        $output             = true;
        $sb_view            = $this->load->view('payroll/data_komponen_kehadiran/import/download', $data, $output);

        $komponen     = $data['master'];
        $total_column = count($komponen['kehadiran']) + 6;

        if ($total_column > 6) {
            if (count($komponen['kehadiran']) > 0) {
                $komponen_kehadiran = $komponen['kehadiran'];
            }
        } else {
            // pendapatan = 0
            return;
        }

        // column dinamis dari header table
        $column_param = array(
            'A' => ['width' => 5, 'align' => 'center', 'valign' => 'middle'],
            'B' => ['width' => 10, 'align' => 'center', 'valign' => 'middle', 'format' => 'text', 'lock' => true],
            'C' => ['width' => 40, 'lock' => true],
            'D' => ['width' => 20, 'lock' => true],
            'E' => ['width' => 20, 'lock' => true],
            'F' => ['width' => 20, 'lock' => true],
            'G' => ['width' => 20, 'align' => 'right', 'valign' => 'middle', 'rupiah' => true, 'lock' => true],
        );
        $col          = 'H';
        for ($i = 0; $i < ($total_column - 6); $i++) {
            // jika dari persentase gapok maka di lock
            if ($komponen_kehadiran[$i]['flag_persentase_gapok'] == '1') {
                $column_param[$col] = ['align' => 'right', 'valign' => 'middle', 'format' => 'text', 'rupiah' => true, 'lock' => true];
            } else {
                $column_param[$col] = ['align' => 'right', 'valign' => 'middle', 'format' => 'text', 'rupiah' => true];
            }
            $col++;
        }

        $param = [
            'download'    => true,
            'cLength'     => $total_column,
            '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' => 13,
                // 'runFunction'	=> ['highlightlibur' => 'P'],
                'wrap'   => ['B', 'C', 'D', 'E', 'F'],
                'column' => $column_param,
            ],
        ];
        $this->excel->generateExcel($sb_view, $param);
    }

    public function import_data_excel()
    {
        if (!empty($_FILES['file']['name'])) {
            $tahunbulan                   = date('Ym');
            $fileUpload['fname']          = 'file';
            $fileUpload['location']       = 'template_data_komponen/' . $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]);
        }

        $highestColumm = $objPHPExcel->setActiveSheetIndex(0)->getHighestColumn();
        $highestRow    = $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
        $data_insert   = array();

        $highestColumm++;
        for ($row = 5; $row < ($highestRow - 3); $row++) {
            $dataset = array();
            for ($column = 'B'; $column != $highestColumm; $column++) {
                $head = $objPHPExcel->setActiveSheetIndex(0)->getCell($column . '4')->getValue();
                if (empty($head)) {
                    $head = $objPHPExcel->setActiveSheetIndex(0)->getCell($column . '3')->getValue();
                }
                // menghapus tanda kurung dan konten di dalamnya
                $head = preg_replace('/\s*\([^)]*\)\s*$/', '', $head);
                // if (strpos($head, '(') !== false) {
                //     $head = (substr($head, -8, 1) != '(') ? substr($head, 0, -8) : substr($head, 0, -9);
                // }
                $cell = $objPHPExcel->setActiveSheetIndex(0)->getCell($column . $row)->getValue();

                // key dataset = head dan column karena untuk membedakan jika ada nama komponen yg sama
                $dataset[$head . '(' . $column . ')'] = $cell;
            }
            $data_insert[] = $dataset;
        }
        $results         = array_filter($data_insert);
        $master_komponen = $this->model->master_komponen();
        $komponen        = json_decode($master_komponen, true);
        $jml_header      = 6;
        $jml_pend        = count($komponen['kehadiran']);

        $data_pendapatan = array();
        for ($i_data = 0; $i_data < count($results); $i_data++) {
            if ($jml_pend > 0) {
                for ($i_pend = $jml_header; $i_pend < ($jml_header + $jml_pend); $i_pend++) {
                    $nm_pendapatan     = array_keys($results[$i_data])[$i_pend];
                    $data_pendapatan[] = [
                        'nik'               => $results[$i_data][array_keys($results[$i_data])[0]],
                        'nm_karyawan'       => $results[$i_data][array_keys($results[$i_data])[1]],
                        'cabang'            => $results[$i_data][array_keys($results[$i_data])[2]],
                        'departemen'        => $results[$i_data][array_keys($results[$i_data])[3]],
                        'jabatan'           => $results[$i_data][array_keys($results[$i_data])[4]],
                        'gapok'             => $results[$i_data][array_keys($results[$i_data])[5]],
                        'nominal_tunjangan' => $results[$i_data][$nm_pendapatan],
                        'nm_tunjangan'      => preg_replace('/\s*\([^)]*\)\s*$/', '', $nm_pendapatan),
                        'user_input'        => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                        'id_company'        => $this->id_company
                    ];
                }
            }
        }

        // $this->db->trans_strict(FALSE);
        $this->db->trans_start();

        if (count($data_pendapatan) > 0) {
            // hapus data payroll_tunj_kehadiran_temp
            $this->db->where("id_company", $this->id_company);
            $this->db->delete("payroll_tunj_kehadiran_temp");

            // insert data payroll_tunj_kehadiran_temp
            if ($this->db->trans_status()) {
                $this->db->insert_batch('payroll_tunj_kehadiran_temp', $data_pendapatan);
            }
        }

        $this->db->trans_complete();

        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 {
            $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()
    {
        $get_pend               = json_decode($this->model->tambah_pendapatan(), true);
        $list                   = $this->model->get_datatables();
        $data_pendapatan        = array();
        $data_pendapatan_delete = array();

        foreach ($list as $field) {
            if (count($get_pend[$field->id_karyawan]) > 0) {
                foreach ($get_pend[$field->id_karyawan] as $key) {
                    if (!empty($field->id_karyawan)) {
                        $data_pendapatan[]        = [
                            'concat(id_karyawan,id_item,id_company)' => $key['id_karyawan'] . $key['id_item'] . $this->id_company,
                            'nominal_tunjangan'                      => $key['nominal_tunjangan'],
                        ];
                        $data_pendapatan_delete[] = $key['nik'] . $key['nm_tunjangan'] . $this->id_company;
                    }
                }
            }
        }

        $this->db->trans_start();

        if (count($data_pendapatan_delete) > 0) {
            $this->db->where_in('concat(nik,nm_tunjangan,id_company)', $data_pendapatan_delete);
            $this->db->delete('payroll_tunj_kehadiran_temp');
        }
        if (count($data_pendapatan) > 0) {
            $this->db->update_batch('payroll_tunj_kehadiran_m', $data_pendapatan, 'concat(id_karyawan,id_item,id_company)');
        }

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return __response_save(false);
        } else {
            $this->db->trans_commit();
            return __response_save(true);
        }
    }

    public function delete_all_temp()
    {
        $this->db->trans_start();

        $this->db->where("id_company", $this->id_company);
        $this->db->delete("payroll_tunj_kehadiran_temp");

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return __response_delete(false);
        } else {
            $this->db->trans_commit();
            return __response_delete(true);
        }
    }
}
