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

class Approval_activity extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('sales_activity/approval_activity/Approval_activity_m', 'model');
    }

    public function index()
    {
        $data['judul']           = 'Approval Activity';
        $data['periode_mulai']   = date('d-m-Y',  time());
        $data['periode_selesai'] = date('d-m-Y',  time());
        $this->load->view('sales_activity/approval_activity/index', $data);
    }

    public function list_data($mulai, $selesai, $status, $karyawan, $group)
    {
        // reformat date
        $mulai   = $mulai ? date('Y-m-d', strtotime($mulai)) : '';
        $selesai = $selesai ? date('Y-m-d', strtotime($selesai)) : '';
        $ttl_pengajuan = 0;
        $list = $this->model->get_datatables($mulai, $selesai, $status, $karyawan, $group);
        $data = array();
        $no   = $_GET['start'];
        foreach ($list as $field) {
            $no++;
            $row = array();
            if ($field->status === 'pengajuan') {
                if (($this->is_sales_skip_approval === false) && ($field->user_id === $this->id_karyawan)) {
                    $row[] = '<input type="checkbox" disabled>';
                } else {
                    $row[] = '<input type="checkbox">';
                }
            } else {
                $row[] = '<input type="checkbox" disabled>';
            }
            $row[] = $no;
            $row[] = date('d-m-Y H:i', strtotime($field->waktu));
            $row[] = ltrim(explode('-', $field->user)[1]) . '<p class="text-light" style="font-size: 11px">' . trim(explode('-', $field->user)[0]) . '</p>';
            if ($field->tabel === 'log') {
                if ($field->kategori === 'move') {
                    $aktivitas  = explode(',', $field->aktivitas_pindah_bulan);
                    $row[]      = '<i class="text-warning">' . $aktivitas[0] . '</i> ' . $aktivitas[1] . ' <i class="fa fa-long-arrow-right"></i> ' . $aktivitas[2];
                } else {
                    if ($field->aktivitas == 'Move') {
                        $row[] = '<i class="text-warning">' . $field->aktivitas . '</i> ' . $field->tahapan_sebelum . ' <i class="fa fa-long-arrow-right"></i> ' . $field->tahapan_sekarang;
                    } else {
                        $row[] = '<i class="text-primary">' . $field->aktivitas . '</i> ' . $field->tahapan_sekarang;
                    }
                }
            } else {
                $row[] = $field->aktivitas;
            }
            $row[] = ($field->poin != '') ? number_format($field->poin, 0, ',', '.') : '-';
            $row[] = htmlspecialchars(($field->kategori === 'move') ? $field->keterangan : ($field->aktivitas_pindah_bulan ?: $field->keterangan));
            $row[] = $field->nama_perusahaan;

            if ($field->status === 'pengajuan') {
                if ($this->is_sales_admin === true || $this->level_user === '1') {
                    $ttl_pengajuan++;
                    if ($field->tabel == 'log') {
                        $row[] = '<button onclick="preview_verify(this)" type="button" data-in="' . $field->tabel . '" data-id="' . $field->id . '" class="btn btn-biru btn-verify">' . $this->lang->line('verifikasi') . '</button>';
                    } else {
                        $row[] = '<button onclick="preview_verify(this)" type="button" data-in="' . $field->tabel . '" data-id="' . $field->user_id . '_' . str_replace(":", "-", str_replace(" ", "_", $field->waktu)) . '" class="btn btn-biru btn-verify">' . $this->lang->line('verifikasi') . '</button>';
                    }
                } else {
                    if (($this->is_sales_skip_approval === false) && ($field->user_id === $this->id_karyawan)) {
                        $row[] = '<span class="badge badge-warning" data-status="-">' . $this->lang->line('pengajuan') . '</span>';
                    } else {
                        $ttl_pengajuan++;
                        if ($field->tabel == 'log') {
                            $row[] = '<button onclick="preview_verify(this)" type="button" data-in="' . $field->tabel . '" data-id="' . $field->id . '" class="btn btn-biru btn-verify">' . $this->lang->line('verifikasi') . '</button>';
                        } else {
                            $row[] = '<button onclick="preview_verify(this)" type="button" data-in="' . $field->tabel . '" data-id="' . $field->user_id . '_' . str_replace(":", "-", str_replace(" ", "_", $field->waktu)) . '" class="btn btn-biru btn-verify">' . $this->lang->line('verifikasi') . '</button>';
                        }
                    }
                }
            } else {
                if ($field->status == 'approve') {
                    $row[] = '<span class="badge badge-success" data-status="' . $field->status . '">' . $this->lang->line('disetujui') . '</span>';
                } else {
                    $row[] = '<span class="badge badge-danger" data-status="-">' . $this->lang->line('ditolak') . '</span>';
                }
            }

            $data[] = $row;
        }

        $output = array(
            "draw"            => $_GET['draw'],
            "recordsTotal"    => $this->model->count_all($mulai, $selesai, $status, $karyawan, $group),
            "recordsFiltered" => $this->model->count_filtered($mulai, $selesai, $status, $karyawan, $group),
            "data"            => $data,
            "ttl_pengajuan"   => $ttl_pengajuan,
        );

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

        echo json_encode($output);
    }

    # single approval
    public function verify_confirmation($tabel, $id)
    {
        $data['tabel']   = $tabel;
        $data['id']      = $id;
        $data['preview'] = $this->model->preview_verifikasi($tabel, $id);
        $this->load->view('sales_activity/approval_activity/verifikasi', $data);
    }

    public function verify_approve()
    {
        $tabel = $this->input->post('tabel');
        $id    = $this->input->post('id');

        // validation
        if (empty($tabel) || empty($id)) return __response_approve(false);
        if (!in_array($tabel, ['log', 'activity'])) return __response_approve(false);

        // classify data
        $get_preview = $this->model->preview_verifikasi($tabel, $id);
        if ($tabel == 'log') {
            $id_pipeline_main     = $get_preview->id_pipeline_main;
            $id_pipeline_main_log = $get_preview->id_pipeline_main_log;
            $action               = $get_preview->aktivitas;

            $get_pipeline = $this->model->get_detail_pipeline($id_pipeline_main);
            $get_tahapan  = $this->model->get_data_tahapan_trx($get_pipeline->tahun, $get_pipeline->bulan, $get_preview->id_tahapan_sekarang)[0];

            // jika pindah bulan
            if ($get_preview->kategori === 'move') {
                $sales_group          = $this->model->get_sales_group($get_pipeline->id_karyawan);
                $pipeline_trx         = $this->db->get_where('sales_pipeline_trx', ['id_company' => $this->id_company, 'id_pipeline_main' => $get_pipeline->id_pindah_bulan])->result();
                $next_id_pipeline_trx = $this->fungsi->getNextId('sales_pipeline_trx', 'id_pipeline_trx', $this->id_company, 5);
                $data_trx             = ['for'  => 'clone'];
                foreach ($pipeline_trx as $value) {
                    $data_trx['data'][] = [
                        'id_pipeline_trx'       => $next_id_pipeline_trx,
                        'id_pipeline_main'      => $id_pipeline_main,
                        'id_karyawan'           => $value->id_karyawan,
                        'nik'                   => $value->nik,
                        'nama_karyawan'         => $value->nama_karyawan,
                        'tahun'                 => $get_pipeline->tahun,
                        'bulan'                 => $get_pipeline->bulan,
                        'id_tahapan'            => $value->id_tahapan,
                        'jenis_tahapan'         => $value->jenis_tahapan,
                        'nama_tahapan'          => $value->nama_tahapan,
                        'warna_tahapan'         => $value->warna_tahapan,
                        'warna_text_tahapan'    => $value->warna_text_tahapan,
                        'no_urut_tahapan'       => $value->no_urut_tahapan,
                        'nominal_layanan'       => $value->nominal_layanan,
                        'jumlah_layanan'        => $value->jumlah_layanan,
                        'id_pelanggan'          => $value->id_pelanggan,
                        'nama_perusahaan'       => $value->nama_perusahaan,
                        'provinsi'              => $value->provinsi,
                        'kota'                  => $value->kota,
                        'kecamatan'             => $value->kecamatan,
                        'kelurahan'             => $value->kelurahan,
                        'alamat'                => $value->alamat,
                        'nama_jenis_perusahaan' => $value->nama_jenis_perusahaan,
                        'nama_lead_source'      => $value->nama_lead_source,
                        'title'                 => $value->title,
                        'id_group_m'            => $value->id_group_m ? $value->id_group_m : ($sales_group->id_group_m ?: ''),
                        'nama_group'            => $value->id_group_m ? $value->nama_group : ($sales_group ? $sales_group->kode . ' - ' . $sales_group->nama : ''),
                        'tgl_incoming'          => $value->tgl_incoming,
                        'id_company'            => $value->id_company,
                        'user_approve'          => $value->user_approve,
                        'tgl_approve'           => $value->tgl_approve,
                    ];

                    $last_id = substr($next_id_pipeline_trx, -5);
                    $next_id_pipeline_trx = $this->id_company . date('Ym') . sprintf("%05d", ($last_id + 1));
                }
            } else {
                if ($get_preview->aktivitas == 'New') {
                    $data_trx = [
                        'id_pipeline_trx'       => $this->fungsi->getNextId('sales_pipeline_trx', 'id_pipeline_trx', $this->id_company, 5),
                        'id_pipeline_main'      => $id_pipeline_main,
                        'id_karyawan'           => $get_preview->user_id,
                        'nik'                   => $get_pipeline->sales_nik,
                        'nama_karyawan'         => $get_pipeline->sales_nama,
                        'tahun'                 => $get_pipeline->tahun,
                        'bulan'                 => $get_pipeline->bulan,
                        'id_tahapan'            => $get_tahapan->id_tahapan_m,
                        'jenis_tahapan'         => $get_tahapan->jenis,
                        'nama_tahapan'          => $get_tahapan->nama,
                        'warna_tahapan'         => $get_tahapan->warna,
                        'warna_text_tahapan'    => $get_tahapan->warna_text,
                        'no_urut_tahapan'       => $get_tahapan->no_urut,
                        'nominal_layanan'       => $get_pipeline->nominal_layanan,
                        'jumlah_layanan'        => $get_pipeline->jumlah_layanan,
                        'id_pelanggan'          => $get_pipeline->id_pelanggan,
                        'nama_perusahaan'       => $get_pipeline->nama_perusahaan,
                        'provinsi'              => $get_pipeline->provinsi,
                        'kota'                  => $get_pipeline->kota,
                        'kecamatan'             => $get_pipeline->kecamatan ?: '',
                        'kelurahan'             => $get_pipeline->kelurahan ?: '',
                        'alamat'                => $get_pipeline->alamat,
                        'nama_jenis_perusahaan' => $get_pipeline->nama_jenis_perusahaan ?: '',
                        'nama_lead_source'      => $get_pipeline->nama_lead_source,
                        'title'                 => $get_pipeline->title ?: '',
                        'id_group_m'            => $get_pipeline->id_group ?: '',
                        'nama_group'            => $get_pipeline->id_group ? $get_pipeline->kode_group . ' - ' . $get_pipeline->nama_group : '',
                        'id_company'            => $this->id_company,
                        'user_approve'          => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                        'tgl_incoming'          => $get_pipeline->tgl_input,
                        'tgl_approve'           => date('Y-m-d H:i:s'),
                    ];
                } else {
                    $data_existing_trx = $this->model->get_data_existing_trx($get_preview->user_id, $get_pipeline->tahun, $get_pipeline->bulan, $id_pipeline_main, $get_tahapan->id_tahapan_m);
                    if (count($data_existing_trx) > 0) {
                        $data_trx = [
                            'for'  => 'update',
                            'data' => [
                                'jenis_tahapan'      => $get_tahapan->jenis,
                                'nama_tahapan'       => $get_tahapan->nama,
                                'warna_tahapan'      => $get_tahapan->warna,
                                'warna_text_tahapan' => $get_tahapan->warna_text,
                                'no_urut_tahapan'    => $get_tahapan->no_urut,
                                'nominal_layanan'    => $get_pipeline->nominal_layanan,
                                'jumlah_layanan'     => $get_pipeline->jumlah_layanan,
                                'user_approve'       => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                                'tgl_approve'        => date('Y-m-d H:i:s'),
                            ],
                            'where_update' => $get_tahapan->id_tahapan_m,
                            'where_delete' => $get_tahapan->no_urut,
                        ];
                    } else {
                        $data_trx = [
                            'for'  => 'insert',
                            'data' => [
                                'id_pipeline_trx'       => $this->fungsi->getNextId('sales_pipeline_trx', 'id_pipeline_trx', $this->id_company, 5),
                                'id_pipeline_main'      => $id_pipeline_main,
                                'id_karyawan'           => $get_preview->user_id,
                                'nik'                   => $get_pipeline->sales_nik,
                                'nama_karyawan'         => $get_pipeline->sales_nama,
                                'tahun'                 => $get_pipeline->tahun,
                                'bulan'                 => $get_pipeline->bulan,
                                'id_tahapan'            => $get_tahapan->id_tahapan_m,
                                'jenis_tahapan'         => $get_tahapan->jenis,
                                'nama_tahapan'          => $get_tahapan->nama,
                                'warna_tahapan'         => $get_tahapan->warna,
                                'warna_text_tahapan'    => $get_tahapan->warna_text,
                                'no_urut_tahapan'       => $get_tahapan->no_urut,
                                'nominal_layanan'       => $get_pipeline->nominal_layanan,
                                'jumlah_layanan'        => $get_pipeline->jumlah_layanan,
                                'id_pelanggan'          => $get_pipeline->id_pelanggan,
                                'nama_perusahaan'       => $get_pipeline->nama_perusahaan,
                                'provinsi'              => $get_pipeline->provinsi,
                                'kota'                  => $get_pipeline->kota,
                                'kecamatan'             => $get_pipeline->kecamatan ?: '',
                                'kelurahan'             => $get_pipeline->kelurahan ?: '',
                                'alamat'                => $get_pipeline->alamat,
                                'nama_jenis_perusahaan' => $get_pipeline->nama_jenis_perusahaan ?: '',
                                'nama_lead_source'      => $get_pipeline->nama_lead_source,
                                'title'                 => $get_pipeline->title ?: '',
                                'id_group_m'            => $get_pipeline->id_group ?: '',
                                'nama_group'            => $get_pipeline->id_group ? $get_pipeline->kode_group . ' - ' . $get_pipeline->nama_group : '',
                                'id_company'            => $this->id_company,
                                'user_approve'          => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                                'tgl_incoming'          => $get_pipeline->tgl_input,
                                'tgl_approve'           => date('Y-m-d H:i:s'),
                            ],
                            'where_delete' => $get_tahapan->no_urut,
                        ];
                    }
                }
            }

            if ($get_tahapan->jenis == 'wont') {
                $data_realisasi = [
                    'update_pelanggan' => [
                        'jenis'       => '1',
                        'user_update' => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                        'tgl_update'  => date('Y-m-d H:i:s'),
                    ],
                    'where_pelanggan' => [
                        'id_pelanggan' => $get_pipeline->id_pelanggan,
                    ],
                    'jenis' => $get_tahapan->jenis
                ];
                $realisasi_sales   = $this->model->get_realisasi_sales($get_preview->user_id, $get_pipeline->tahun, $get_pipeline->bulan, $get_pipeline->id_group);
                $target_personil_r = $this->db->get_where('sales_target_personil_r', [
                    'id_company'  => $this->id_company,
                    'id_karyawan' => $get_preview->user_id,
                    'tahun'       => $get_pipeline->tahun,
                    'bulan'       => $get_pipeline->bulan,
                    'id_group_m'  => $get_pipeline->id_group ?: '',
                ])->num_rows();
                if ($target_personil_r > 0) {
                    $data_realisasi['target_personil_for'] = 'update';
                    $data_realisasi['target_personil_r'] = [
                        'nominal_realisasi' => ($realisasi_sales->nominal_realisasi != null) ? ($realisasi_sales->nominal_realisasi + $get_pipeline->nominal_layanan) : $get_pipeline->nominal_layanan,
                        'jumlah_po'         => (int)($realisasi_sales->jumlah_po) + 1,
                        'user_update'       => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                        'tgl_update'        => date('Y-m-d H:i:s'),
                        'id_group_m'        => $get_pipeline->id_group ?: '',
                    ];
                } else {
                    $data_realisasi['target_personil_for'] = 'insert';
                    $target_personil_p = $this->db->get_where('sales_target_personil_p', [
                        'id_company'  => $this->id_company,
                        'id_karyawan' => $get_preview->user_id,
                        'tahun'       => $get_pipeline->tahun,
                        'bulan'       => $get_pipeline->bulan,
                    ])->num_rows();
                    if ($target_personil_p == 0) {
                        $data_realisasi['target_personil_p'] = [
                            'id_karyawan' => $get_preview->user_id,
                            'tahun'       => $get_pipeline->tahun,
                            'bulan'       => $get_pipeline->bulan,
                            'nominal'     => 0,
                            'id_company'  => $this->id_company,
                            'user_input'  => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                            'tgl_input'   => date('Y-m-d H:i:s'),
                        ];
                    }
                    $data_realisasi['target_personil_r'] = [
                        'id_karyawan'       => $get_preview->user_id,
                        'nik'               => $get_preview->nik,
                        'nama_karyawan'     => $get_preview->nama_karyawan,
                        'tahun'             => $get_pipeline->tahun,
                        'bulan'             => $get_pipeline->bulan,
                        'nominal_target'    => 0,
                        'nominal_realisasi' => ($realisasi_sales->nominal_realisasi != null) ? ($realisasi_sales->nominal_realisasi + $get_pipeline->nominal_layanan) : $get_pipeline->nominal_layanan,
                        'jumlah_po'         => $realisasi_sales->jumlah_po + 1,
                        'id_group_m'        => $get_pipeline->id_group ?: '',
                        'nama_group'        => $get_pipeline->id_group ? $get_pipeline->kode_group . ' - ' . $get_pipeline->nama_group : '',
                        'id_company'        => $this->id_company,
                        'user_input'        => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                        'tgl_input'         => date('Y-m-d H:i:s'),
                    ];
                }
            }

            $data_main = [
                'update' => [
                    'status' => 'approve',
                ],
                'where' => [
                    'id_pipeline_main' => $id_pipeline_main,
                    'id_company'       => $this->id_company
                ]
            ];

            $data_main_log = [
                'update' => [
                    'status'       => 'approve',
                    'user_approve' => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                    'tgl_approve'  => date('Y-m-d H:i:s'),
                ],
                'where' => [
                    'id_pipeline_main_log' => $id_pipeline_main_log,
                    'id_company'           => $this->id_company
                ]
            ];

            $where_update = [
                'id_company'       => $this->id_company,
                'id_karyawan'      => $get_preview->user_id,
                'tahun'            => $get_pipeline->tahun,
                'bulan'            => $get_pipeline->bulan,
                'id_pipeline_main' => $id_pipeline_main
            ];

            $this->model->verify_approve('log', [$data_trx, $data_main, $data_main_log, $data_realisasi, $where_update], $action);
        } else {
            $split = explode('_', $id);
            $id    = $split[0];
            $tgl   = $split[1];
            $jam   = str_replace('-', ':', $split[2]);

            $data_activity = [
                'update' => [
                    'status'       => 'approve',
                    'user_approve' => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                    'tgl_approve'  => date('Y-m-d H:i:s'),
                ],
                'where' => [
                    'id_company'   => $this->id_company,
                    'id_karyawan'  => $get_preview->user_id,
                    'tgl_activity' => $tgl,
                    'jam_activity' => $jam
                ]
            ];
            $this->model->verify_approve('activity', $data_activity);
        }
    }

    public function verify_reject()
    {
        $tabel = $this->input->post('tabel');
        $id    = $this->input->post('id');

        // validation
        if (empty($tabel) || empty($id)) return __response_update(false);
        if (!in_array($tabel, ['log', 'activity'])) return __response_update(false);

        // classify data
        $get_preview = $this->model->preview_verifikasi($tabel, $id);
        if ($tabel == 'log') {
            $id_pipeline_main     = $get_preview->id_pipeline_main;
            $id_pipeline_main_log = $get_preview->id_pipeline_main_log;
            $action               = $get_preview->aktivitas;

            if ($get_preview->kategori === 'move') {
                // tolak pindah bulan
                $this->verify_reject_pindah_bulan($get_preview);
            } else {
                if ($get_preview->aktivitas == 'New') {
                    $data_main = [
                        'update' => [
                            'status' => 'tolak',
                        ],
                        'where' => [
                            'id_pipeline_main' => $id_pipeline_main,
                            'id_company'       => $this->id_company
                        ]
                    ];
                } else {
                    $data_main = [
                        'update' => [
                            'id_tahapan_m' => $get_preview->id_tahapan_sebelum,
                            'status'       => 'approve',
                        ],
                        'where' => [
                            'id_pipeline_main' => $id_pipeline_main,
                            'id_company'       => $this->id_company
                        ]
                    ];

                    $data_main_log_insert = [
                        'id_pipeline_main_log' => $this->fungsi->getNextId('sales_pipeline_main_log', 'id_pipeline_main_log', $this->id_company, 5),
                        'id_pipeline_main'     => $id_pipeline_main,
                        'tahapan_sesudah_id'   => $get_preview->id_tahapan_sebelum,
                        'tahapan_sesudah_nm'   => $get_preview->tahapan_sebelum,
                        'status'               => 'approve',
                        'id_company'           => $this->id_company,
                        'user_input'           => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                    ];
                }

                $data_main_log_update = [
                    'update' => [
                        'status'       => 'tolak',
                        'user_approve' => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                        'tgl_approve'  => date('Y-m-d H:i:s'),
                    ],
                    'where' => [
                        'id_pipeline_main_log' => $id_pipeline_main_log,
                        'id_company'           => $this->id_company
                    ]
                ];

                $this->model->verify_reject('log', [$data_main, $data_main_log_update, $data_main_log_insert], $action);
            }
        } else {
            $split = explode('_', $id);
            $id    = $split[0];
            $tgl   = $split[1];
            $jam   = str_replace('-', ':', $split[2]);

            $data_activity = [
                'update' => [
                    'status'       => 'tolak',
                    'user_approve' => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                    'tgl_approve'  => date('Y-m-d H:i:s'),
                ],
                'where' => [
                    'id_company'   => $this->id_company,
                    'id_karyawan'  => $get_preview->user_id,
                    'tgl_activity' => $tgl,
                    'jam_activity' => $jam
                ]
            ];
            $this->model->verify_reject('activity', $data_activity);
        }
    }

    # mass approval
    public function verify_mass_confirmation()
    {
        $data['list']    = json_encode($this->input->post('selected_rows'));
        $data['content'] = 'Data dipilih';
        $this->load->view('sales_activity/approval_activity/verifikasi_masal', $data);
    }

    public function verify_mass_approve()
    {
        $selected_data = $this->input->post('selected_data');
        $log           = [];
        $activity      = [];

        // validation
        if (count($selected_data) == 0) return __response_approve(false);

        // classify data
        foreach ($selected_data as $item) {
            if (strpos($item, 'log_') === 0) {
                $log[] = str_replace('log_', '', $item);
            } elseif (strpos($item, 'activity_') === 0) {
                $combined_item = str_replace('activity_', '', $item);
                $split         = explode('_', $combined_item);
                $id            = $split[0];
                $tgl           = $split[1];
                $jam           = str_replace('-', ':', $split[2]);
                $activity[]    = $this->id_company . $id . $tgl . $jam;
            }
        }

        // get next id_pipeline_trx
        $id_pipeline_trx = $this->fungsi->getNextId('sales_pipeline_trx', 'id_pipeline_trx', $this->id_company, 5);

        // collecting data for updating log
        $data_trx = [
            'insert' => [],
            'delete' => [],
            'update' => [],
        ];
        $data_main      = [];
        $data_main_log  = [];
        $data_realisasi = [];

        if (!empty($log)) {
            $preview_log = $this->model->preview_verifikasi('log', $log, 'mass');
            if (count($preview_log) > 0) {
                $get_pipeline_log = $this->model->get_detail_pipeline_by_log($log);
                foreach ($preview_log as $preview) {
                    $id_pipeline_main     = $preview->id_pipeline_main;
                    $id_pipeline_main_log = $preview->id_pipeline_main_log;

                    $get_pipeline = $get_pipeline_log[$id_pipeline_main];
                    $get_tahapan  = $this->model->get_data_tahapan_trx($get_pipeline['tahun'], $get_pipeline['bulan'], $preview->id_tahapan_sekarang)[0];

                    // jika pindah bulan
                    if ($preview->kategori === 'move') {
                        $sales_group  = $this->model->get_sales_group($get_pipeline['id_karyawan']);
                        $pipeline_trx = $this->db->get_where('sales_pipeline_trx', ['id_company' => $this->id_company, 'id_pipeline_main' => $get_pipeline['id_pindah_bulan']])->result();
                        foreach ($pipeline_trx as $value) {
                            $data_trx['insert'][] = [
                                'id_pipeline_trx'       => $id_pipeline_trx,
                                'id_pipeline_main'      => $id_pipeline_main,
                                'id_karyawan'           => $value->id_karyawan,
                                'nik'                   => $value->nik,
                                'nama_karyawan'         => $value->nama_karyawan,
                                'tahun'                 => $get_pipeline['tahun'],
                                'bulan'                 => $get_pipeline['bulan'],
                                'id_tahapan'            => $value->id_tahapan,
                                'jenis_tahapan'         => $value->jenis_tahapan,
                                'nama_tahapan'          => $value->nama_tahapan,
                                'warna_tahapan'         => $value->warna_tahapan,
                                'warna_text_tahapan'    => $value->warna_text_tahapan,
                                'no_urut_tahapan'       => $value->no_urut_tahapan,
                                'nominal_layanan'       => $value->nominal_layanan,
                                'jumlah_layanan'        => $value->jumlah_layanan,
                                'id_pelanggan'          => $value->id_pelanggan,
                                'nama_perusahaan'       => $value->nama_perusahaan,
                                'provinsi'              => $value->provinsi,
                                'kota'                  => $value->kota,
                                'kecamatan'             => $value->kecamatan,
                                'kelurahan'             => $value->kelurahan,
                                'alamat'                => $value->alamat,
                                'nama_jenis_perusahaan' => $value->nama_jenis_perusahaan,
                                'nama_lead_source'      => $value->nama_lead_source,
                                'title'                 => $value->title,
                                'id_group_m'            => $value->id_group_m ? $value->id_group_m : ($sales_group->id_group_m ?: ''),
                                'nama_group'            => $value->id_group_m ? $value->nama_group : ($sales_group ? $sales_group->kode . ' - ' . $sales_group->nama : ''),
                                'tgl_incoming'          => $value->tgl_incoming,
                                'id_company'            => $value->id_company,
                                'user_approve'          => $value->user_approve,
                                'tgl_approve'           => $value->tgl_approve,
                            ];

                            $last_id         = substr($id_pipeline_trx, -5);
                            $id_pipeline_trx = $this->id_company . date('Ym') . sprintf("%05d", ($last_id + 1));
                        }
                    } else {
                        if ($preview->aktivitas == 'New') {
                            $data_trx['insert'][] = [
                                'id_pipeline_trx'       => $id_pipeline_trx,
                                'id_pipeline_main'      => $id_pipeline_main,
                                'id_karyawan'           => $preview->user_id,
                                'nik'                   => $get_pipeline['sales_nik'],
                                'nama_karyawan'         => $get_pipeline['sales_nama'],
                                'tahun'                 => $get_pipeline['tahun'],
                                'bulan'                 => $get_pipeline['bulan'],
                                'id_tahapan'            => $get_tahapan->id_tahapan_m,
                                'jenis_tahapan'         => $get_tahapan->jenis,
                                'nama_tahapan'          => $get_tahapan->nama,
                                'warna_tahapan'         => $get_tahapan->warna,
                                'warna_text_tahapan'    => $get_tahapan->warna_text,
                                'no_urut_tahapan'       => $get_tahapan->no_urut,
                                'nominal_layanan'       => $get_pipeline['nominal_layanan'],
                                'jumlah_layanan'        => $get_pipeline['jumlah_layanan'],
                                'id_pelanggan'          => $get_pipeline['id_pelanggan'],
                                'nama_perusahaan'       => $get_pipeline['nama_perusahaan'],
                                'provinsi'              => $get_pipeline['provinsi'],
                                'kota'                  => $get_pipeline['kota'],
                                'kecamatan'             => $get_pipeline['kecamatan'] ?: '',
                                'kelurahan'             => $get_pipeline['kelurahan'] ?: '',
                                'alamat'                => $get_pipeline['alamat'],
                                'nama_jenis_perusahaan' => $get_pipeline['nama_jenis_perusahaan'] ?: '',
                                'nama_lead_source'      => $get_pipeline['nama_lead_source'],
                                'title'                 => $get_pipeline['title'] ?: '',
                                'id_group_m'            => $get_pipeline['id_group'] ?: '',
                                'nama_group'            => $get_pipeline['id_group'] ? $get_pipeline['kode_group'] . ' - ' . $get_pipeline['nama_group'] : '',
                                'id_company'            => $this->id_company,
                                'user_approve'          => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                                'tgl_incoming'          => $get_pipeline['tgl_input'],
                                'tgl_approve'           => date('Y-m-d H:i:s'),
                            ];

                            $last_id         = substr($id_pipeline_trx, -5);
                            $id_pipeline_trx = $this->id_company . date('Ym') . sprintf("%05d", ($last_id + 1));
                        } else {
                            $data_trx['delete'][] = [
                                $preview->user_id . $get_pipeline['tahun'] . $get_pipeline['bulan'] . $this->id_company . $id_pipeline_main,
                                $get_tahapan->no_urut
                            ];

                            $data_existing_trx = $this->model->get_data_existing_trx($preview->user_id, $get_pipeline['tahun'], $get_pipeline['bulan'], $id_pipeline_main, $get_tahapan->id_tahapan_m);
                            if (count($data_existing_trx) > 0) {
                                $data_trx['update'][] = [
                                    'concat(id_karyawan,tahun,bulan,id_company,id_pipeline_main,id_tahapan)' => $preview->user_id . $get_pipeline['tahun'] . $get_pipeline['bulan'] . $this->id_company . $id_pipeline_main . $get_tahapan->id_tahapan_m,
                                    'jenis_tahapan'                                                          => $get_tahapan->jenis,
                                    'nama_tahapan'                                                           => $get_tahapan->nama,
                                    'warna_tahapan'                                                          => $get_tahapan->warna,
                                    'warna_text_tahapan'                                                     => $get_tahapan->warna_text,
                                    'no_urut_tahapan'                                                        => $get_tahapan->no_urut,
                                    'nominal_layanan'                                                        => $get_pipeline['nominal_layanan'],
                                    'jumlah_layanan'                                                         => $get_pipeline['jumlah_layanan'],
                                    'user_approve'                                                           => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                                    'tgl_approve'                                                            => date('Y-m-d H:i:s'),
                                ];
                            } else {
                                $data_trx['insert'][] = [
                                    'id_pipeline_trx'       => $id_pipeline_trx,
                                    'id_pipeline_main'      => $id_pipeline_main,
                                    'id_karyawan'           => $preview->user_id,
                                    'nik'                   => $get_pipeline['sales_nik'],
                                    'nama_karyawan'         => $get_pipeline['sales_nama'],
                                    'tahun'                 => $get_pipeline['tahun'],
                                    'bulan'                 => $get_pipeline['bulan'],
                                    'id_tahapan'            => $get_tahapan->id_tahapan_m,
                                    'jenis_tahapan'         => $get_tahapan->jenis,
                                    'nama_tahapan'          => $get_tahapan->nama,
                                    'warna_tahapan'         => $get_tahapan->warna,
                                    'warna_text_tahapan'    => $get_tahapan->warna_text,
                                    'no_urut_tahapan'       => $get_tahapan->no_urut,
                                    'nominal_layanan'       => $get_pipeline['nominal_layanan'],
                                    'jumlah_layanan'        => $get_pipeline['jumlah_layanan'],
                                    'id_pelanggan'          => $get_pipeline['id_pelanggan'],
                                    'nama_perusahaan'       => $get_pipeline['nama_perusahaan'],
                                    'provinsi'              => $get_pipeline['provinsi'],
                                    'kota'                  => $get_pipeline['kota'],
                                    'kecamatan'             => $get_pipeline['kecamatan'] ?: '',
                                    'kelurahan'             => $get_pipeline['kelurahan'] ?: '',
                                    'alamat'                => $get_pipeline['alamat'],
                                    'nama_jenis_perusahaan' => $get_pipeline['nama_jenis_perusahaan'] ?: '',
                                    'nama_lead_source'      => $get_pipeline['nama_lead_source'],
                                    'title'                 => $get_pipeline['title'] ?: '',
                                    'id_group_m'            => $get_pipeline['id_group'] ?: '',
                                    'nama_group'            => $get_pipeline['id_group'] ? $get_pipeline['kode_group'] . ' - ' . $get_pipeline['nama_group'] : '',
                                    'id_company'            => $this->id_company,
                                    'user_approve'          => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                                    'tgl_incoming'          => $get_pipeline['tgl_input'],
                                    'tgl_approve'           => date('Y-m-d H:i:s'),
                                ];

                                $last_id         = substr($id_pipeline_trx, -5);
                                $id_pipeline_trx = $this->id_company . date('Ym') . sprintf("%05d", ($last_id + 1));
                            }
                        }
                    }

                    if ($get_tahapan->jenis == 'wont') {
                        $realisasi_sales = $this->model->get_realisasi_sales($preview->user_id, $get_pipeline['tahun'], $get_pipeline['bulan'], $get_pipeline['id_group']);
                        $target_personil_r = $this->db->get_where('sales_target_personil_r', [
                            'id_company'  => $this->id_company,
                            'id_karyawan' => $preview->user_id,
                            'tahun'       => $get_pipeline['tahun'],
                            'bulan'       => $get_pipeline['bulan'],
                            'id_group_m'  => $get_pipeline['id_group'] ?: '',
                        ])->num_rows();

                        if ($target_personil_r > 0) {
                            $key = $preview->user_id . $get_pipeline['tahun'] . $get_pipeline['bulan'] . $this->id_company . ($get_pipeline['id_group'] ?: '');

                            $existing_index = false;
                            foreach ($data_realisasi['update'] as $index => $item) {
                                list($concat_key) = array_values($item);
                                if ($concat_key === $key) {
                                    $existing_index = $index;
                                    break;
                                }
                            }

                            if ($existing_index === false) {
                                // Add new entry
                                $data_realisasi['update'][] = [
                                    'concat(id_karyawan,tahun,bulan,id_company,id_group_m)' => $key,
                                    'nominal_realisasi'                                     => ($realisasi_sales->nominal_realisasi != null) ? ($realisasi_sales->nominal_realisasi + $get_pipeline['nominal_layanan']) : $get_pipeline['nominal_layanan'],
                                    'jumlah_po'                                             => $realisasi_sales->jumlah_po + 1,
                                    'user_update'                                           => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                                    'tgl_update'                                            => date('Y-m-d H:i:s'),
                                ];
                            } else {
                                // Update existing entry
                                $data_realisasi['update'][$existing_index]['nominal_realisasi'] += $get_pipeline['nominal_layanan'];
                                $data_realisasi['update'][$existing_index]['jumlah_po']         += 1;
                            }
                        } else {
                            // Check for existing entry in target_personil_p
                            $target_personil_p = $this->db->get_where('sales_target_personil_p', [
                                'id_company'  => $this->id_company,
                                'id_karyawan' => $preview->user_id,
                                'tahun'       => $get_pipeline['tahun'],
                                'bulan'       => $get_pipeline['bulan'],
                            ])->num_rows();
                            if ($target_personil_p == 0) {
                                $existing_p = false;
                                foreach ($data_realisasi['insert']['target_personil_p'] ?? [] as $index => $item) {
                                    if (
                                        $item['id_karyawan'] == $preview->user_id &&
                                        $item['tahun']       == $get_pipeline['tahun'] &&
                                        $item['bulan']       == $get_pipeline['bulan']
                                    ) {
                                        $existing_p = $index;
                                        break;
                                    }
                                }

                                if ($existing_p === false) {
                                    $data_realisasi['insert']['target_personil_p'][] = [
                                        'id_karyawan' => $preview->user_id,
                                        'tahun'       => $get_pipeline['tahun'],
                                        'bulan'       => $get_pipeline['bulan'],
                                        'nominal'     => 0,
                                        'id_company'  => $this->id_company,
                                        'user_input'  => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                                        'tgl_input'   => date('Y-m-d H:i:s'),
                                    ];
                                }
                            }

                            // Check for existing entry in target_personil_r
                            $existing_r = false;
                            foreach ($data_realisasi['insert']['target_personil_r'] ?? [] as $index => $item) {
                                if (
                                    $item['id_karyawan'] == $preview->user_id &&
                                    $item['tahun']       == $get_pipeline['tahun'] &&
                                    $item['bulan']       == $get_pipeline['bulan'] &&
                                    $item['id_group']    == $get_pipeline['id_group']
                                ) {
                                    $existing_r = $index;
                                    break;
                                }
                            }

                            if ($existing_r === false) {
                                $data_realisasi['insert']['target_personil_r'][] = [
                                    'id_karyawan'       => $preview->user_id,
                                    'nik'               => $preview->nik,
                                    'nama_karyawan'     => $preview->nama_karyawan,
                                    'tahun'             => $get_pipeline['tahun'],
                                    'bulan'             => $get_pipeline['bulan'],
                                    'nominal_target'    => 0,
                                    'nominal_realisasi' => ($realisasi_sales->nominal_realisasi != null) ? ($realisasi_sales->nominal_realisasi + $get_pipeline['nominal_layanan']) : $get_pipeline['nominal_layanan'],
                                    'jumlah_po'         => $realisasi_sales->jumlah_po + 1,
                                    'id_group_m'        => $get_pipeline['id_group'] ?: '',
                                    'nama_group'        => $get_pipeline['id_group'] ? $get_pipeline['kode_group'] . ' - ' . $get_pipeline['nama_group'] : '',
                                    'id_company'        => $this->id_company,
                                    'user_input'        => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                                    'tgl_input'         => date('Y-m-d H:i:s'),
                                ];
                            } else {
                                // Update existing entry
                                $data_realisasi['insert']['target_personil_r'][$existing_r]['nominal_realisasi'] += $get_pipeline['nominal_layanan'];
                                $data_realisasi['insert']['target_personil_r'][$existing_r]['jumlah_po']         += 1;
                            }
                        }
                        $data_realisasi['pelanggan'][] = [
                            'id_pelanggan' => $get_pipeline['id_pelanggan'],
                            'jenis'        => '1',
                            'user_update'  => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                            'tgl_update'   => date('Y-m-d H:i:s'),
                        ];
                    }

                    $data_main[] = [
                        'concat(id_pipeline_main,id_company)' => $id_pipeline_main . $this->id_company,
                        'status'                              => 'approve',
                    ];

                    $data_main_log[] = [
                        'concat(id_pipeline_main_log,id_company)' => $id_pipeline_main_log . $this->id_company,
                        'status'                                  => 'approve',
                        'user_approve'                            => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                        'tgl_approve'                             => date('Y-m-d H:i:s'),
                    ];
                }
            }
        }

        // collecting data for updating activity
        $data_activity = [];

        if (!empty($activity)) {
            $preview_activity = $this->model->preview_verifikasi('activity', $activity, 'mass');
            if (count($preview_activity) > 0) {
                foreach ($preview_activity as $preview) {
                    $split = explode(' ', $preview->waktu);
                    $tgl   = $split[0];
                    $jam   = $split[1];

                    $data_activity[] = [
                        'concat(id_company,id_karyawan,tgl_activity,jam_activity)' => $this->id_company . $preview->user_id . $tgl . $jam,
                        'status'                                                   => 'approve',
                        'user_approve'                                             => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                        'tgl_approve'                                              => date('Y-m-d H:i:s'),
                    ];
                }
            }
        }

        $this->db->trans_begin();

        if (!empty($log)) $this->model->verify_mass_approve('log', [$data_trx, $data_main, $data_main_log, $data_realisasi]);
        if (!empty($activity)) $this->model->verify_mass_approve('activity', $data_activity);

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

    public function verify_mass_reject()
    {
        $selected_data = $this->input->post('selected_data');
        $log           = [];
        $activity      = [];

        // validation
        if (count($selected_data) == 0) return __response_approve(false);

        // classify data
        foreach ($selected_data as $item) {
            if (strpos($item, 'log_') === 0) {
                $log[] = str_replace('log_', '', $item);
            } elseif (strpos($item, 'activity_') === 0) {
                $combined_item = str_replace('activity_', '', $item);
                $split         = explode('_', $combined_item);
                $id            = $split[0];
                $tgl           = $split[1];
                $jam           = str_replace('-', ':', $split[2]);
                $activity[]    = $this->id_company . $id . $tgl . $jam;
            }
        }

        // collecting data for updating log
        $data_main            = [];
        $data_main_log_update = [];
        $data_main_log_insert = [];

        if (!empty($log)) {
            $preview_log = $this->model->preview_verifikasi('log', $log, 'mass');
            if (count($preview_log) > 0) {
                $next_id_pipeline_main_log = $this->fungsi->getNextId('sales_pipeline_main_log', 'id_pipeline_main_log', $this->id_company, 5);
                foreach ($preview_log as $preview) {
                    $id_pipeline_main     = $preview->id_pipeline_main;
                    $id_pipeline_main_log = $preview->id_pipeline_main_log;
                    $action               = $preview->aktivitas;

                    if ($preview->kategori === 'move') {
                        $data_main[] = [
                            'id_pipeline_main' => $id_pipeline_main,
                            'status'           => 'tolak',
                            'id_pindah_bulan'  => ''
                        ];
                    } else {
                        if ($preview->aktivitas == 'New') {
                            $data_main[] = [
                                'id_pipeline_main' => $id_pipeline_main,
                                'status' => 'tolak',
                            ];
                        } else {
                            $data_main[] = [
                                'id_pipeline_main' => $id_pipeline_main,
                                'id_tahapan_m'     => $preview->id_tahapan_sebelum,
                                'status'           => 'approve',
                            ];

                            $data_main_log_insert[] = [
                                'id_pipeline_main_log' => $next_id_pipeline_main_log,
                                'id_pipeline_main'     => $id_pipeline_main,
                                'tahapan_sesudah_id'   => $preview->id_tahapan_sebelum,
                                'tahapan_sesudah_nm'   => $preview->tahapan_sebelum,
                                'status'               => 'approve',
                                'id_company'           => $this->id_company,
                                'user_input'           => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                            ];
                            $last_id                   = substr($next_id_pipeline_main_log, -5);
                            $next_id_pipeline_main_log = $this->id_company . date('Ym') . sprintf("%05d", ($last_id + 1));
                        }
                    }

                    $data_main_log_update[] = [
                        'id_pipeline_main_log' => $id_pipeline_main_log,
                        'status'               => 'tolak',
                        'user_approve'         => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                        'tgl_approve'          => date('Y-m-d H:i:s'),
                    ];
                }
            }
        }

        // collecting data for updating activity
        $data_activity = [];

        if (!empty($activity)) {
            $preview_activity = $this->model->preview_verifikasi('activity', $activity, 'mass');
            if (count($preview_activity) > 0) {
                foreach ($preview_activity as $preview) {
                    $split = explode(' ', $preview->waktu);
                    $tgl   = $split[0];
                    $jam   = $split[1];

                    $data_activity[] = [
                        'concat(id_company,id_karyawan,tgl_activity,jam_activity)' => $this->id_company . $preview->user_id . $tgl . $jam,
                        'status'                                                   => 'tolak',
                        'user_approve'                                             => $this->nik_karyawan . ' - ' . $this->nm_karyawan,
                        'tgl_approve'                                              => date('Y-m-d H:i:s'),
                    ];
                }
            }
        }

        $this->db->trans_begin();

        if (!empty($log)) $this->model->verify_mass_reject('log', [$data_main, $data_main_log_update, $data_main_log_insert], $action);
        if (!empty($activity)) $this->model->verify_mass_reject('activity', $data_activity);

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

    # all approval
    public function verify_all_confirmation($mulai, $selesai, $karyawan = 'all')
    {
        // reformat date
        $mulai          = $mulai ? date('Y-m-d', strtotime($mulai)) : '';
        $selesai        = $selesai ? date('Y-m-d', strtotime($selesai)) : '';
        $data_pengajuan = $this->model->get_data_pengajuan($mulai, $selesai, $karyawan);

        $list_data = [];
        foreach ($data_pengajuan as $value) {
            if ($value->tabel == 'log') {
                $list_data[] = $value->tabel . '_' . $value->id;
            } else {
                $list_data[] = $value->tabel . '_' . $value->user_id . '_' . str_replace(":", "-", str_replace(" ", "_", $value->waktu));
            }
        }

        $data['list']    = json_encode($list_data);
        $data['content'] = 'Data Pengajuan';
        $this->load->view('sales_activity/approval_activity/verifikasi_masal', $data);
    }

    public function verify_reject_pindah_bulan($data_pipeline)
    {
        // validation
        if (!$data_pipeline) {
            return __response_update(false);
        }

        $this->model->verify_reject_pindah_bulan($data_pipeline);
    }
}
