Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
49 kB
2
Indexable
Never
<?php

declare(strict_types=1);

namespace App\Http\Controllers\V1;

use stdClass;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Exceptions\ParameterException;
use App\Repositories\QCModelRepository;
use function PHPUnit\Framework\isEmpty;
use App\Exceptions\InvalidRuleException;
use App\Exceptions\DataNotFoundException;

use Illuminate\Support\Facades\Validator;
use App\Exceptions\ThirdPartyServiceException;
use App\Repositories\GeneralRepository;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;

class InputQcController extends Controller
{
    private $qcRepo;
    private $generalRepo;
    private $output;

    public function __construct(QCModelRepository $qcRepo, GeneralRepository $generalRepo)
    {
        header("Strict-Transport-Security: max-age=31536000; includeSubDomains; preload");
        $this->qcRepo = $qcRepo;
        $this->generalRepo = $generalRepo;
        $this->output = new stdClass();
        $this->output->responseCode = '';
        $this->output->responseDesc = '';
        $this->output->responseData = '';
    }

    public function getDataQCMerchant(Request $request)
    {
        $filter = [];
        $new_req = new Request([
            'mid' => $request->header('mid'),
            'nama-merchant' => $request->header('nama-merchant'),
        ]);

        $validator = Validator::make($new_req->all(), [
            'mid' => 'bail|nullable|numeric',
        ], [
            'mid.numeric' => 'Kolom MID harus berupa angka',
        ]);


        if ($validator->fails()) {
            $error_message = $validator->errors()->first();
            throw new ParameterException($error_message);
        }

        $filter['mid'] = $request->header('mid');
        $filter['nama-merchant'] = $request->header('nama-merchant');

        $result = $this->qcRepo->getDataQCMerchant($filter);
        if (empty($result->items())) {
            throw new DataNotFoundException("Data Merchant Tidak Ditemukan");
        }

        $this->output->responseCode = '00';
        $this->output->responseDesc = 'Success';
        $this->output->responseData = $result;

        return response()->json($this->output);
    }

    public function getDetailQCMerchant(Request $request)
    {
        $filter = [];
        $new_req = new Request([
            'mid' => $request->header('mid'),
            // 'nama-merchant' => $request->header('nama-merchant'),
        ]);

        $validator = Validator::make($new_req->all(), [
            'mid' => 'bail|required|numeric',
        ], [
            'mid.numeric' => 'Kolom MID harus berupa angka',
        ]);


        if ($validator->fails()) {
            $error_message = $validator->errors()->first();
            throw new ParameterException($error_message);
        }

        $filter['mid'] = $request->header('mid');
        // $filter['nama-merchant'] = $request->header('nama-merchant');

        $result = $this->qcRepo->getDetailQCMerchant($filter);
        if (empty($result)) {
            throw new DataNotFoundException("Data Merchant Tidak Ditemukan");
        }

        $this->output->responseCode = '00';
        $this->output->responseDesc = 'Success';
        $this->output->responseData = $result;

        return response()->json($this->output);
    }

