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

class Tahapan_m extends CI_Model
{   
    var $table = 'sales_tahapan_m';

    public function list_data(){
        $query = $this->db->select('tahapan.id_tahapan_m,
                                    tahapan.jenis,
                                    tahapan.nama,
                                    tahapan.warna,
                                    tahapan.warna_text,
                                    tahapan.no_urut,
                                    tahapan.id_company,
                                    IF(main.id_tahapan_m IS NULL, "YA", "TIDAK") AS status_hapus,
                                ')
                        ->from($this->table. ' AS tahapan')
                        ->join('sales_pipeline_main AS main', 
                                'main.id_tahapan_m = tahapan.id_tahapan_m
                                    AND bulan = "'.date("m").'"
                                    AND tahun = "'.date("Y").'" ',
                                'LEFT'
                            )
                        ->where('tahapan.id_company', $this->id_company)
                        ->group_by('tahapan.id_tahapan_m')
                        ->order_by('tahapan.no_urut ASC')
                        ->get()
                        ->result();
        
        $data          = array();
        $data_tahapan  = array();
        $data_activity = array();
        foreach($query AS $value){
            if($value->jenis == 'activity'){
                $data = array( 'id_tahapan_m' => $value->id_tahapan_m,
                                'jenis'        => $value->jenis,
                                'nama'         => $value->nama,
                                'warna'        => $value->warna,
                                'warna_text'   => $value->warna_text,
                                'no_urut'      => $value->no_urut,
                                'status_hapus' => $value->status_hapus,
                                'id_company'   => $value->id_company);
    
                $data_activity[] = $data;
            }else{
                $data = array( 'id_tahapan_m' => $value->id_tahapan_m,
                                'jenis'      => $value->jenis,
                                'nama'       => $value->nama,
                                'warna'      => $value->warna,
                                'warna_text' => $value->warna_text,
                                'no_urut'    => $value->no_urut,
                                'id_company' => $value->id_company);
    
                $data_tahapan[$value->jenis] = $data;
            }
        }
        
        $data_tahapan['activity'] = $data_activity;
        return $data_tahapan;
    }

    public function save($action="", $id="", $data=[]){
        if(!empty($id)){
            // PROSES UPDATE
            $user_update    = array('tgl_update'     => date("Y-m-d H:i:s"),
                                    'user_update'	=> $this->nik_karyawan. " - ". $this->nm_karyawan);
            
            $this->db->trans_start();
            $this->db->where("md5(id_tahapan_m)",$id);
            $this->db->where('id_company', $this->id_company);
            $this->db->update($this->table, array_merge($data,$user_update));

            $this->db->where('tahun', date('Y'));
            $this->db->where('bulan', date('m'));
            $this->db->where("md5(id_tahapan_m)",$id);
            $this->db->where('id_company', $this->id_company);
            $this->db->update('sales_tahapan_trx', array_merge($data,$user_update));

            $this->db->trans_complete();
            if ($this->db->trans_status() === TRUE) {
                $this->db->trans_commit();
                return  __response_update(true);
            } else {
                $this->db->trans_rollback();
                return  __response_update(false);
            }
        }else{
            // PROSES SAVE
            $id      = $this->fungsi->getNextId($this->table, 'id_tahapan_m', $this->id_company, 5);
            $no_urut = $this->get_no_urut();
            $no_urut = $no_urut + 1;

            $user_input = array('id_tahapan_m' => $id,
                                'no_urut'    => $no_urut,
                                'tgl_input'  => date("Y-m-d H:i:s"),
                                'user_input' => $this->nik_karyawan. " - ". $this->nm_karyawan);

            $trx = array('tahun' => date('Y'),
                        'bulan' => date('m'));

                                
            $this->db->trans_start();
            
            // insert data tahapan trx jika pertama insert pada pipeline main
            $task_exist = $this->check_task_exist();
            if (!$task_exist) {
                $this->db->query('
                    INSERT INTO
                        sales_tahapan_trx (tahun, bulan, id_tahapan_m, jenis, nama, warna, no_urut, id_company, user_input)
                    SELECT
                        "' . date('Y') . '", "' . date('m') . '", id_tahapan_m, jenis, nama, warna, no_urut, id_company, "' . $this->nik_karyawan . ' - ' . $this->nm_karyawan . '"
                    FROM
                        sales_tahapan_m
                    WHERE
                        id_company = "' . $this->id_company . '"
                ');
            }

            $this->db->insert($this->table, array_merge($data, $user_input));
            $this->db->insert('sales_tahapan_trx', array_merge($data, $user_input, $trx));

            $this->db->trans_complete();
            if ($this->db->trans_status() === TRUE) {
                $this->db->trans_commit();

                $new_params = array("new_params" => array(  'id' => $id,
                                                            'id_md5' => MD5($id)
                                                        ));

                return  __response_save(true, $new_params);
            } else {
                $this->db->trans_rollback();
                return  __response_save(false);
            }
        }
    }

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

        $this->db->where('id_company', $this->id_company);
        $this->db->update_batch($this->table, $data, 'concat(id_tahapan_m,id_company)');

        $this->db->where('tahun', date('Y'));
        $this->db->where('bulan', date('m'));
        $this->db->where('id_company', $this->id_company);
        $this->db->update_batch('sales_tahapan_trx', $data, 'concat(id_tahapan_m,id_company)');

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

    public function delete($id = null){
        $this->db->trans_start();

        $this->db->where('MD5(id_tahapan_m)', $id);
        $this->db->where('id_company', $this->id_company);
        $this->db->delete($this->table);

        $this->db->where('tahun', date('Y'));
        $this->db->where('bulan', date('m'));
        $this->db->where('MD5(id_tahapan_m)', $id);
        $this->db->where('id_company', $this->id_company);
        $this->db->delete('sales_tahapan_trx');

        $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);
        }
    }

