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

class Poin_bulanan extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('sales_activity/report/realisasi_poin/Poin_bulanan_m', 'model');
    }

    public function view_data()
    {
        $this->load->view('sales_activity/report/realisasi_poin/poin_bulanan/table');
    }

    public function list_data()
    {
        $periode     = $this->input->get('periode');
        $id_group    = $this->input->get('id_group');
        $id_karyawan = $this->input->get('id_karyawan');

        $p_realisasi = $this->model->get_poin_realisasi($periode, $id_group, $id_karyawan);
        $p_target    = $this->model->get_poin_target($periode, $id_group, $id_karyawan);

        $list = $this->model->get_datatables($periode, $id_group, $id_karyawan);
        $data = array();
        $no = $_GET['start'];
        foreach ($list as $field) {
            $no++;
            $row   = array();
            $row[] = $no;
            $row[] = $field->nama_karyawan . "<br><b>" . $field->nik . "</b>";

            $total_target    = 0;
            $total_realisasi = 0;
            for ($i = 1; $i <= 12; $i++) {
                $key_poin = ($periode) . "-" . (sprintf("%02d", $i)) . ($field->id_karyawan);

                $res_target    = array_search($key_poin, array_column($p_target, 'key_poin'));
                $res_target    = ($res_target !== false) ? $p_target[$res_target] : null;

                $poin_target   = !empty($res_target['target_poin']) ? $res_target['target_poin'] : '0';
                $row[]         = $poin_target;
                $total_target += $poin_target;

                $res_realisasi    = array_search($key_poin, array_column($p_realisasi, 'key_poin'));
                $res_realisasi    = ($res_realisasi !== false) ? $p_realisasi[$res_realisasi] : null;
                $poin_realisasi   = !empty($res_realisasi['total_poin']) ? $res_realisasi['total_poin'] : '0';
                $row[]            = $poin_realisasi;
                $total_realisasi += $poin_realisasi;
            }

            $row[] = '<B>' . $total_target . '</B>';
            $row[] = '<B>' . $total_realisasi . '</B>';

            $data[] = $row;
        }

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

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

        echo json_encode($output);
    }

    public function view_data_diagram()
    {
        $this->load->view('sales_activity/report/realisasi_poin/poin_bulanan/diagram');
    }

    public function list_data_diagram(){
        $periode     = $this->input->get('periode');
        $id_group    = $this->input->get('id_group');
        $id_karyawan = $this->input->get('id_karyawan');

        $array_bulan_short = $this->lang->line('array_bulan');
        $months            = str_replace(["[", "]", "'"], "", $array_bulan_short);
        $months_array      = explode(", ", $months);

        $realisasi_m   = $this->model->get_poin_realisasi($periode, $id_group, $id_karyawan);
        $realisasi_arr = $this->_change_array_key_value($realisasi_m, 'realisasi');
        $target_m      = $this->model->get_poin_target($periode, $id_group, $id_karyawan);
        $target_arr    = $this->_change_array_key_value($target_m, 'target');

        $i = 1;
        foreach($months_array AS $bulan){
            $data['bulan'][] = $bulan;
            $key_periode     = $periode. '-'. (sprintf("%02d", $i));

            $target_poin           = $target_arr[$id_karyawan][$key_periode]['total'];
            $data["target_poin"][] = !empty($target_poin) ? $target_poin : 0;

            $realisasi           = $realisasi_arr[$id_karyawan][$key_periode]['total'];
            $data["realisasi"][] = !empty($realisasi) ? $realisasi : 0;

            $i++;
        }

        // Skala Maksimal
        $maxNominal = [
            max($data['target_poin']),
            max($data['realisasi']),
        ];
        $skala_maximal = max($maxNominal) * 110/100;
        $data['max']   = ceil($skala_maximal / 100) * 100;

        echo json_encode($data);
    }

    public function download()
    {
        $periode     = $this->input->get('periode');
        $id_group    = $this->input->get('id_group');
        $nm_group    = $this->input->get('nm_group');
        $id_karyawan = $this->input->get('id_karyawan');
        $nm_karyawan = $this->input->get('nm_karyawan');

        $title       = "Sales Monitoring - Laporan Poin Bulanan ".$nm_group." ".$nm_karyawan;

        $data['filename']    = "Sales Monitoring - Laporan Poin Bulanan Tahun ".$periode." ".$nm_group." ".$nm_karyawan;
        $data['periode']     = $periode;
        $data['p_realisasi'] = $this->model->get_poin_realisasi($periode, $id_group, $id_karyawan);
        $data['p_target']    = $this->model->get_poin_target($periode, $id_group, $id_karyawan);
        $data['list']        = $this->model->get_datatables($periode, $id_group, $id_karyawan);

        $output  = true;
        $sb_view = $this->load->view('sales_activity/report/realisasi_poin/poin_bulanan/download', $data, $output);

        $column = 3 + (13 * 2);
        // START FORMAT COLUMN
        $format_columns = [
            'A'  => ['width' => 5, 'align' => 'center', 'valign' => 'middle'],
            'B'  => ['width' => 20, 'align' => 'center', 'valign' => 'middle', 'format' => 'text'],
            'C'  => ['width' => 30, 'align' => 'left', 'valign' => 'middle'],
        ];
        for ($i = 3; $i < $column; $i++) {
            $columnName = $this->getColumnName($i);
            $format_columns[$columnName] = ['width' => 12, 'align' => 'center', 'valign' => 'middle'];
        }
        // END FORMAT COLUMN

        $param = [
            'download'    => true,
            'cLength'     => ($column - 1),
            'file_name'   => strtoupper($title),
            'paper_size'  => 'LEGAL',
            'font-size'   => 11,
            'page_margin' => ['top' => 0, 'right' => 0.75, 'left' => 0.75, 'botom' => 0],
            'orientation' => 'landscape',
            'header'      => [
                '1' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
                '2' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
                '3' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
            ],
            'freezecolumn' => ['D6'],
            'thead'        => ['4', '5'],
            'tbody'        => [
                'start'  => '4',
                'height' => 15,
                'wrap'   => ['B', 'C'],
                'column' => $format_columns,
            ],
            'align_column_unit' => [
                ['align' => 'center', 'column' => ['A4:C4']]
            ]
        ];

        $this->load->library('PHPExcel/Excel');

        if ($output) {
            $this->excel->generateExcel($sb_view, $param);
        }
        exit;
    }

    private function getColumnName($index)
    {
        $letters = '';
        while ($index >= 0) {
            $letters = chr($index % 26 + 65) . $letters;
            $index = intdiv($index, 26) - 1;
        }
        return $letters;
    }

    private function _change_array_key_value($array=[], $jenis=""){
        if($jenis == 'target'){
            $poin_name = 'target_poin';
            $tgl_name  = 'DATE_FORMAT(tgl_trx, "%Y-%m")';
        }else{
            $poin_name = 'total_poin';
            $tgl_name  = 'DATE_FORMAT(tgl_activity, "%Y-%m")';
        }

        $data = array();
        foreach ($array as $value) {
            $id_karyawan = $value['id_karyawan'];
            $key_periode = $value[$tgl_name];
            $poin        = $value[$poin_name];

            $data[$id_karyawan][$key_periode]['total']  = $poin;
            $data['all'][$key_periode]['total']        += $poin;
        }

        return $data;
    }

    public function dropdown_group()
    {
        $periode = $this->input->get("periode");
        $search  = $this->input->get("q");
        return $this->model->dropdown_group($periode, $search);
    }

    public function dropdown_karyawan()
    {
        $periode  = $this->input->get("periode");
        $id_group = $this->input->get("id_group");
        $search   = $this->input->get("q");
        return $this->model->dropdown_karyawan($periode, $id_group, $search);
    }
}
