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

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

    public function index()
    {
        $data['judul']       = 'Report Sales Monitoring';
        $data['periode']     = date('m-Y');
        $data['tahapan_trx'] = $this->model->get_tahapan_trx(date('m-Y'));
        $this->load->view('sales_activity/report/data_sales/home', $data);
    }

    public function view_data($bulan = "", $nama_group = "all")
    {
        $data['tahapan_trx'] = $this->model->get_tahapan_trx($bulan);
        $data['bulan']       = $bulan;
        $data['nama_group']  = $nama_group;
        $this->load->view('sales_activity/report/data_sales/view_data', $data);
    }

    public function view_diagram($bulan = "", $nama_group = "all")
    {
        $periode             = implode('-', array_reverse(explode('-', ('01-' . $bulan))));
        $data['tahapan_trx'] = $this->model->get_tahapan_trx($bulan);
        $data['bulan']       = $bulan;
        $data['nama_group']  = $nama_group;
        $data['periode']     = ($this->code_lang == 'id') ? indo_date(strtotime($periode), 'F Y') : date('F Y ', strtotime($periode));
        $this->load->view('sales_activity/report/data_sales/view_diagram', $data);
    }

    public function combineData($jumlah, $nominal)
    {
        $datasets = [];
        $count = count($jumlah);

        for ($i = 0; $i < $count; $i++) {
            $datasets[] = $jumlah[$i];
            $datasets[] = $nominal[$i];
        }

        return $datasets;
    }

    public function list_data_diagram($bulan = "", $nama_group = "all")
    {
        $list        = $this->model->get_datatables($bulan, "", $nama_group);
        $tahapan_arr = $this->model->get_tahapan_trx($bulan);
        $data        = [];
        $no_tahapan  = 0;
        foreach ($list as $value) {
            $data['nama'][] = $value->nama_lengkap;
            foreach ($tahapan_arr as $tahapan) {
                $var_nominal = "nominal___" . $tahapan->id_tahapan_m;
                $var_jumlah  = "jumlah_po___" . $tahapan->id_tahapan_m;

                $data['nominal'][$no_tahapan][] = $value->$var_nominal;
                $data['jumlah'][$no_tahapan][]  = $value->$var_jumlah;
            }
            $no_tahapan++;
        }
        $data['datasets_jumlah']  = $this->transposeArray($data['jumlah']);
        $data['datasets_nominal'] = $this->transposeArray($data['nominal']);
        $data['maxJumlah']        = (int)max(array_map('max', $data['datasets_jumlah']));
        $data['maxNominal']       = (int)max(array_map('max', $data['datasets_nominal']));
        // $data['datasets']   = $this->combineData($transposedArrayJumlah, $transposedArrayNominal);

        echo json_encode($data);
    }

    function transposeArray($array)
    {
        $transposedArray = [];
        foreach ($array as $rowKey => $row) {
            foreach ($row as $columnKey => $value) {
                $transposedArray[$columnKey][$rowKey] = $value;
            }
        }
        return $transposedArray;
    }

    public function list_data($bulan = "", $nama_group = "all")
    {
        $tahapan_arr = $this->model->get_tahapan_trx($bulan);
        $list        = $this->model->get_datatables($bulan, "", $nama_group);
        $total       = $this->model->get_total_jumlah_dan_nominal($bulan, "", $nama_group);

        $data  = array();
        $no    = $_GET['start'];
        foreach ($list as $field) {
            $no++;
            $row   = array();
            $row[] = $no;
            $row[] = $field->nama_lengkap . "<br><b>" . $field->nik . "</b>";

            if (COUNT($tahapan_arr) > 0) {
                foreach ($tahapan_arr as $tahapan) {
                    $var_nominal_layanan = "nominal___" . $tahapan->id_tahapan_m;
                    $var_jumlah_po = "jumlah_po___" . $tahapan->id_tahapan_m;

                    $row[] = $field->$var_jumlah_po;
                    $row[] = number_format($field->$var_nominal_layanan, 0, ",", ".");
                }
            } else {
                $row[] = "-";
                $row[] = "-";
            }

            $data[] = $row;
        }

        // START FOOTER TOTAL
        if(!empty($data)){
            $row_total   = array();
            $row_total[] = "<strong>TOTAL</strong>";
            $row_total[] = "";
    
            if (COUNT($tahapan_arr) > 0) {
                foreach ($tahapan_arr as $tahapan) {
                    $row_total[] = "<B>" . $total[$tahapan->id_tahapan_m]['jumlah'] . "</B>";
                    $row_total[] = "<B>" . number_format($total[$tahapan->id_tahapan_m]['nominal'], 0, ",", ".") . "</B>";
                }
            } else {
                $row_total[] = "-";
                $row_total[] = "-";
            }
    
            $row_total[] = "colspan";
            $data[] = $row_total;
        }
        // END FOOTER TOTAL

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

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

    public function download($periode = "", $nama_group = "all")
    {
        $bulan    = $this->fungsi->get_bulan($periode);
        $tahun    = $this->fungsi->get_tahun($periode);
        $filename = "Laporan Pipeline " . $bulan . " " . $tahun;

        $data['periode']     = $bulan . " " . $tahun;
        $data['tahapan_trx'] = $this->model->get_tahapan_trx($periode);
        $data['list']        = $this->model->get_datatables($periode, "",$nama_group);

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

        // START FORMAT COLUMN
        $format_columns = [
            'A'  => ['width' => 5, 'align' => 'center', 'valign' => 'middle'],
            'B'  => ['width' => 20, 'align' => 'left', 'valign' => 'middle', 'format' => 'text'],
            'C'  => ['width' => 30, 'align' => 'left', 'valign' => 'middle'],
        ];

        if (COUNT($data['tahapan_trx']) > 0) {
            $c_length = 2 + (COUNT($data['tahapan_trx']) * 2);

            for ($i = 4; $i <= ($c_length + 1); $i++) {
                $alphabet = $this->_numberToLetters($i);
                $alphabet = strtoupper($alphabet);

                if ($i % 2 == 0) {
                    $width  = 10;
                    $align  = 'center';
                    $rupiah = false;
                } else {
                    $width  = 15;
                    $align  = 'right';
                    $rupiah = true;
                }

                $format_columns[$alphabet] = [
                    'width'  => $width,
                    'align'  => $align,
                    'valign' => 'middle',
                    'rupiah' => $rupiah
                ];
            }
        } else {
            $c_length = 4;

            $format_columns = [
                'A'  => ['width' => 5, 'align' => 'center', 'valign' => 'middle'],
                'D'  => ['width' => 20, 'align' => 'center', 'valign' => 'middle',],
                'E'  => ['width' => 30, 'align' => 'right', 'valign' => 'middle',],
            ];
        }
        // END FORMAT COLUMN

        // Bold Header & Footer Table
        $bold_footer = COUNT($data['list']) + 6;
        $thead = ['4', '5', strval($bold_footer)];

        $param = [
            'download'    => true,
            'cLength'     => $c_length,
            'file_name'   => strtoupper($filename),
            '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'        => $thead,
            'tbody'        => [
                'start'  => '4',
                'height' => 15,
                'wrap'   => ['B', 'C', 'D', 'E'],
                'column' => $format_columns,
            ],
        ];

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

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

    private function _numberToLetters($number)
    {
        $letters = '';
        while ($number > 0) {
            $mod = ($number - 1) % 26;
            $letters = chr(97 + $mod) . $letters;
            $number = floor(($number - 1) / 26);
        }
        return $letters;
    }

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