<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Template extends MY_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('pkwt/master/template_m');
        $this->load->helper(['generateid', 'pkwt']);

        $this->sub_folder = $this->id_company.'/pkwt/template';
        $this->folder     = $this->config->item('base_upload').$this->sub_folder;
    }

    public function index()
    {
        $data['aktif']   = 'pkwt_template';
        $data['judul']   = 'Template PKWT';
        $data['content'] = $this->load->view('pkwt/master/template/home', $data, true);
        $data['menu']    = $this->load->view('main_menu', $data, true);
        $this->load->view('main_template', $data);
    }

    public function list_data()
    {
        $list = $this->template_m->get_datatables();
        $data = array();
        $no = $_GET['start'];
        foreach ($list as $field) {
            $no++;
            $row   = array();
            $row[] = $no;
            $row[] = $field->nama;

            $btn_preview = '<a href="'.route('pkwt.master.template.preview', ['id' => md5($field->id_template)]).'" target="_blank" title="PREVIEW"> <i class="fa fa-file (alias) "> </i></a>';
            $btn_edit    = '<a href="'.route('pkwt.master.template.form.edit', ['id' => md5($field->id_template)]).'" class="text-warning" title="EDIT"> <i class="btn_edit fa fa-edit (alias) "> </i></a>';
            $btn_hapus   = '<a href="#" class="text-danger" title="' . $this->lang->line('hapus') . '"><i id="' . md5($field->id_template) . '" class="btn_delete fa fa-trash"></i></a>';
            $row[]       = $btn_preview.'&nbsp;&nbsp;'.$btn_edit . '&nbsp;&nbsp;' . $btn_hapus;

            $data[] = $row;
        }

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

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

        echo json_encode($output);
    }

    public function form($id = '')
    {
        $data['aktif'] = 'pkwt_template';
        $data['judul'] = 'Form Template PKWT';
        if($id == '') {
            $data['data']->template = $this->load->view('pkwt/master/template/contoh_template', $data, true);
        } else {
            $data['data']                  = $this->template_m->getDataById($id);
            $data['data']->lokasi_template = $data['data']->template;
            $data['data']->template        = read_template_file($data['data']->template);
        }
        $data['content'] = $this->load->view('pkwt/master/template/form', $data, true);
        $data['menu']    = $this->load->view('main_menu', $data, true);
        $this->load->view('main_template', $data);
    }

    public function form_parameter($id) {
        $data['id']   = $id;
        $data['data'] = $this->template_m->getDataById($id);
        $data['row']  = $this->form_parameter_row(read_template_file($data['data']->template), $data['data']->parameter);
        $this->load->view('pkwt/master/template/form_parameter', $data);
    }

    private function form_parameter_row($template, $parameter) {
        preg_match_all('/({{)\w+(}})/', $template, $match);
        $results = array_unique($match[0]);
        $parameter = json_decode($parameter, 1);
        if(count($results) > 0) {
            $temp = "";
            foreach($results as $value) {
                $value = str_replace(["{{", "}}"], ["", ""], $value);

                if(in_array($value, ['ttd_karyawan', 'ttd_direktur'])) {
                    continue;
                }

                $teks     = "checked";
                $nominal  = "";
                if(is_array($parameter)) {
                    if(array_key_exists($value, $parameter)) {
                        if($parameter[$value] == 'nominal') {
                            $teks    = "";
                            $nominal = "checked";
                        }
                    }
                }
                $temp    .= "<div class='form-group row'>
                            <label for='staticEmail' class='col-sm-6 col-form-label'>$value</label>
                            <div class='col-sm-6'>
                                <div class='form-check form-check-inline'>
                                    <input class='form-check-input' type='radio' name='$value' value='teks' $teks>
                                    <label class='form-check-label' for='inlineRadio1'>teks</label>
                                </div>
                                <div class='form-check form-check-inline'>
                                    <input class='form-check-input' type='radio' name='$value' value='nominal' $nominal>
                                    <label class='form-check-label' for='inlineRadio2'>nominal</label>
                                </div>
                            </div>
                        </div>";
            }
            return $temp;
        }
    }

    public function save() 
    {
        $id_template = htmlentities($this->input->post('id_template'));
        $user        = $this->nik_karyawan." - ".$this->nm_karyawan;
        $data        = [
            'nama'       => htmlentities($this->input->post('nama')),
            'template'   => $this->save_template_file(),
            'id_company' => $this->id_company,
        ];

        if($id_template == '') {
            $data['id_template'] = generate_id('id_template', $this->id_company);
            $data['user_input']  = $user;
            $insert              = $this->db->insert('pkwt_template_m', $data);
            __response_save($insert, ['new_params' => ['id_template' => md5($data['id_template']), 'lokasi_template' => $data['template']]]);
        } else {
            $data['user_update'] = $user;
            $update              = $this->db->update('pkwt_template_m', $data, ['md5(id_template)' => $id_template]);
            __response_update($update, ['new_params' => ['id_template' => $id_template]]);
        }
    }

    private function save_template_file() {
        $cek_folder_exists = $this->cek_folder_exists();
        $lokasi_template = $this->input->post('lokasi_template');
	if($lokasi_template == '') {
		$filename = gen_uuid_v4().'.php';
	} else {
		$temp = explode("/", $lokasi_template);
		$filename = $temp[count($temp)-1];
	}
        if($cek_folder_exists) {
            if(file_put_contents($this->folder.'/'.$filename, urldecode($this->input->post('template')))) {
                return $this->sub_folder.'/'.$filename;
            } else {
                __response_save(false, ['message' => '<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>tidak dapat menyimpan template</font>']);
                exit;
            }
        }
    }

    private function cek_folder_exists() {
        if(file_exists($this->folder)) {
            return true;
        } else {
            if(mkdir($this->folder, 0755, true)) {
                return true;
            } else {
                __response_save(false, ['message' => '<font color="#eb3a28"><i class="fa fa-exclamation-triangle">&nbsp;</i>tidak dapat menyimpan template</font>']);
                exit();
            }
        }
    }

    public function delete() 
    {
        $id_template = htmlentities($this->input->post('id_template'));

        $template = $this->template_m->getDataById($id_template)->template;
        if($this->template_m->cekTemplateDigunakan($template) == 0 && $this->template_m->cekTemplateDigunakan($template, 'import') == 0) {
            unlink($this->config->item('base_upload').$template);
        }
        $this->db->where('md5(id_template)', $id_template);
        $delete = $this->db->delete('pkwt_template_m');
        __response_delete($delete);
    }

    public function save_parameter() {
        $post = $this->input->post();
        $id   = $post['id_template'];
        unset($post['id_template']);

        $update = $this->db->update('pkwt_template_m', ['parameter' => json_encode($post)], ['md5(id_template)' => $id]);
        __response_save($update);
    }

    public function preview($id) {
        $this->load->library('mpdf');

        $data = $this->template_m->getDataById($id);

        if($data == NULL) {
            echo "template belum disimpan";
            exit;
        }

		$param['title']          = str_replace(' ', '_', strtolower($data->nama));
		$param['page_number']    = true;
		$param['show_watermark'] = false;
		$param['custom_font']    = false;
		$param['download']       = false;
		$param['header']         = true;
		$this->mpdf->generate(read_template_file($data->template), $param['title'], 'A4', 'P', $param);
    }
}