    function get_no_urut(){
        return $this->db->select('MAX(no_urut) as no_urut')
                        ->from($this->table)
                        ->where('id_company', $this->id_company)
                        ->where('no_urut <', 997)
                        ->get()
                        ->row()
                        ->no_urut;
    }

    # START UP INSERT TAHAPAN
    function check_data_tahapan(){
        $cek_tahapan = $this->db->select('id_tahapan_m')
                        ->from($this->table)
                        ->where('id_company', $this->id_company)
                        ->get()
                        ->row()
                        ->id_tahapan_m;
        
        if(empty($cek_tahapan)){
            $data = array();

            # Incoming
            $data[] = array(
                'id_tahapan_m' => $this->id_company. date('Ym'). '00001',
                'jenis' => 'incoming',
                'nama' => 'Leads',
                'warna' => '#7B219F',
                'warna_text' => '#FFFFFF',
                'no_urut' => '1',
                'id_company' => $this->id_company,
                'tgl_input'  => date("Y-m-d H:i:s"),
                'user_input' => $this->nik_karyawan. " - ". $this->nm_karyawan
            );

            # Activity 1
            $data[] = array(
                'id_tahapan_m' => $this->id_company. date('Ym'). '00002',
                'jenis' => 'activity',
                'nama' => 'Prospect',
                'warna' => '#00A3D7',
                'warna_text' => '#FFFFFF',
                'no_urut' => '2',
                'id_company' => $this->id_company,
                'tgl_input'  => date("Y-m-d H:i:s"),
                'user_input' => $this->nik_karyawan. " - ". $this->nm_karyawan
            );

            # Activity 2
            $data[] = array(
                'id_tahapan_m' => $this->id_company. date('Ym'). '00003',
                'jenis' => 'activity',
                'nama' => 'Hot Prospect',
                'warna' => '#FF8647',
                'warna_text' => '#FFFFFF',
                'no_urut' => '3',
                'id_company' => $this->id_company,
                'tgl_input'  => date("Y-m-d H:i:s"),
                'user_input' => $this->nik_karyawan. " - ". $this->nm_karyawan
            );
            
            # Po
            $data[] = array(
                'id_tahapan_m' => $this->id_company. date('Ym'). '00004',
                'jenis' => 'wont',
                'nama' => 'PO',
                'warna' => '#96D35F',
                'warna_text' => '#FFFFFF',
                'no_urut' => '998',
                'id_company' => $this->id_company,
                'tgl_input'  => date("Y-m-d H:i:s"),
                'user_input' => $this->nik_karyawan. " - ". $this->nm_karyawan
            );

            # Failed
            $data[] = array(
                'id_tahapan_m' => $this->id_company. date('Ym'). '00005',
                'jenis' => 'lost',
                'nama' => 'Failed',
                'warna' => '#FF6251',
                'warna_text' => '#FFFFFF',
                'no_urut' => '999',
                'id_company' => $this->id_company,
                'tgl_input'  => date("Y-m-d H:i:s"),
                'user_input' => $this->nik_karyawan. " - ". $this->nm_karyawan
            );

            $this->db->trans_start();
            $this->db->insert_batch($this->table, $data);
            $this->db->trans_complete();
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
            } else {
                $this->db->trans_commit();
            }
        }
    }

    public function check_task_exist(): bool
    {   
        $task_exist = $this->db->select('trx.id_tahapan_m')
            ->from('sales_tahapan_trx trx')
            ->where('trx.tahun = "' . date('Y') . '"')
            ->where('trx.bulan = "' . date('m') . '"')
            ->where('trx.id_company', $this->id_company)
            ->limit(1)
            ->get()
            ->num_rows();

        if ($task_exist > 0) {
            return true;
        } else {
            return false;
        }
    }
}
