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

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

    public function view_data()
    {
        $periode_mulai           = date('Y-m-d', strtotime($this->input->get('periode_mulai')));
        $periode_selesai         = date('Y-m-d', strtotime($this->input->get('periode_selesai')));
        $data['periode_mulai']   = $periode_mulai;
        $data['periode_selesai'] = $periode_selesai;
        $data['id_group']        = $this->input->get('id_group');
        $data['id_karyawan']     = $this->input->get('id_karyawan');
        $data['header']          = $this->buat_tabel_header($periode_mulai, $periode_selesai);
        $this->load->view('sales_activity/report/realisasi_poin/poin_harian/table', $data);
    }

    function buat_tabel_header($periode_mulai="0000-00-00", $periode_selesai="0000-00-00")
    {
        $akhir   = date_create($periode_selesai);
        $awal    = date_create($periode_mulai);
        $selisih = date_diff($akhir, $awal)->format("%a");
        $hasil   = array();
        $d       = "d M";

        $akhir    = date_create(date('Y-m-d', strtotime('+1 days ' . $periode_selesai)));
        $interval = DateInterval::createFromDateString('1 day');
        $period   = new DatePeriod($awal, $interval, $akhir);
        foreach ($period as $dt) {
            $hasil[] = indo_date($dt->format("Y-m-d"), $d);
        }
        return $hasil;
    }

    public function list_data()
    {

        $periode_mulai   = date('Y-m-d', strtotime($this->input->get('periode_mulai')));
        $periode_selesai = date('Y-m-d', strtotime($this->input->get('periode_selesai')));
        $id_group        = $this->input->get('id_group');
        $id_karyawan     = $this->input->get('id_karyawan');

        $awal     = date_create($periode_mulai);
        $akhir    = date_create(date('Y-m-d', strtotime('+1 days ' . $periode_selesai)));
        $interval = DateInterval::createFromDateString('1 day');
        $period   = new DatePeriod($awal, $interval, $akhir);

        $get_absensi   = $this->model->get_absensi($periode_mulai, $periode_selesai, $id_karyawan);
        $get_target    = $this->model->get_poin_target($periode_mulai, $periode_selesai, $id_group, $id_karyawan);
        $get_realisasi = $this->model->get_poin_realisasi($periode_mulai, $periode_selesai, $id_group, $id_karyawan);

        $list = $this->model->get_datatables($periode_mulai, $periode_selesai, $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>";

            if ($awal <= $akhir) {
                $total_target    = 0;
                $total_realisasi = 0;

                foreach ($period as $dt) {
                    $jenis_absen = $get_absensi[$field->id_karyawan][$dt->format('Y-m-d')]['jenis_absen'];

                    if (empty($jenis_absen)) {
                        $target_poin   = $get_target[$field->id_karyawan][$dt->format('Y-m-d')]['target_poin'];
                        $row[]         = !empty($target_poin) ? $target_poin : 0;
                        $total_target += $target_poin;

                        $row[]            = 0;
                        $total_realisasi += 0;
                    } else if (in_array($jenis_absen, ['reguler', 'shift', 'alpha'])) {
                        $target_poin   = $get_target[$field->id_karyawan][$dt->format('Y-m-d')]['target_poin'];
                        $row[]         = !empty($target_poin) ? $target_poin : 0;
                        $total_target += $target_poin;

                        $total_poin       = $get_realisasi[$field->id_karyawan][$dt->format('Y-m-d')]['total_poin'];
                        $row[]            = !empty($total_poin) ? $total_poin : 0;
                        $total_realisasi += $total_poin;
                    } else {
                        $kode_absen = $get_absensi[$field->id_karyawan][$dt->format('Y-m-d')]['kode_absen'];

                        $row[] = $kode_absen . "<span style='display:none'>" . $jenis_absen . "</span>";
                        $row[] = $kode_absen . "<span style='display:none'>" . $jenis_absen . "</span>";

                        $total_target    += 0;
                        $total_realisasi += 0;
                    }
                }

                $row[] = '<B>' . $total_target . '</B>';
                $row[] = '<B>' . $total_realisasi . '</B>';
            } else {
                $row[] = "-";
                $row[] = "-";
                $row[] = "-";
                $row[] = "-";
            }

            $data[] = $row;
        }

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

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

        echo json_encode($output);
    }

    public function download()
    {
        $periode_mulai   = date('Y-m-d', strtotime($this->input->get('periode_mulai')));
        $periode_selesai = date('Y-m-d', strtotime($this->input->get('periode_selesai')));
        $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 Harian ".$nm_group." ".$nm_karyawan;
        $data['title'] = "Sales Monitoring - Laporan Poin Harian ".$nm_group." ".$nm_karyawan;

        $data['awal']   = date_create($periode_mulai);
        $data['akhir']  = date_create(date('Y-m-d', strtotime('+1 days ' . $periode_selesai)));
        $interval       = DateInterval::createFromDateString('1 day');
        $data['period'] = new DatePeriod($data['awal'], $interval, $data['akhir']);

        $data['get_absensi']   = $this->model->get_absensi($periode_mulai, $periode_selesai, $id_karyawan);
        $data['get_target']    = $this->model->get_poin_target($periode_mulai, $periode_selesai, $id_group, $id_karyawan);
        $data['get_realisasi'] = $this->model->get_poin_realisasi($periode_mulai, $periode_selesai, $id_group, $id_karyawan);

        $data['periode_mulai']   = $periode_mulai;
        $data['periode_selesai'] = $periode_selesai;

        $filename = "Sales Monitoring - Laporan Poin Harian ".$data['periode_mulai']." s.d ".$data['periode_selesai']." ".$nm_group." ".$nm_karyawan;
        $data['filename']        = $filename;
        $data['list']            = $this->model->get_datatables($periode_mulai, $periode_selesai, $id_group, $id_karyawan);
        $data['header']          = $this->buat_tabel_header($periode_mulai, $periode_selesai);

        // Start warna excel libur
        $data_libur  = array();
        $baris_libur = 6;
        foreach ($data['list'] as $list) {
            $kolom_libur = 3;

            $karyawan = $data['get_absensi'][$list->id_karyawan];
            foreach ($karyawan as $tanggal) {
                for ($x = 1; $x <= 2; $x++) {
                    if (in_array($tanggal['jenis_absen'], ['izin', 'libur', 'cuti', 'sakit'])) {
                        $columnName = $this->getColumnName($kolom_libur);
                        $data_libur[$columnName . $baris_libur] = 'FF7588';
                    }

                    $kolom_libur++;
                }
            }

            $baris_libur++;
        }
        // End warna excel libur

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

        // 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'],
        ];

        $column = 3 + ((count($data['header']) + 1) * 2);
        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($filename),
            'paper_size'  => 'LEGAL',
            'font-size'   => 11,
            'page_margin' => ['top' => 0, 'right' => 0.75, 'left' => 0.75, 'botom' => 0],
            'orientation' => 'landscape',
            'freezecolumn' => ['D6'],
            'header'      => [
                '1' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
                '2' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
                '3' => ['merge' => true, 'align' => 'center', 'weight' => 'bold'],
            ],
            'thead'        => ['4', '5'],
            'tbody'        => [
                'start'  => '4',
                'height' => 15,
                'wrap'   => ['B', 'C'],
                'column' => $format_columns,
            ],
            'align_column_unit' => [
                ['align' => 'center', 'column' => ['A4:C4']]
            ],
            'color_column_unit' => $data_libur,
        ];

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

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

    public function dropdown_group()
    {
        $periode_mulai   = date_format(date_create($this->input->get("periode_mulai")),"Y-m-d");
        $periode_selesai = date_format(date_create($this->input->get("periode_selesai")),"Y-m-d");
        $search          = $this->input->get("q");
        return $this->model->dropdown_group($periode_mulai, $periode_selesai, $search);
    }

    public function dropdown_karyawan($tanggal_mulai = "", $tanggal_selesai = "")
    {
        $periode_mulai   = date_format(date_create($this->input->get("periode_mulai")),"Y-m-d");
        $periode_selesai = date_format(date_create($this->input->get("periode_selesai")),"Y-m-d");
        $id_group        = $this->input->get("id_group");
        $search          = $this->input->get("q");
        return $this->model->dropdown_karyawan($periode_mulai, $periode_selesai, $id_group, $search);
    }

    public function view_data_diagram()
    {
        $data['periode_mulai']   = date('Y-m-d', strtotime($this->input->get("periode_mulai")));
        $data['periode_selesai'] = date('Y-m-d', strtotime($this->input->get("periode_selesai")));
        $data['id_group']        = $this->input->get("id_group");
        $data['id_karyawan']     = $this->input->get("id_karyawan");
        $this->load->view('sales_activity/report/realisasi_poin/poin_harian/diagram', $data);
    }

    public function list_data_diagram()
    {
        $periode_mulai   = date('Y-m-d', strtotime($this->input->get("periode_mulai")));
        $periode_selesai = date('Y-m-d', strtotime($this->input->get("periode_selesai")));
        $id_group        = $this->input->get("id_group");
        $id_karyawan     = $this->input->get("id_karyawan");

        $get_absensi   = $this->model->get_absensi($periode_mulai, $periode_selesai, $id_karyawan);
        $get_target    = $this->model->get_poin_target($periode_mulai, $periode_selesai, $id_group, $id_karyawan);
        $get_realisasi = $this->model->get_poin_realisasi($periode_mulai, $periode_selesai, $id_group, $id_karyawan);

        // Initial Foreach Tanggal
        $awal     = date_create($periode_mulai);
        $akhir    = date_create(date('Y-m-d', strtotime('+1 days ' . $periode_selesai)));
        $interval = DateInterval::createFromDateString('1 day');
        $period   = new DatePeriod($awal, $interval, $akhir);

        // Array Data
        $data     = array();
        foreach ($period as $dt) {
            $tanggal = $dt->format('Y-m-d');
            if ($id_karyawan == 'all') {
                $hari_kerja    = false;
                $all_karyawan  = array_values(array_column($get_absensi, $tanggal));
                foreach ($all_karyawan as $value) {
                    if (in_array($value['jenis_absen'], ['reguler', 'shift', 'alpha'])) {
                        $hari_kerja = true;
                    }
                }

                if ($hari_kerja) {
                    $data["tanggal"][] = indo_date($tanggal, "d M");

                    $target_poin           = $get_target[$id_karyawan][$tanggal]['target_poin'];
                    $data["target_poin"][] = !empty($target_poin) ? $target_poin : 0;

                    $realisasi           = $get_realisasi[$id_karyawan][$tanggal]['total_poin'];
                    $data["realisasi"][] = !empty($realisasi) ? $realisasi : 0;
                }
            } else {
                $jenis_absen = $get_absensi[$id_karyawan][$dt->format('Y-m-d')]['jenis_absen'];
                if (in_array($jenis_absen, ['reguler', 'shift', 'alpha'])) {
                    $data["tanggal"][] = indo_date($tanggal, "d M");

                    $target_poin           = $get_target[$id_karyawan][$tanggal]['target_poin'];
                    $data["target_poin"][] = !empty($target_poin) ? $target_poin : 0;

                    $realisasi           = $get_realisasi[$id_karyawan][$tanggal]['total_poin'];
                    $data["realisasi"][] = !empty($realisasi) ? $realisasi : 0;
                }
            }
        }

        // Skala Maksimal
        $maxNominal = [
            max($data['target_poin']),
            max($data['realisasi']),
        ];

        $skala_maximal = max($maxNominal) * 120 / 100;
        $data['max']   = ceil($skala_maximal / 10) * 10;

        echo json_encode($data);
    }

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