    public function InputQCMerchant(Request $request)
    {
        //validate header
        $new_req = new Request([
            'PERNR' => $request->header('PERNR'),
            'NAMA-LENGKAP' => $request->header('NAMA-LENGKAP'),
            'LEVEL-ID' => $request->header('LEVEL-ID'),
        ]);
        $validator = Validator::make($new_req->all(), [
            'PERNR' => 'required',
            'NAMA-LENGKAP' => 'required',
            'LEVEL-ID' => 'required',
        ]);

        if ($validator->fails()) {
            $error_message = $validator->errors()->first();
            throw new ParameterException($error_message);
        }

        $validator = Validator::make($request->all(), [
            'app_id' => ['required'],
            'mid' => 'required|numeric',
            'nama_merchant' => ['required'],
            'dba' => ['required'],
            'alamat_merchant' => ['required'],
            'kodepos' => ['required'],
            'kelurahan' => ['required'],
            'kecamatan' => ['required'],
            'kabupaten' => ['required'],
            'provinsi' => ['required'],
            'pic' => ['required'],
            'tlp_merchant_1' => ['required', 'max:13', 'regex:/^[0-9\-]+$/'],
            'tlp_merchant_2' => ['required', 'max:13', 'regex:/^[0-9\-]+$/'],
            'jenis_merchant' => ['required'],
            'group_merchant' => 'bail|nullable|alpha',
            // 'program_merchant' => ['required'],
            'no_rek' => ['required', 'regex:/^[0-9\-]+$/'],
            'pemilik_rek' => ['required'],
            'merchant_tipe' => ['required'],
            'mcc_visa' => ['required'],
            'mcc_master' => ['required'],
            'mcc_npg' => ['required'],
            'mcc_unik'  => ['required'],
            'mcc_master_auto' => ['required', 'regex:/^[^!@#$%^&*<>\?]+$/'],
            'mcc_visa_auto' => ['required', 'regex:/^[^!@#$%^&*<>\?]+$/'],
            'mcc_npg_auto' => ['required', 'regex:/^[^!@#$%^&*<>\?]+$/'],
            'mcc_unik_auto' => ['required', 'regex:/^[^!@#$%^&*<>\?]+$/'],
            'mdr_onus' => ['required'],
            'mdr_offus' => ['required'],
            'mdr_debit' => ['required'],
            'mdr_debit_pl' => ['required'],
            'mdr_debit_npg' => ['required'],
            'mdr_unik' => ['required'],
            "sales_volume" => ['required', 'starts_with:1,2,3,4,5,6,7,8,9'],
            'jam_buka' => ['required'],
            'jam_tutup' => ['required'],
            'note' => ['required'],
            // 'mdr_plan' => ['required', 'array'],
            'mdr_plan.*.mdr_term' => ['required'],
            'mdr_plan.*.mdr_plan' => ['required'],
            'mdr_plan.*.mdr' => ['required'],
        ], [
            'mdr_plan.*.mdr_term.required' => 'The mdr installment data must be completed.',
            'mdr_plan.*.mdr_plan.required' => 'The mdr installment data must be completed.',
            'mdr_plan.*.mdr.required' => 'The mdr installment data must be completed.'
        ]);

        if ($validator->fails()) {
            $error_message = $validator->errors()->first();
            throw new ParameterException($error_message);
        }

        $req_data = $request->all();
        $data_from_table = $this->qcRepo->getMerchant($request->app_id);
        if (empty($data_from_table)) {
            throw new DataNotFoundException("app id Tidak Ditemukan");
        }

        // $old_data = [];
        foreach ($data_from_table as $key => $value) {
            $old_data[$key] = $value;
        }

        //get mapping field
        $mapping_field = $this->generalRepo->getMappingField()->toArray();
        $mapping_key = array_column($mapping_field, 'app_merchant', 'field_name');

        //compare the old and new app_merchant
        $changes = [];
        foreach ($old_data as $key => $old_value) {
            $new_value = $req_data[$key];
            if ($old_value !== $new_value && !empty($new_value)) {
                if (isset($mapping_key[$key])) {
                    $column_name = $mapping_key[$key];
                    $changes[$column_name] = array(
                        $old_value,
                        $new_value
                    );
                } else {
                    throw new ParameterException("Field " . $key . " tidak diketahui.");
                }
            }
        }

        //compare mdr
        $mdr_plan_zero = [];
        $cicilan = [];
        $mdr = $this->qcRepo->GetMdr($request->app_id);
        foreach ($mdr as $key => $value) {
            if ($value->mdr_plan == 0) {
                if ($value->on_off == 1) {
                    $mdr_plan_zero['mdr_onus'] = $value;
                }
                if ($value->on_off == 0) {
                    $mdr_plan_zero['mdr_offus'] = $value;
                }
                if ($value->on_off == 2) {
                    $mdr_plan_zero['mdr_debit'] = $value;
                }
                if ($value->on_off == 3) {
                    $mdr_plan_zero['mdr_debit_pl'] = $value;
                }
                if ($value->on_off == 4) {
                    $mdr_plan_zero['mdr_debit_png'] = $value;
                }
                if ($value->on_off == 5) {
                    $mdr_plan_zero['mdr_unik'] = $value;
                }
            } else {
                $cicilan[] = $value;
            }
        }

        if (isset($mdr_plan_zero['mdr_debit_pl']) && $request->mdr_onus !== $mdr_plan_zero['mdr_onus']->mdr) {
            $changes['mdr_onus'] = [$mdr_plan_zero['mdr_onus']->mdr, $request->mdr_onus];
        }
        if (isset($mdr_plan_zero['mdr_debit_pl']) && $request->mdr_offus !== $mdr_plan_zero['mdr_offus']->mdr) {
            $changes['mdr_offus'] = [$mdr_plan_zero['mdr_offus']->mdr, $request->mdr_offus];
        }
        if (isset($mdr_plan_zero['mdr_debit_pl']) && $request->mdr_debit !== $mdr_plan_zero['mdr_debit']->mdr) {
            $changes['mdr_debit'] = [$mdr_plan_zero['mdr_debit']->mdr, $request->mdr_debit];
        }
        if (isset($mdr_plan_zero['mdr_debit_pl']) && $request->mdr_debit_pl !== $mdr_plan_zero['mdr_debit_pl']->mdr) {
            $changes['mdr_debit_pl'] = [$mdr_plan_zero['mdr_debit_pl']->mdr, $request->mdr_debit_pl];
        }
        if (isset($mdr_plan_zero['mdr_debit_pl']) && $request->mdr_debit_npg !== $mdr_plan_zero['mdr_debit_png']->mdr) {
            $changes['mdr_debit_npg'] = [$mdr_plan_zero['mdr_debit_png']->mdr, $request->mdr_debit_npg];
        }
        if (isset($mdr_plan_zero['mdr_debit_pl']) && $request->mdr_unik !== $mdr_plan_zero['mdr_unik']->mdr) {
            $changes['mdr_unik'] = [$mdr_plan_zero['mdr_unik']->mdr, $request->mdr_unik];
        }

        $mdr_cicilan_uba = 0;
        $perubahan_mdr = [];
        $penambahan_mdr = [];
        if ($request->merchant_tipe == 99) {
            foreach ($request->mdr_plan as $key => $mdr_plan) {
                if (array_key_exists($key, $cicilan)) {
                    if ($mdr_plan['mdr'] !== $cicilan[$key]->mdr) {
                        $perubahan_mdr[] = [$mdr_plan['mdr'], $cicilan[$key]->mdr];
                    }
                    if ($mdr_plan['mdr_term'] !== $cicilan[$key]->mdr_term) {
                        $perubahan_mdr[] = [$mdr_plan['mdr_term'], $cicilan[$key]->mdr_term];
                    }
                    if ($mdr_plan['mdr_plan'] !== $cicilan[$key]->mdr_plan) {
                        $perubahan_mdr[] = [$mdr_plan['mdr_plan'], $cicilan[$key]->mdr_plan];
                    }
                } else {
                    $penambahan_mdr[] = [$mdr_plan['mdr']];
                }
            }

            if (!empty($perubahan_mdr) || !empty($penambahan_mdr) || count($request->mdr_plan) !== count($cicilan)) {
                $mdr_cicilan_uba = 1;
                // $changes['mdr_cicilan'] = [$mdr_cicilan, $request->mdr_plan];
            }
        }

        if (empty($changes) && $mdr_cicilan_uba != 1) {
            throw new DataNotFoundException("Tidak terdeteksi perubahan data");
        }

        DB::beginTransaction();
        try {
            $json_changes = json_encode($changes);

            //check perubahan mcc
            $param_mcc = 'NON-MCC';
            if (isset($changes['mcc_visa']) || isset($changes['mcc_master']) || isset($changes['mcc_npg']) || isset($changes['mcc_unik'])) {
                $param_mcc = 'MCC';
            }

            //get level
            $inbox_level = $this->qcRepo->getStatusInboxLevel($request->header('LEVEL-ID'), $param_mcc, 'INPUT');
            if (empty($inbox_level)) {
                throw new ParameterException("Anda tidak memeliki kewenangan untuk melakukan proses ini.");
            }

            //insert qc_data
            $data_insert = array(
                'app_id' => $request->app_id,
                'app_jenis' => $request->app_jenis,
                'mid' => $request->mid,
                'status' => 'INPUT',
                'status_inbox_level' => $inbox_level->user_level_next,
                'status_last_level' => $request->header('LEVEL-ID'),
                'tgl_entry' => Carbon::now()->toDateTimeString(),
                'user_entry' => $request->header('PERNR') . "|" . $request->header('NAMA-LENGKAP'),
                'note_entry' => $request->notes,
                'tgl_update' => Carbon::now()->toDateTimeString(),
                'user_update' => $request->header('PERNR') . "|" . $request->header('NAMA-LENGKAP'),
                'note_update' => $request->note,
                'is_mdr_cicilan_ubah' => $mdr_cicilan_uba,
                'data_ubah' => $json_changes
            );

            $result = $this->qcRepo->Insert($data_insert);
            if ($result === null) {
                throw new ParameterException("Gagal insert qc_data");
            }

            $arr_mdr_cicilan = [];
            if ($mdr_cicilan_uba == 1) {
                foreach ($request->mdr_plan as $rows) {
                    $arr_mdr_cicilan[] = [
                        "id_qc" => $result,
                        "mid" => $request->mid,
                        "plan" => $rows["mdr_plan"],
                        "term" => $rows["mdr_term"],
                        "mdr" => $rows["mdr"],
                    ];
                }
                $this->qcRepo->input_mdr_cicilan($arr_mdr_cicilan);
            }

            //insert qc_log
            $insert_log = array(
                'id_qc' => $result,
                'status' => 'INPUT',
                'tgl' => date("Y-m-d H:i:s"),
                'user' => $request->header('PERNR') . '|' . $request->header('NAMA-LENGKAP'),
                'user_level' => $request->header('LEVEL-ID'),
                'note' => $request->note
            );

            $result_log = $this->qcRepo->insert_qc_log($insert_log);
            if ($result_log < 0) {
                throw new ParameterException('Gagal insert log.');
            }

            DB::commit();
            $this->output->responseCode = '00';
            $this->output->responseDesc = "Data quality control berhasil diajukan.\nID QC : " . $result;
            $this->output->responseData = ['id_qc' => $result];
            return response()->json($this->output);
        } catch (\Throwable $e) {
            DB::rollback();
            $error_msg = $e->getMessage();
            throw new ParameterException($error_msg);
        }
    }

    public function AproveQCMerchant(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id_qc' => 'bail|required|numeric',
            'note_approve' => 'bail|required'
        ]);

        $validator_header = Validator::make($request->header(), [
            'level-id' => 'bail|required',
            'pernr' => 'bail|required',
            'nama-lengkap' => 'bail|required'
        ]);

        if ($validator->fails()) {
            $error_massage = $validator->errors()->first();
            throw new ParameterException($error_massage);
        }

        if ($validator_header->fails()) {
            $error_massage = $validator_header->errors()->first();
            throw new ParameterException($error_massage);
        }

        $id_qc = $request->id_qc;
        $level_id = $request->header('level-id');
        $username = $request->header('pernr');
        $nama_lengkap = $request->header('nama-lengkap');
        $note_approve = $request->note_approve;

        $data_qc = $this->qcRepo->getDataQc($id_qc);
        if (empty($data_qc)) {
            throw new DataNotFoundException("Data QC Tidak Ditemukan.");
        }

        DB::beginTransaction();
        try {
            $data_ubah = (array) json_decode($data_qc->data_ubah);
            $jmlh_data_ubah = count($data_ubah);

            //pengecekan jika melalui analis
            if ($level_id == '18') {
                if (($jmlh_data_ubah == 2) && (isset($data_ubah['mcc_visa']) || isset($data_ubah['mcc_master']) || isset($data_ubah['mcc_npg']) || isset($data_ubah['mcc_unik']))) {
                    $map_mcs = $this->qcRepo->select_data('map_mcs', array('modul' => 'QUALITYCONTROL', 'user_level_action' => $level_id, 'action' => 'APPROVE', 'param' => 'MCC'), $select_str = 'user_level_next');
                } else {
                    $map_mcs = $this->qcRepo->select_data('map_mcs', array('modul' => 'QUALITYCONTROL', 'user_level_action' => $level_id, 'action' => 'APPROVE', 'param' => 'MCC++'), $select_str = 'user_level_next');
                }
            } else {
                $map_mcs = $this->qcRepo->select_data('map_mcs', array('modul' => 'QUALITYCONTROL', 'user_level_action' => $level_id, 'action' => 'APPROVE'), $select_str = 'user_level_next');
            }

            if (count($map_mcs) < 1) {
                DB::rollback();
                throw new DataNotFoundException("Data map_mcs Tidak Ditemukan/user anda tidak dapat mengakses menu ini.");
            }

            $arr_data_trail = array();
            $arr_query_trail = array();
            if ($map_mcs[0]->user_level_next == '9999') {
                $dqc_ubah = array();
                foreach ($data_ubah as $key => $value) {
                    if ($key == 'mdr_onus' || $key == 'mdr_offus' || $key == 'mdr_debit_pl' || $key == 'mdr_debit' || $key == 'mdr_debit_npg' || $key == 'mdr_unik') {
                        $field_mdr_ubah[] = $key;
                        $mdr_ubah[$key] = $value[1];
                    } else {
                        $field_qc_ubah[] = $key;
                        if ($key == 'tlp_merchant_1' || $key == 'tlp_merchant_2') {
                            $field_param_ubah[] = 'tlp_merchant_1;tlp_merchant_2';
                        } else {
                            $field_param_ubah[] = $key;
                        }

                        $dqc_ubah[$key] = $value[1];
                    }
                }

                $arr_data_trail[] = $dqc_ubah;

                /*update data terkait hasil quality control*/
                if (isset($dqc_ubah) && count($dqc_ubah) > 0) {
                    $proses_app_merchant = $this->qcRepo->update_data('app_merchant', $dqc_ubah, array('app_id' => $data_qc->app_id, 'mid' => $data_qc->mid));

                    if ($proses_app_merchant < 0) {
                        DB::rollback();
                        throw new DataNotFoundException("Data merchant gagal diperbaharui.");
                    }

                    //update data inisiasi
                    $list_param = $this->qcRepo->get_map_merchant_inisiasi($field_param_ubah);

                    if (empty($list_param)) {
                        DB::rollback();
                        throw new DataNotFoundException("Data list_param tidak ditemukan.");
                    }

                    foreach ($list_param as $val) {
                        $field_inisiasi     = explode(';', $val->inisiasi_field);
                        $field_app_merchant = explode(';', $val->app_merchant_field);

                        if (count($field_inisiasi) == count($field_app_merchant)) {
                            if (isset($init_ubah[$val->inisiasi_field])) {
                                $init_ubah[$val->inisiasi_field] = $init_ubah[$val->inisiasi_field] . ',' . $dqc_ubah[$val->app_merchant_field];
                            } else {
                                $init_ubah[$val->inisiasi_field] = $dqc_ubah[$val->app_merchant_field];
                            }
                        }

                        if (count($field_inisiasi) > count($field_app_merchant)) {
                            for ($i = 0; $i < count($field_inisiasi); $i++) {
                                if (isset($init_ubah[$field_inisiasi[$i]])) {
                                    $init_ubah[$field_inisiasi[$i]] = $init_ubah[$field_inisiasi[$i]] . ',' . $dqc_ubah[$val->app_merchant_field];
                                } else {
                                    $init_ubah[$field_inisiasi[$i]] = $dqc_ubah[$val->app_merchant_field];
                                }
                            }
                        }

                        if (count($field_inisiasi) < count($field_app_merchant)) {
                            $app_merchant_field = "";
                            for ($i = 0; $i < count($field_app_merchant); $i++) {
                                if ($i) {
                                    $app_merchant_field = $app_merchant_field . '/' . (isset($dqc_ubah[$field_app_merchant[$i]]) ? $dqc_ubah[$field_app_merchant[$i]] : "");
                                } else {
                                    $app_merchant_field = (isset($dqc_ubah[$field_app_merchant[$i]]) ? $dqc_ubah[$field_app_merchant[$i]] : "");
                                }
                            }
                            if (isset($init_ubah[$val->inisiasi_field])) {
                                $init_ubah[$val->inisiasi_field] = $init_ubah[$val->inisiasi_field] . ',' . $app_merchant_field;
                            } else {
                                $init_ubah[$val->inisiasi_field] = $app_merchant_field;
                            }
                        }
                    }

                    if (isset($init_ubah) && count($init_ubah) > 0) {
                        $proses_inisiasi = $this->qcRepo->update_data('inisiasi', $init_ubah, array('app_id' => $data_qc->app_id));

                        if (empty($proses_inisiasi)) {
                            DB::rollback();
                            throw new DataNotFoundException("Data inisiasi gagal diperbaharui");
                        }
                    }

                    $mdr = $this->qcRepo->select_data('app_merchant_mdr', array('app_id' => $data_qc->app_id), '*');
                    $mdr_onus = 0;
                    $mdr_offus = 0;
                    $mdr_debit = 0;
                    $mdr_debit_pl = 0;
                    $mdr_debit_npg = 0;
                    $mdr_unik = 0;

                    if (isset($mdr)) {
                        foreach ($mdr as $dr) {
                            if ($dr->plan == 0) {
                                if ($dr->on_off == 1) {
                                    $mdr_onus = 1;
                                } elseif ($dr->on_off == 0) {
                                    $mdr_offus = 1;
                                } elseif ($dr->on_off == 2) {
                                    $mdr_debit = 1;
                                } elseif ($dr->on_off == 3) {
                                    $mdr_debit_pl = 1;
                                } elseif ($dr->on_off == 4) {
                                    $mdr_debit_npg = 1;
                                } elseif ($dr->on_off == 5) {
                                    $mdr_unik = 1;
                                }
                            }
                        }
                    }

                    if (isset($mdr_ubah['mdr_offus'])) {
                        if ($mdr_offus) {
                            $proses_offus = $this->qcRepo->update_data('app_merchant_mdr', array('mdr' => $mdr_ubah['mdr_offus']), array('app_id' => $data_qc->app_id, 'plan' => 0, 'on_off' => 0));
                        } else {
                            $data_offus = array(
                                'app_id'    => $data_qc->app_id,
                                'mid'         => $data_qc->mid,
                                'on_off'    => 0,
                                'plan'        => 0,
                                'term'        => 0,
                                'mdr'        => $mdr_ubah['mdr_offus']
                            );
                            $proses_offus = $this->qcRepo->insert_data('app_merchant_mdr', $data_offus);
                        }

                        if ($proses_offus < 0) {
                            DB::rollback();
                            throw new DataNotFoundException("Data MDR off us gagal diperbaharui.");
                        }
                    }

                    if (isset($mdr_ubah['mdr_onus'])) {
                        if ($mdr_onus) {
                            $proses_onus = $this->qcRepo->update_data('app_merchant_mdr', array('mdr' => $mdr_ubah['mdr_onus']), array('app_id' => $data_qc->app_id, 'plan' => 0, 'on_off' => 1));
                        } else {
                            $data_onus = array(
                                'app_id'    => $data_qc->app_id,
                                'mid'         => $data_qc->mid,
                                'on_off'    => 1,
                                'plan'        => 0,
                                'term'        => 0,
                                'mdr'        => $mdr_ubah['mdr_onus']
                            );
                            $proses_onus = $this->qcRepo->insert_data('app_merchant_mdr', $data_onus);
                        }

                        if ($proses_onus < 0) {
                            DB::rollback();
                            throw new DataNotFoundException("Data MDR on us gagal diperbaharui.");
                        }
                    }

                    if (isset($mdr_ubah['mdr_debit'])) {
                        if ($mdr_debit) {
                            $proses_debit = $this->qcRepo->update_data('app_merchant_mdr', array('mdr' => $mdr_ubah['mdr_debit']), array('app_id' => $data_qc->app_id, 'plan' => 0, 'on_off' => 2));
                        } else {
                            $data_debit = array(
                                'app_id'    => $data_qc->app_id,
                                'mid'         => $data_qc->mid,
                                'on_off'    => 2,
                                'plan'        => 0,
                                'term'        => 0,
                                'mdr'        => $mdr_ubah['mdr_debit']
                            );
                            $proses_debit = $this->qcRepo->insert_data('app_merchant_mdr', $data_debit);
                        }

                        if ($proses_debit < 0) {
                            DB::rollback();
                            throw new DataNotFoundException("Data MDR debit gagal diperbaharui.");
                        }
                    }

                    if (isset($mdr_ubah['mdr_debit_pl'])) {
                        if ($mdr_debit_pl) {
                            $proses_debit_pl = $this->qcRepo->update_data('app_merchant_mdr', array('mdr' => $mdr_ubah['mdr_debit_pl']), array('app_id' => $data_qc->app_id, 'plan' => 0, 'on_off' => 3));
                        } else {
                            $data_debit_pl = array(
                                'app_id'    => $data_qc->app_id,
                                'mid'         => $data_qc->mid,
                                'on_off'    => 3,
                                'plan'        => 0,
                                'term'        => 0,
                                'mdr'        => $mdr_ubah['mdr_debit_pl']
                            );
                            $proses_debit_pl = $this->qcRepo->insert_data('app_merchant_mdr', $data_debit_pl);
                        }

                        if ($proses_debit_pl < 0) {
                            DB::rollback();
                            throw new DataNotFoundException("Data MDR debit PL gagal diperbaharui.");
                        }
                    }

                    if (isset($mdr_ubah['mdr_debit_npg'])) {
                        if ($mdr_debit_npg) {
                            $proses_debit_npg = $this->qcRepo->update_data('app_merchant_mdr', array('mdr' => $mdr_ubah['mdr_debit_npg']), array('app_id' => $data_qc->app_id, 'plan' => 0, 'on_off' => 4));
                        } else {
                            $data_debit_npg = array(
                                'app_id'    => $data_qc->app_id,
                                'mid'         => $data_qc->mid,
                                'on_off'    => 4,
                                'plan'        => 0,
                                'term'        => 0,
                                'mdr'        => $mdr_ubah['mdr_debit_npg']
                            );
                            $proses_debit_npg = $this->qcRepo->insert_data('app_merchant_mdr', $data_debit_npg);
                        }

                        if ($proses_debit_npg < 0) {
                            DB::rollback();
                            throw new DataNotFoundException("Data MDR debit NPG gagal diperbaharui.");
                        }
                    }

                    if (isset($mdr_ubah['mdr_unik'])) {
                        if ($mdr_unik) {
                            $proses_debit_unik = $this->qcRepo->update_data('app_merchant_mdr', array('mdr' => $mdr_ubah['mdr_unik']), array('app_id' => $data_qc->app_id, 'plan' => 0, 'on_off' => 5));
                        } else {
                            $data_debit_npg = array(
                                'app_id'    => $data_qc->app_id,
                                'mid'         => $data_qc->mid,
                                'on_off'    => 5,
                                'plan'        => 0,
                                'term'        => 0,
                                'mdr'        => $mdr_ubah['mdr_unik']
                            );
                            $proses_debit_unik = $this->qcRepo->insert_data('app_merchant_mdr', $mdr_unik);
                        }

                        if ($proses_debit_unik < 0) {
                            DB::rollback();
                            throw new DataNotFoundException("Data MDR debit NPG gagal diperbaharui.");
                        }
                    }
                }

                $mdr_cicilan = $this->qcRepo->select_data('qc_mdr_cicilan_ubah', array('id_qc' => $id_qc), '*');
                if (!empty($mdr_cicilan)) {
                    $this->qcRepo->delete_data_mdr(array('app_id' => $data_qc->app_id, 'mid' => $data_qc->mid, 'on_off' => '1'));
                    foreach ($mdr_cicilan as $val) {
                        $data_mdr_cicilan = array(
                            'app_id'    => $data_qc->app_id,
                            'mid'         => $val->mid,
                            'on_off'    => 1,
                            'plan'        => $val->plan,
                            'term'        => $val->term,
                            'mdr'        => $val->mdr
                        );
                        $proses_mdr_cicilan = $this->qcRepo->insert_data('app_merchant_mdr', $data_mdr_cicilan);
                        if (!$proses_mdr_cicilan) {
                            DB::rollback();
                            throw new DataNotFoundException("Data MDR debit PL gagal diperbaharui.");
                        }
                    }
                }
            }
            $insert_update = array(
                'status'                => 'APPROVE',
                'status_inbox_level'     => $map_mcs[0]->user_level_next,
                'status_last_level'        => $level_id,
                'tgl_update'            => date('Y-m-d H:i:s'),
                'user_update'            => $username . '|' . $nama_lengkap,
                'note_update'            => $note_approve
            );

            $result_ins = $this->qcRepo->update_data('qc_data', $insert_update, array('id_qc' => $id_qc));

            $result_interface = 0;
            if ($map_mcs[0]->user_level_next == '9999') {
                $insert_interface = array('id_qc' => $id_qc);
                $result_interface = $this->qcRepo->insert_data('qc_interface', $insert_interface);
            }

            $datadbl['id_qc']         = $id_qc;
            $datadbl['status']         = 'APPROVE';
            $datadbl['tgl']         = date("Y-m-d H:i:s");
            $datadbl['user']         = $username . '|' . $nama_lengkap;
            $datadbl['user_level']     = $level_id;
            $datadbl['note']         = $note_approve;
            $insert_log = $this->qcRepo->insert_qc_log($datadbl);

            if (!$insert_log) {
                DB::rollback();
                throw new DataNotFoundException("Data insert Log PL gagal diperbaharui.");
            }

            DB::commit();
            $this->output->responseCode = "00";
            $this->output->responseDesc = "SUCCESS APRROVE QC";
            return response()->json($this->output);
        } catch (\Thowable $e) {
            DB::rollback();
            $error_msg = $e->getMessage();
            throw new DataNotFoundException($error_msg);
        }
    }

    public function RejectQCMerchant(Request $request)
    {
        //validate header
        $new_req = new Request([
            'PERNR' => $request->header('PERNR'),
            'NAMA-LENGKAP' => $request->header('NAMA-LENGKAP'),
            'LEVEL-ID' => $request->header('LEVEL-ID'),
        ]);
        $validator = Validator::make($new_req->all(), [
            'PERNR' => 'required',
            'NAMA-LENGKAP' => 'required',
            'LEVEL-ID' => 'required',
        ]);

        if ($validator->fails()) {
            $error_message = $validator->errors()->first();
            throw new ParameterException($error_message);
        }

        $validator = Validator::make($request->all(), [
            'id_qc' => 'required',
            'status' => 'required',
            'notes' => 'bail|required'
        ], [
            'notes.required' => 'The notes reject field is required'
        ]);

        if ($validator->fails()) {
            $error_message = $validator->errors()->first();
            throw new ParameterException($error_message);
        }
        DB::beginTransaction();
        try {
            $map_mcs = $this->qcRepo->select_data('map_mcs', array('modul' => 'QUALITYCONTROL', 'user_level_action' => $request->header('LEVEL-ID'), 'action' => $request->status), $select_str = 'user_level_next');

            if (count($map_mcs) < 1) {
                throw new DataNotFoundException("Data map_mcs Tidak Ditemukan/user anda tidak dapat mengakses menu ini.");
            }

            $data_update = array(
                'status' => $request->status,
                'status_inbox_level' => $map_mcs[0]->user_level_next,
                'status_last_level' => $request->header('LEVEL-ID'),
                'tgl_update' => date('Y-m-d H:i:s'),
                'user_update' => $request->header('PERNR') . '|' . $request->header('NAMA-LENGKAP'),
                'note_update' => $request->notes
            );

            $where = [
                'id_qc' => $request->id_qc
            ];

            $result_update = $this->qcRepo->update_data('qc_data', $data_update, $where);
            if ($result_update < 0) {
                DB::rollBack();
                throw new ParameterException('Gagal update qc_data.');
            }

            $insert_log = array(
                'id_qc' => $request->id_qc,
                'status' => $request->status,
                'tgl' => date("Y-m-d H:i:s"),
                'user' => $request->header('PERNR') . '|' . $request->header('NAMA-LENGKAP'),
                'user_level' => $request->header('LEVEL-ID'),
                'note' => $request->notes
            );

            $result_log = $this->qcRepo->insert_qc_log($insert_log);
            if ($result_log < 0) {
                DB::rollBack();
                throw new ParameterException('Gagal insert log.');
            }

            DB::commit();
            $this->output->responseCode = "00";
            $this->output->responseDesc = "SUCCESS APRROVE QC";
            return response()->json($this->output);
        } catch (\Throwable $e) {
            DB::rollback();
            $error_msg = $e->getMessage();
            throw new ParameterException($error_msg);
        }
    }

    public function DeleteQCMerchant(Request $request)
    {
        //validate header
        $new_req = new Request([
            'PERNR' => $request->header('PERNR'),
            'NAMA-LENGKAP' => $request->header('NAMA-LENGKAP'),
            'LEVEL-ID' => $request->header('LEVEL-ID'),
        ]);
        $validator = Validator::make($new_req->all(), [
            'PERNR' => 'required',
            'NAMA-LENGKAP' => 'required',
            'LEVEL-ID' => 'required',
        ]);

        if ($validator->fails()) {
            $error_message = $validator->errors()->first();
            throw new ParameterException($error_message);
        }

        $validator = Validator::make($request->all(), [
            'id_qc' => 'required',
        ]);
        if ($validator->fails()) {
            $error_message = $validator->errors()->first();
            throw new ParameterException($error_message);
        }

        $data_qc = $this->qcRepo->getDataQc($request->id_qc);
        if (empty($data_qc)) {
            throw new DataNotFoundException("Data QC Tidak Ditemukan.");
        }

        $req_user_entry = $request->header('PERNR') . '|' . $request->header('NAMA-LENGKAP');
        if ($data_qc->user_entry != $req_user_entry) {
            throw new ParameterException("User entry tidak sesuai");
        }

        if ($data_qc->status != 'REJECT') {
            throw new ParameterException("Status tidak sesuai");
        }

        $delete_qc_result = $this->qcRepo->delete_qc_data($request->id_qc);

        if ($delete_qc_result < 0) {
            throw new ParameterException("Data QC gagal di hapus");
        }

        $delete_log = $this->qcRepo->delete_qc_log($request->id_qc);

        if ($delete_log < 0) {
            throw new ParameterException("Data log gagal di hapus");
        }

        $this->output->responseCode = "00";
        $this->output->responseDesc = "SUCCESS DELETE QC";
        return response()->json($this->output);
    }

    public function updateInterfaceStatus(Request $request)
    {
        $where = array('job_name' => $request->jobname);

        $update_data['status'] = '-1';
        $update_data['ket'] = 'RETRY';
        $update_data['last_update'] = date('Y-m-d H:i:s');

        DB::beginTransaction();
        try {
            $res = $this->qcRepo->update_data('interface_status', $update_data, $where);

            if ($res < 0) {
                DB::rollback();
                throw new DataNotFoundException("Data merchant gagal diperbaharui.");
            }

            DB::commit();
            $this->output->responseCode = "00";
            $this->output->responseDesc = "SUCCESS RETRY STATUS";
            return response()->json($this->output);
        } catch (\Throwable $e) {
            DB::rollback();
            $error_msg = $e->getMessage();
            throw new DataNotFoundException($error_msg);
        }
    }

    public function interfaceProcess(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'tindak_lanjut' => 'required',
            'data' => 'required',
            'data.*.id_qc' => ['required'],
            // 'data.*.app_id' => [''],
            'data.*.app_jenis' => ['required'],
            'data.*.mid' => ['required'],
        ]);

        if ($validator->fails()) {
            $error_message = $validator->errors()->first();
            throw new ParameterException($error_message);
        }

        $req_iface = $request->all();



        DB::beginTransaction();
        try {
            $mid_mdr_onus_retry = array();

            foreach ($req_iface['data'] as $key => $iface_data) {
                $response_error = array(
                    'id_qc' => $iface_data['id_qc'],
                    'error' => array()
                );

                $res_detail_qc = $this->qcRepo->get_qc_detail($iface_data);
                if ($res_detail_qc->isEmpty()) {
                    Log::channel('daily')->error('Data Interface tidak ditemukan | id_qc : ' . $iface_data['id_qc']);
                    $response_error['error'][] = array('error_message' => 'Data Interface tidak ditemukan');
                    continue;
                }

                $data_ubah = array();
                $tmp_ubah     = (array) json_decode($res_detail_qc[0]->data_ubah);
                if (is_array($tmp_ubah) && count($tmp_ubah) > 0) {
                    $data_ubah = $tmp_ubah;
                }

                dd($data_ubah);

                //GETTING ORIGINAL DATA BEFORE QC
                $merchant_ori = $this->qcRepo->select_data('app_merchant', array('app_id' => $iface_data['app_id']));
                if (empty($merchant_ori)) {
                    Log::channel('daily')->error('Original data merchant tidak ditemukan | app_id : ' . $iface_data['app_id'] . '| id_qc : ' . $iface_data['id_qc']);
                    $response_error['error'][] = array('error_message' => 'Original data merchant tidak ditemukan');
                }

                //GET ORIGINAL MDR
                $result_mdr = null;
                $app_mdr = $this->qcRepo->select_data('app_merchant_mdr', array('app_id' => $iface_data['app_id'], 'mid' => $iface_data['mid']), '*');
                if ($iface_data['app_id'] != '') {
                    if (empty($app_mdr)) {
                        $app_mdr = $this->qcRepo->select_data('app_merchant_mdr', array('mid' => $iface_data['mid']), '*');
                        if (empty($app_mdr)) {
                            $app_merchant = $this->qcRepo->select_data('merchant_data', array('mid' => $iface_data['mid']));
                            if (!empty($app_merchant)) {
                                $merchant_row = $app_merchant[0];
                                $result_mdr['mdr_onus'] = $merchant_row->mdr_onus;
                                $result_mdr['mdr_offus'] = $merchant_row->mdr_offus;
                                $result_mdr['mdr_debit'] = $merchant_row->mdr_debit;
                                $result_mdr['mdr_debit_pl'] = $merchant_row->mdr_debit_pl;
                                $result_mdr['mdr_npg'] = $merchant_row->mdr_debit_npg;
                                $result_mdr['mdr_unik'] = $merchant_row->mdr_unik;
                                if ($merchant_row->tipe_merchant == '99') {
                                    $mdr_cicilan = $this->qcRepo->select_data('merchant_data_mdr_cicilan', array('mid' => $iface_data['mid']));
                                    if (!empty($mdr_cicilan)) {
                                        foreach ($mdr_cicilan as $mdrcicilan_row) {
                                            $result_mdr['mdr_cicilan'][] = array(
                                                'plan' => $mdrcicilan_row->plan,
                                                'term' => $mdrcicilan_row->term,
                                                'mdr' => $mdrcicilan_row->mdr
                                            );
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (!empty($app_mdr)) {
                        foreach ($app_mdr as $app_mdr_row) {
                            $keys = array(
                                '0' => 'mdr_offus',
                                '1' => ($app_mdr_row->plan == '0') ? 'mdr_onus' : 'mdr_cicilan',
                                '2' => 'mdr_debit',
                                '3' => 'mdr_debit_pl',
                                '4' => 'mdr_npg',
                                '5' => 'mdr_unik'
                            );

                            $result_key = $keys[$app_mdr_row->on_off];
                            if ($result_key == 'mdr_cicilan') {
                                $result_mdr[$result_key][] = array(
                                    'plan' => $app_mdr_row->plan,
                                    'term' => $app_mdr_row->term,
                                    'mdr' => $app_mdr_row->mdr
                                );
                            } else {
                                $result_mdr[$result_key] = $app_mdr_row->mdr;
                            }
                        }
                    }
                } else {
                    $app_merchant = $this->qcRepo->select_data('merchant_data', array('mid' => $iface_data['mid']));
                    if (!empty($app_merchant)) {
                        $merchant_row = $app_merchant[0];
                        $result_mdr['mdr_onus'] = $merchant_row->mdr_onus;
                        $result_mdr['mdr_offus'] = $merchant_row->mdr_offus;
                        $result_mdr['mdr_debit'] = $merchant_row->mdr_debit;
                        $result_mdr['mdr_debit_pl'] = $merchant_row->mdr_debit_pl;
                        $result_mdr['mdr_npg'] = $merchant_row->mdr_debit_npg;
                        $result_mdr['mdr_unik'] = $merchant_row->mdr_unik;
                        if ($merchant_row->tipe_merchant == '99') {
                            $mdr_cicilan = $this->qcRepo->select_data('merchant_data_mdr_cicilan', array('mid' => $iface_data['mid']));
                            if (!empty($mdr_cicilan)) {
                                foreach ($mdr_cicilan as $mdrcicilan_row) {
                                    $result_mdr['mdr_cicilan'][] = array(
                                        'plan' => $mdrcicilan_row->plan,
                                        'term' => $mdrcicilan_row->term,
                                        'mdr' => $mdrcicilan_row->mdr
                                    );
                                }
                            }
                        }
                    }
                }

                if ($result_mdr == null) {
                    Log::channel('daily')->error('MDR Original tidak ditemukan | id_qc : ' . $iface_data['id_qc']);
                    $response_error['error'][] = array('error_message' => 'MDR Original tidak ditemukan');
                }


                if ($req_iface['tindak_lanjut'] == 'retry') {
                    if ($iface_data['is_mdr_onus'] == -1 && !in_array($iface_data['mid'], $mid_mdr_onus_retry)) {
                        $res_update = $this->interface_mdr($iface_data['mid'], 'ON', $data_ubah['mdr_onus'][])
                    }
                }
            }
        } catch (\Throwable $e) {
            DB::rollback();
            $error_msg = $e->getMessage();
            throw new DataNotFoundException($error_msg);
        }
    }

    public function interface_mdr($mid = '001000000000', $type = 'ON', $mdr = '00,00')
    {
        if ($type == 'ON') {
            $MDR_ON_OFF = 'ON';
            $mdr_id = '0';
            $MDR_TYPE = 'EDC';
        } elseif ($type == 'OFF') {
            // $MDR_ON_OFF = 'OFF';
            $MDR_ON_OFF = 'OF';
            $mdr_id = '1';
            $MDR_TYPE = 'EDC';
        } elseif ($type == 'NPG') {
            // $MDR_ON_OFF = 'OFF';
            $MDR_ON_OFF = 'OF';
            $mdr_id = '3';
            $MDR_TYPE = 'NPG';
        }

        $mdr_app_id                        = substr($mid, 3) . '000' . '00' . $mdr_id;
        $data_csap['MDR_MID']            = substr($mid, 3);
        $data_csap['MDR_INSTALLMENT']    = '0';
        $data_csap['MDR_ON_OFF']        = $MDR_ON_OFF;
        $data_csap['MDR_TYPE']             = $MDR_TYPE;
        $data_csap['MDR_PLAN']            = '';
        $data_csap['MDR_TERM']            = '';
        $data_csap['MDR_RATE']            = floatval(str_replace(',', '.', $mdr));
        $data_csap['MDR_DATE_MODIFIED']    = date('Y-m-d H:i:s');
        $data_csap['MDR_MODIFIED_BY']    = 'MMS';
        $res_update = $this->qcRepo->interface_mdr($data_csap, $mdr_app_id);

        dd($res_update);
    }
}