<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Validator;
use Hidehalo\Nanoid\Client as Nanoid;
use GuzzleHttp\Client as GuzzleClient;
use App\Responses;
use App\Helper;
use App\Models\Users;
use App\Models\Banks;
use App\Models\Drivers;
use App\Models\DriversDetail;
use App\Models\Vehicles;
use App\Models\VehiclesDetail;
use App\Models\Devices;
use App\Models\Orders;
use App\Models\OrdersPickups;
use App\Models\OrdersDrops;
use App\Models\OrdersClients;
use App\Models\OrdersRates;
use App\Models\OrdersVendors;
use App\Models\OrdersDrivers;
use App\Models\OrdersVehicles;
use App\Models\OrdersInsurances;
use App\Models\OrdersTermins;
use App\Models\OrdersAItems;
use App\Models\UnitTypes;
use App\Models\Zone;
use App\Models\ConfRates;
use App\Models\ConfTruckTypes;
use App\Models\Clients;
use App\Models\Insurances;
use App\Models\StaticInsurances;
use App\Models\OrdersPckDrop;
use App\Models\PocketMoney;
use App\Models\Checkpoints;
use App\Models\OrdersPockets;
use App\Models\OrdersCheckpoints;

class TransactionSpcController extends Controller
{
    public function view_transactions_spc_add()
    {
        $vendors = DB::table("t_users")
            ->where("id", Auth::user()->id)
            ->get();

        $vehicles = DB::table("t_vehicles as tv")
            ->leftJoin("t_users as tu", "tu.id", "tv.vendor_id")
            ->where("tu.id", Auth::user()->id)
            ->where("tv.status", 1)
            ->whereNull("tv.dlt")
            ->select("tv.*")
            ->get();

        $drivers = DB::table("t_drivers as td")
            ->leftJoin("t_users as tu", "tu.id", "td.vendor_id")
            ->where("tu.id", Auth::user()->id)
            ->where("td.status", 1)
            // ->where("td.is_in_ord", 1)
            ->whereNull("td.dlt")
            ->select("td.*")
            ->get();

        $data = [
            "uclients" => Users::listUsers([
                "role" => Users::ROLE_VENDOR,
                "status" => Users::STATUS_ACTIVE,
                "id" => Auth::user()->id,
            ]),
            "truck_types" => ConfTruckTypes::listTruckTypes(
                ConfTruckTypes::IS_ACTIVE,
                ["is_publish" => ConfTruckTypes::IS_PUBLISH]
            ),
            "devices" => Devices::listDevices([
                "is_active" => Devices::IS_ACTIVE,
                "type" => Devices::TYPE_PORTABLE,
                "is_idle_yes" => 1,
                "is_available" => Devices::IS_AVAIL,
            ]),
            "vendors" => $vendors,
            "vehicles" => $vehicles,
            "drivers" => $drivers,
            "banks" => Banks::listBanks(["is_active" => Banks::IS_ACTIVE]),
        ];
        return view("menu_v1._addTransactionsSpcMultiple", $data);
        // return view('menu_v1._addTransactionsSpcSingle', $data);
    }

    /**
     * CASE SEMI AUTOMATIC
     * Vendor
     *      phone belum digunakan, email digunakan ? AMAN
     *      phone digunakan, email belum digunakan ? AMAN
     *      phone digunakan, emaill digunakan ? AMAN
     * Driver
     *      driver lock on phone1 ? AMAN
     *      driver in order ? AMAN
     *      driver phone1 used but from current input its different name driver ? AMAN
     *      driver ditemukan tapi beda vendor ?
     * Vehicle
     *      device_id used on vhc and nopol same ?
     *      device_id used on vhc but nopol not same ? AMAN
     *      device_id not used on any vhc and nopol not used ? AMAN
     *      device_id not used on any vhc but nopol used ? AMAN
     *      vehilce ditemukan tapi beda vendor ?
     * Rates
     *      rates yang sama ? AMAN
     * Other
     *      kir_exp / tax_exp not input on DB when new vhc AMAN
     *      show suggestion beluman
     */

    //	multiple
    public function api_trx_spc_checkout_v1(Request $req)
    {
        try {
            $now = time();

            $input = [
                "uid" => $req->uid,
                "points" => $req->points,
                "truck_type_id" => $req->truck_type_id,
                "truck_type_name" => $req->truck_type_name,
                "is_insurance" => $req->is_insurance,
                "is_client_pkp" => $req->is_client_pkp,
                "amt_beneficiary" => $req->amt_beneficiary,
                "vdr_name" => $req->vdr_name,
                "vdr_phone" => $req->vdr_phone,
                "vdr_email" => $req->vdr_email,
                "vdr_addr" => $req->vdr_addr,
                "vdr_bank_id" => $req->vdr_bank_id,
                "vdr_bank_code" => $req->vdr_bank_code,
                "vdr_bank_short" => $req->vdr_bank_short,
                "vdr_bank_name" => $req->vdr_bank_name,
                "vdr_kcp" => $req->vdr_bank_branch_name,
                "vdr_bank_acc_number" => $req->vdr_bank_acc_number,
                "vdr_bank_acc_name" => $req->vdr_bank_acc_name,
                "is_vdr_bcng" => $req->is_vdr_bcng,
                "device_id" => $req->device_id,
                "vhc_nopol" => $req->vhc_nopol,
                "vhc_stnk_taxexp" => $req->vhc_stnk_taxexp,
                "vhc_kir_exp" => $req->vhc_kir_exp,
                "drv_name" => $req->drv_name,
                "drv_phone" => $req->drv_phone,
                "drv_phone2" => $req->drv_phone2,
                "drv_bank_id" => $req->drv_bank_id,
                "drv_bank_code" => $req->drv_bank_code,
                "drv_bank_name" => $req->drv_bank_name,
                "drv_kcp" => $req->drv_bank_branch_name,
                "drv_bank_acc_number" => $req->drv_bank_acc_number,
                "drv_bank_acc_name" => $req->drv_bank_acc_name,
                "sell_price" => $req->sell_price,
                "buy_price" => $req->buy_price,
                "buy_price_tax_type" => $req->buy_price_tax_type,
                "buy_price_tax_ppn_percent" => $req->buy_price_tax_ppn_percent,
                "buy_price_tax_ppn_flat" => $req->buy_price_tax_ppn_flat,
                "buy_price_tax_pph_percent" => $req->buy_price_tax_pph_percent,
                "buy_price_tax_pph_flat" => $req->buy_price_tax_pph_flat,
                "buy_price_total_tax" => $req->buy_price_total_tax,
                "margin_price" => $req->margin_price,
                "percent_price" => $req->percent_price,
                "lead_time" => $req->lead_time,
                "termin1_amt_type" => $req->termin1_amt_type,
                "termin1_amt" => $req->termin1_amt,
                "termin1_calc_percent" => $req->termin1_calc_percent,
                "termin1_date" => $req->termin1_date,
                "termin1_time" => $req->termin1_time,
                "termin1_at" => $req->termin1_at,
                "termin2_amt_type" => $req->termin2_amt_type,
                "termin2_amt" => $req->termin2_amt,
                "termin2_calc_percent" => $req->termin2_calc_percent,
                "sell_termin1_amt_type" => $req->sell_termin1_amt_type,
                "sell_termin1_amt" => $req->sell_termin1_amt,
                "sell_termin1_calc_percent" => $req->sell_termin1_calc_percent,
                "sell_termin1_date" => $req->sell_termin1_date,
                "sell_termin1_time" => $req->sell_termin1_time,
                "sell_termin1_at" => $req->sell_termin1_at,
                "sell_termin2_amt_type" => $req->sell_termin2_amt_type,
                "sell_termin2_amt" => $req->sell_termin2_amt,
                "sell_termin2_calc_percent" => $req->sell_termin2_calc_percent,
                "pocket_id" => $req->pocket_id,
                "pocket_type" => $req->pocket_type,
                "pocket_checkpoints" => $req->pocket_checkpoints,
            ];
            $rulesInput = [
                "uid" => "required|integer|not_in:0",
                "points" => "required|array|min:1",
                "points.*.pickup_at" => "required|integer",
                "points.*.pickup_zone_id" => "required|integer",
                "points.*.pickup_zone_pic_name" => "required|string",
                "points.*.pickup_zone_pic_phone" => "required|numeric",
                "points.*.drop_zone_id" => "required|integer",
                "points.*.drop_zone_pic_name" => "required|string",
                "points.*.drop_zone_pic_phone" => "required|numeric",
                "truck_type_id" => "required|integer|not_in:0",
                "truck_type_name" => "required|string",
                "is_insurance" => "nullable|string",
                "is_client_pkp" => "nullable|numeric",
                "amt_beneficiary" => "nullable|numeric",
                "vdr_name" => "required|string",
                "vdr_phone" => "required|numeric",
                "vdr_email" => "required|email",
                "vdr_addr" => "required|string|min:35",
                "vdr_bank_id" => "required|integer|not_in:0",
                "vdr_bank_code" => "required|numeric",
                "vdr_bank_short" => "required|string",
                "vdr_bank_name" => "required|string",
                "vdr_kcp" => "required|string",
                "vdr_bank_acc_number" => "required|numeric",
                "vdr_bank_acc_name" => "required|string|max:255",
                "is_vdr_bcng" => "nullable|numeric",
                "device_id" => "nullable|numeric",
                "vhc_nopol" => "required|string",
                "vhc_stnk_taxexp" => "required|date_format:Y-m-d",
                "vhc_kir_exp" => "required|date_format:Y-m-d",
                "drv_name" => "required|string",
                "drv_phone" => "required|numeric",
                "drv_phone2" => "nullable|numeric",
                "drv_bank_id" => "nullable|numeric",
                "drv_bank_code" => "nullable|string",
                "drv_bank_name" => "nullable|string",
                "drv_kcp" => "nullable|string",
                "drv_bank_short_name" => "nullable|string",
                "drv_bank_acc_number" => "nullable|string",
                "drv_bank_acc_name" => "nullable|string",
                "sell_price" => "required|numeric",
                "buy_price" => "required|numeric",
                "buy_price_tax_type" => "required|numeric",
                "buy_price_tax_ppn_percent" => "required|numeric",
                "buy_price_tax_ppn_flat" => "required|numeric",
                "buy_price_tax_pph_percent" => "required|numeric",
                "buy_price_tax_pph_flat" => "required|numeric",
                "buy_price_total_tax" => "required|numeric",
                "margin_price" => "required|numeric",
                "lead_time" => "required|integer|not_in:0",
                "termin1_amt_type" => "nullable|numeric",
                "termin1_amt" => "nullable|numeric",
                "termin1_calc_percent" => "nullable|numeric",
                "termin1_date" => "nullable|string",
                "termin1_time" => "nullable|string",
                "termin1_at" => "nullable|numeric",
                "termin2_amt_type" => "nullable|numeric",
                "termin2_amt" => "nullable|numeric",
                "termin2_calc_percent" => "nullable|numeric",
                "sell_termin1_amt_type" => "nullable|numeric",
                "sell_termin1_amt" => "nullable|numeric",
                "sell_termin1_calc_percent" => "nullable|numeric",
                "sell_termin1_date" => "nullable|string",
                "sell_termin1_time" => "nullable|string",
                "sell_termin1_at" => "nullable|numeric",
                "sell_termin2_amt_type" => "nullable|numeric",
                "sell_termin2_amt" => "nullable|numeric",
                "sell_termin2_calc_percent" => "nullable|numeric",
                "pocket_id" => "nullable|integer",
                "pocket_type" => "nullable|numeric",
                "pocket_checkpoints" => "nullable|array",
            ];
            // $req->margin_price = 0;

            // validasi input
            $isValidInput = Validator::make($input, $rulesInput);
            if (!$isValidInput->passes()) {
                $apiResp = Responses::bad_input(
                    $isValidInput->messages()->first()
                );
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            $nopol = explode(" ", strtoupper($req->vhc_nopol));
            if (count($nopol) < 3) {
                $apiResp = Responses::bad_input(
                    "Nomor polisi kendaraan tidak valid"
                );
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }
            $device_id = str_pad(
                $req->device_id,
                Vehicles::MAX_DEVICE_ID,
                "0",
                STR_PAD_LEFT
            );

            if ($req->drv_name) {
                if (!$req->drv_phone) {
                    $apiResp = Responses::bad_input(
                        "No Telepon driver ke-1 belum diisi"
                    );
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
            }

            if ($req->drv_phone2) {
                if (!$req->drv_name) {
                    $apiResp = Responses::bad_input(
                        "Nama driver ke-2 belum diisi"
                    );
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
            }

            $existVdrId = 0;
            $vdr = null;
            $uniqPhone = Users::getUserByPhone($req->vdr_phone);
            if (count($uniqPhone) > 0) {
                $existVdrId = $uniqPhone[0]->id;
                $vdr = $uniqPhone[0];
                $uniqMail = Users::getUserByEmail($req->vdr_email);
                if (count($uniqMail) > 0) {
                    if ($uniqMail[0]->id !== $uniqPhone[0]->id) {
                        // email vendor tidak sesuai dengan akun yang terdata pada nomor telepon vendor
                        $apiResp = Responses::bad_request(
                            "email vendor telah digunakan"
                        );
                        return new Response($apiResp, $apiResp["meta"]["code"]);
                    }
                }
            }
            if ($existVdrId === 0) {
                $uniqMail = Users::getUserByEmail($req->vdr_email);
                if (count($uniqMail) > 0) {
                    $existVdrId = $uniqMail[0]->id;
                    $vdr = $uniqMail[0];
                }
            }

            $existDrvId = 0;
            $drv = null;
            $uniqPhone = Drivers::getDriverByPhone($req->drv_phone);
            if (count($uniqPhone) > 0) {
                if (
                    strpos(
                        strtolower($uniqPhone[0]->fullname),
                        strtolower($req->drv_name)
                    ) === false
                ) {
                    $apiResp = Responses::bad_request(
                        "no telepon driver sudah digunakan oleh driver " .
                            $uniqPhone[0]->fullname
                    );
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
                // if ($uniqPhone[0]->is_in_ord === Drivers::IN_ORD_YES) {
                //     $apiResp = Responses::bad_request('driver ' . $uniqPhone[0]->fullname . ' sedang berada dalam order lain');
                //     return (new Response($apiResp, $apiResp['meta']['code']));
                // }
                $existDrvId = $uniqPhone[0]->id;
                $drv = $uniqPhone[0];
            }

            $existVhcId = 0;
            $vhc = null;
            if (
                $device_id !==
                str_pad(0, Vehicles::MAX_DEVICE_ID, "0", STR_PAD_LEFT)
            ) {
                $uniqVhcByDevice = Vehicles::getVehicleByDeviceId($device_id);
            } else {
                $uniqVhcByDevice = [];
            }
            if (count($uniqVhcByDevice) > 0) {
                $uniqPlatNo = Vehicles::getVehicleByPlatNo(
                    $nopol[0],
                    $nopol[1],
                    $nopol[2]
                );
                if (count($uniqPlatNo) > 0) {
                    if ($uniqVhcByDevice[0]->id !== $uniqPlatNo[0]->id) {
                        $apiResp = Responses::bad_request(
                            "plat number has been used"
                        );
                        return new Response($apiResp, $apiResp["meta"]["code"]);
                    }
                    // if ($uniqPlatNo[0]->is_in_ord === Vehicles::IN_ORD_YES) {
                    // 	$apiResp = Responses::bad_request('kendaraan ' . $uniqPlatNo[0]->nopol1 . ' ' . $uniqPlatNo[0]->nopol2 . ' ' . $uniqPlatNo[0]->nopol3 . ' sedang berada dalam order lain');
                    // 	return (new Response($apiResp, $apiResp['meta']['code']));
                    // }
                }
                // if ($uniqVhcByDevice[0]->is_in_ord === Vehicles::IN_ORD_YES) {
                // 	$apiResp = Responses::bad_request('kendaraan ' . $uniqVhcByDevice[0]->nopol1 . ' ' . $uniqVhcByDevice[0]->nopol2 . ' ' . $uniqVhcByDevice[0]->nopol3 . ' sedang berada dalam order lain');
                // 	return (new Response($apiResp, $apiResp['meta']['code']));
                // }
                $existVhcId = $uniqVhcByDevice[0]->id;
                $vhc = $uniqVhcByDevice[0];
            }
            if ($existVhcId === 0) {
                $uniqPlatNo = Vehicles::getVehicleByPlatNo(
                    $nopol[0],
                    $nopol[1],
                    $nopol[2]
                );
                if (count($uniqPlatNo) > 0) {
                    // if ($uniqPlatNo[0]->is_in_ord === Vehicles::IN_ORD_YES) {
                    // 	$apiResp = Responses::bad_request('kendaraan ' . $uniqPlatNo[0]->nopol1 . ' ' . $uniqPlatNo[0]->nopol2 . ' ' . $uniqPlatNo[0]->nopol3 . ' sedang berada dalam order lain');
                    // 	return (new Response($apiResp, $apiResp['meta']['code']));
                    // }
                    $existVhcId = $uniqPlatNo[0]->id;
                    $vhc = $uniqPlatNo[0];
                }
            }

            if ($existDrvId !== 0 && $existVdrId !== $drv->vendor_id) {
                $uVendor = Users::getUserById($drv->vendor_id)[0];
                $apiResp = Responses::bad_request(
                    "data driver sudah termasuk dalam vendor: " .
                        $uVendor->first_name
                );
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            if ($existVhcId !== 0 && $existVdrId !== $vhc->vendor_id) {
                $uVendor = Users::getUserById($vhc->vendor_id)[0];
                $apiResp = Responses::bad_request(
                    "data kendaraan sudah termasuk dalam vendor: " .
                        $uVendor->first_name
                );
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            $pckZids = [];
            $dropZids = [];
            foreach ($req->points as $i => $point) {
                $pckZids[] = $point["pickup_zone_id"];
                $dropZids[] = $point["drop_zone_id"];
            }

            $pcks = Zone::getZoneByIds($pckZids);
            if (count($pcks) < 1) {
                $apiResp = Responses::bad_request(
                    "Lokasi penjemputan tidak ditemukan"
                );
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }
            foreach ($pcks as $i => $pck) {
                if (
                    $pck->prid == 0 ||
                    $pck->ktid == 0 ||
                    $pck->kcid == 0 ||
                    $pck->klid == 0
                ) {
                    $apiResp = Responses::bad_request(
                        "Zonasi wilayah(provinsi, kecamatan, ...) lokasi penjemputan " .
                            $pck->name .
                            " belum lengkap"
                    );
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
            }

            $drops = Zone::getZoneByIds($dropZids);
            if (count($drops) < 1) {
                $apiResp = Responses::bad_request("Lokasi pengantaran");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }
            foreach ($drops as $i => $drop) {
                if (
                    $drop->prid == 0 ||
                    $drop->ktid == 0 ||
                    $drop->kcid == 0 ||
                    $drop->klid == 0
                ) {
                    $apiResp = Responses::bad_request(
                        "Zonasi wilayah(provinsi, kecamatan, ...) lokasi pengantaran " .
                            $drop->name .
                            " belum lengkap"
                    );
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
            }

            if ($req->is_vdr_bcng == Users::IS_VDR_BCNG_YES) {
                // $req->pocket_id
                // $req->pocket_type
                // $req->pocket_checkpoints
                $pocket = PocketMoney::showPocketById($req->pocket_id);
                if (count($pocket) < 1) {
                    $apiResp = Responses::not_found("uang saku belum dipilih");
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
                $pocket[0]->checkpoints = Checkpoints::listCheckpoints([
                    "pocket_id" => $pocket[0]->id,
                ]);
            }

            $client = Clients::getClientById($req->auth->client_group_id);
            $insurance = StaticInsurances::listStaticInsurances([
                "is_active" => StaticInsurances::IS_ACTIVE,
            ]);

            $opts = [];
            $opt = [
                "is_best" => 1,
            ];
            $opt["lead_time_id"] = 0;
            // $center_time = $v->long_time - $v->fast_time;
            $opt["lead_time"] = $req->lead_time; // long_time
            $price = $req->sell_price ?? 0;
            $opt["price"] = $price;
            $opt["real_price"] = $price;
            $opt["disc_price"] = 0;
            $opt["disc_type"] = $client[0]->disc_type;
            $opt["disc_percent"] = 0;
            if ($client[0]->disc_type === Clients::DISC_TYPE_FIX) {
                $opt["disc_price"] = $client[0]->disc_amount;
                $opt["price"] = $opt["price"] - $opt["disc_price"];
            } elseif ($client[0]->disc_type === Clients::DISC_TYPE_PERCENT) {
                $opt["disc_percent"] = $client[0]->disc_amount;
                $opt["disc_price"] =
                    ($opt["price"] * $client[0]->disc_amount) / 100;
                $opt["price"] = $opt["price"] - $opt["disc_price"];
            }
            array_push($opts, $opt);

            $apiResp = Responses::success("checkout success");
            $apiResp["data"] = $opts;

            if ($req->is_insurance === "true") {
                // $insurances = Insurances::getInsurancesByRangeBeneficiaryAndActive($req->amt_beneficiary);
                // if (count($insurances) < 1) {
                // 	$apiResp = Responses::bad_request('Total pertangguhan tidak tersedia');
                // 	return new Response($apiResp, $apiResp['meta']['code']);
                // }
                // $apiResp['insurance'] = $insurances[0];
                $beneficiary = $req->amt_beneficiary ?? 0; // nilai pertangguhan
                $calcPercent =
                    ($beneficiary * $insurance[0]->amt_percent) / 100;
                $flatPercent = $beneficiary - $calcPercent;
                $apiResp["insurance"] = [
                    "premi_price" => $calcPercent,
                ];
            }

            $apiResp["exist_data"] = [
                "vdr_id" => $existVdrId,
                "drv_id" => $existDrvId,
                "vhc_id" => $existVhcId,
            ];

            return new Response($apiResp, $apiResp["meta"]["code"]);
        } catch (\Exception $e) {
            $apiResp = Responses::error($e->getMessage());
            return new Response($apiResp, $apiResp["meta"]["code"]);
        }
    }

    //	multiple
    /**
     * DONE jangan lupa insert t_pocket, t_checkpoint
     * DONE tambahan field t_vendors => is_vdr_bcng
     * DONE tambahin field t_zones => boundary_diameter, boundary_area, boundary_ha
     * tambahin field t_drivers => bank driver
     */
    public function api_trx_spc_create_order_v1(Request $req)
    {
        try {
            $now = time();

            $input = [
                "uid" => $req->uid,
                "points" => $req->points,
                // 'pickup_at' => $req->pickup_at,
                // 'pickup_zone_id' => $req->pickup_zone_id,
                // 'pickup_zone_pic_name' => $req->pickup_zone_pic_name,
                // 'pickup_zone_pic_phone' => $req->pickup_zone_pic_phone,
                // 'drop_zone_id' => $req->drop_zone_id,
                // 'drop_zone_pic_name' => $req->drop_zone_pic_name,
                // 'drop_zone_pic_phone' => $req->drop_zone_pic_phone,
                "truck_type_id" => $req->truck_type_id,
                "truck_type_name" => $req->truck_type_name,
                "is_insurance" => $req->is_insurance,
                "is_client_pkp" => $req->is_client_pkp,
                "amt_beneficiary" => $req->amt_beneficiary,
                "vdr_id" => $req->vdr_id,
                "vdr_name" => $req->vdr_name,
                "vdr_phone" => $req->vdr_phone,
                "vdr_email" => $req->vdr_email,
                "vdr_addr" => $req->vdr_addr,
                "vdr_bank_id" => $req->vdr_bank_id,
                "vdr_bank_code" => $req->vdr_bank_code,
                "vdr_bank_short" => $req->vdr_bank_short,
                "vdr_bank_name" => $req->vdr_bank_name,
                "vdr_kcp" => $req->vdr_bank_branch_name,
                "vdr_bank_acc_number" => $req->vdr_bank_acc_number,
                "vdr_bank_acc_name" => $req->vdr_bank_acc_name,
                "is_vdr_bcng" => $req->is_vdr_bcng,
                "device_id" => $req->device_id,
                "vhc_id" => $req->vhc_id,
                "vhc_nopol" => $req->vhc_nopol,
                "vhc_stnk_taxexp" => $req->vhc_stnk_taxexp,
                "vhc_kir_exp" => $req->vhc_kir_exp,
                "drv_id" => $req->drv_id,
                "drv_name" => $req->drv_name,
                "drv_phone" => $req->drv_phone,
                "drv_phone2" => $req->drv_phone2,
                "drv_bank_id" => $req->drv_bank_id,
                "drv_bank_code" => $req->drv_bank_code,
                "drv_bank_name" => $req->drv_bank_name,
                "drv_kcp" => $req->drv_bank_branch_name,
                "drv_bank_acc_number" => $req->drv_bank_acc_number,
                "drv_bank_acc_name" => $req->drv_bank_acc_name,
                "sell_price" => $req->sell_price,
                "buy_price" => $req->buy_price,
                "buy_price_tax_type" => $req->buy_price_tax_type,
                "buy_price_tax_ppn_percent" => $req->buy_price_tax_ppn_percent,
                "buy_price_tax_ppn_flat" => $req->buy_price_tax_ppn_flat,
                "buy_price_tax_pph_percent" => $req->buy_price_tax_pph_percent,
                "buy_price_tax_pph_flat" => $req->buy_price_tax_pph_flat,
                "buy_price_total_tax" => $req->buy_price_total_tax,
                "margin_price" => $req->margin_price,
                "percent_price" => $req->percent_price,
                "lead_time" => $req->lead_time,
                "termin1_amt_type" => $req->termin1_amt_type,
                "termin1_amt" => $req->termin1_amt,
                "termin1_calc_percent" => $req->termin1_calc_percent,
                "termin1_date" => $req->termin1_date,
                "termin1_time" => $req->termin1_time,
                "termin1_at" => $req->termin1_at,
                "termin2_amt_type" => $req->termin2_amt_type,
                "termin2_amt" => $req->termin2_amt,
                "termin2_calc_percent" => $req->termin2_calc_percent,
                "sell_termin1_amt_type" => $req->sell_termin1_amt_type,
                "sell_termin1_amt" => $req->sell_termin1_amt,
                "sell_termin1_calc_percent" => $req->sell_termin1_calc_percent,
                "sell_termin1_date" => $req->sell_termin1_date,
                "sell_termin1_time" => $req->sell_termin1_time,
                "sell_termin1_at" => $req->sell_termin1_at,
                "sell_termin2_amt_type" => $req->sell_termin2_amt_type,
                "sell_termin2_amt" => $req->sell_termin2_amt,
                "sell_termin2_calc_percent" => $req->sell_termin2_calc_percent,
                "pocket_id" => $req->pocket_id,
                "pocket_type" => $req->pocket_type,
                "pocket_checkpoints" => $req->pocket_checkpoints,
            ];
            $rulesInput = [
                "uid" => "required|integer|not_in:0",
                "points" => "required|array|min:1",
                "points.*.pickup_at" => "required|integer",
                "points.*.pickup_zone_id" => "required|integer",
                "points.*.pickup_zone_pic_name" => "required|string",
                "points.*.pickup_zone_pic_phone" => "required|numeric",
                "points.*.drop_zone_id" => "required|integer",
                "points.*.drop_zone_pic_name" => "required|string",
                "points.*.drop_zone_pic_phone" => "required|numeric",
                "truck_type_id" => "required|integer|not_in:0",
                "truck_type_name" => "required|string",
                "is_insurance" => "nullable|string",
                "is_client_pkp" => "nullable|numeric",
                "amt_beneficiary" => "nullable|numeric",
                "vdr_id" => "required|numeric",
                "vdr_name" => "required|string",
                "vdr_phone" => "required|numeric",
                "vdr_email" => "required|email",
                "vdr_addr" => "required|string|min:35",
                "vdr_bank_id" => "required|integer|not_in:0",
                "vdr_bank_code" => "required|numeric",
                "vdr_bank_short" => "required|string",
                "vdr_bank_name" => "required|string",
                "vdr_kcp" => "required|string",
                "vdr_bank_acc_number" => "required|numeric",
                "vdr_bank_acc_name" => "required|string|max:255",
                "is_vdr_bcng" => "nullable|numeric",
                "device_id" => "nullable|numeric",
                "vhc_id" => "required|numeric",
                "vhc_nopol" => "required|string",
                "vhc_stnk_taxexp" => "required|date_format:Y-m-d",
                "vhc_kir_exp" => "required|date_format:Y-m-d",
                "drv_id" => "required|numeric",
                "drv_name" => "required|string",
                "drv_phone" => "required|numeric",
                "drv_phone2" => "nullable|numeric",
                "drv_bank_id" => "nullable|numeric",
                "drv_bank_code" => "nullable|string",
                "drv_bank_name" => "nullable|string",
                "drv_kcp" => "nullable|string",
                "drv_bank_short_name" => "nullable|string",
                "drv_bank_acc_number" => "nullable|string",
                "drv_bank_acc_name" => "nullable|string",
                "sell_price" => "required|numeric",
                "buy_price" => "required|numeric",
                "buy_price_tax_type" => "required|numeric",
                "buy_price_tax_ppn_percent" => "required|numeric",
                "buy_price_tax_ppn_flat" => "required|numeric",
                "buy_price_tax_pph_percent" => "required|numeric",
                "buy_price_tax_pph_flat" => "required|numeric",
                "buy_price_total_tax" => "required|numeric",
                "margin_price" => "required|numeric",
                // 'margin_price' => 'required',
                // 'percent_price' => 'required|numeric',
                "lead_time" => "required|integer|not_in:0",
                "termin1_amt_type" => "nullable|numeric",
                "termin1_amt" => "nullable|numeric",
                "termin1_calc_percent" => "nullable|numeric",
                "termin1_date" => "nullable|string",
                "termin1_time" => "nullable|string",
                "termin1_at" => "nullable|numeric",
                "termin2_amt_type" => "nullable|numeric",
                "termin2_amt" => "nullable|numeric",
                "termin2_calc_percent" => "nullable|numeric",
                "sell_termin1_amt_type" => "nullable|numeric",
                "sell_termin1_amt" => "nullable|numeric",
                "sell_termin1_calc_percent" => "nullable|numeric",
                "sell_termin1_date" => "nullable|string",
                "sell_termin1_time" => "nullable|string",
                "sell_termin1_at" => "nullable|numeric",
                "sell_termin2_amt_type" => "nullable|numeric",
                "sell_termin2_amt" => "nullable|numeric",
                "sell_termin2_calc_percent" => "nullable|numeric",
                "pocket_id" => "nullable|integer",
                "pocket_type" => "nullable|numeric",
                "pocket_checkpoints" => "nullable|array",
            ];
            // $req->margin_price = 0;

            // validasi input
            $isValidInput = Validator::make($input, $rulesInput);
            if (!$isValidInput->passes()) {
                $apiResp = Responses::bad_input(
                    $isValidInput->messages()->first()
                );
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            $clientAuth = Users::getUserById($req->uid)[0];
            $clientAuth->uid = $clientAuth->id;

            $adm_id = $req->auth->uid;
            $crt_type_order = Orders::CRT_TYPE_ORDER_ADMIN_SPECIAL;

            $type_truck_name = $req->truck_type_name;
            if ($req->truck_type_id && $req->truck_type_id != 0) {
                $type_truck_name = $req->truck_type_name;
            } else {
                $type_truck_name = "";
                $req->truck_type_id = 0;
            }

            $vdr_id = (int) $req->vdr_id;
            $vhc_id = (int) $req->vhc_id;
            $drv_id = (int) $req->drv_id;
            $device_id = str_pad(
                $req->device_id,
                Vehicles::MAX_DEVICE_ID,
                "0",
                STR_PAD_LEFT
            );
            $nopol = explode(" ", strtoupper($req->vhc_nopol));
            if (count($nopol) < 3) {
                $apiResp = Responses::bad_input(
                    "Nomor polisi kendaraan tidak valid"
                );
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            $pckZids = [];
            $dropZids = [];
            $pickupAt = [];
            foreach ($req->points as $i => $point) {
                $pckZids[] = $point["pickup_zone_id"];
                $dropZids[] = $point["drop_zone_id"];
                $pickupAt[] = $point["pickup_at"];
            }
            $pcks = Zone::getZoneByIds($pckZids);
            if (count($pcks) < 1) {
                $apiResp = Responses::not_found(
                    "Lokasi penjemputan tidak ditemukan"
                );
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }
            if (empty($pcks[0]->boundary_points)) {
                $apiResp = Responses::bad_request(
                    "Lokasi penjemputan tidak valid"
                );
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }
            $drops = Zone::getZoneByIds($dropZids);
            if (count($drops) < 1) {
                $apiResp = Responses::not_found(
                    "Lokasi pengantaran tidak ditemukan"
                );
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }
            if (empty($drops[0]->boundary_points)) {
                $apiResp = Responses::bad_request(
                    "Lokasi pengantaran tidak valid"
                );
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }
            $pckPoints = [];
            $dropPoints = [];
            foreach ($req->points as $iPoint => $point) {
                foreach ($pcks as $iPck => $pck) {
                    if ($point["pickup_zone_id"] == $pck->id) {
                        if (
                            $pck->prid == 0 ||
                            $pck->ktid == 0 ||
                            $pck->kcid == 0 ||
                            $pck->klid == 0
                        ) {
                            $apiResp = Responses::bad_request(
                                "Zonasi wilayah(provinsi, kecamatan, ...) lokasi penjemputan " .
                                    $pck->name .
                                    " belum lengkap"
                            );
                            return new Response(
                                $apiResp,
                                $apiResp["meta"]["code"]
                            );
                        }
                        $pcks[$iPck]->inpt_set_pck_at =
                            $req->points[$iPoint]["pickup_at"];
                        $pcks[$iPck]->inpt_pic_name =
                            $req->points[$iPoint]["pickup_zone_pic_name"];
                        $pcks[$iPck]->inpt_pic_phone_code = 62;
                        $pcks[$iPck]->inpt_pic_phone_val =
                            (int) $req->points[$iPoint][
                                "pickup_zone_pic_phone"
                            ];
                        $pcks[$iPck]->inpt_pic_mail = null;
                        $pckPoints[$iPoint] = clone $pcks[$iPck];
                    }
                }
                foreach ($drops as $iDrop => $drop) {
                    if ($point["drop_zone_id"] == $drop->id) {
                        if (
                            $drop->prid == 0 ||
                            $drop->ktid == 0 ||
                            $drop->kcid == 0 ||
                            $drop->klid == 0
                        ) {
                            $apiResp = Responses::bad_request(
                                "Zonasi wilayah(provinsi, kecamatan, ...) lokasi pengantaran " .
                                    $drop->name .
                                    " belum lengkap"
                            );
                            return new Response(
                                $apiResp,
                                $apiResp["meta"]["code"]
                            );
                        }
                        $drops[$iDrop]->inpt_pic_name =
                            $req->points[$iPoint]["drop_zone_pic_name"];
                        $drops[$iDrop]->inpt_pic_phone_code = 62;
                        $drops[$iDrop]->inpt_pic_phone_val =
                            (int) $req->points[$iPoint]["drop_zone_pic_phone"];
                        $drops[$iDrop]->inpt_pic_mail = null;
                        $dropPoints[$iPoint] = clone $drops[$iDrop];
                    }
                }
            }
            $lowestPickupAt = min($pickupAt);
            $longestPickupAt = max($pickupAt);

            $nanoid = new Nanoid();

            // $ord_code = $nanoid->formattedId('0123456789', 12);
            // $doWhile = true;
            // do {
            // 	$uniqOrdCode = Orders::getOrderByCode($ord_code);
            // 	if (count($uniqOrdCode) > 0) {
            // 		$ord_code = $nanoid->formattedId('0123456789', 12);
            // 	} else {
            // 		$doWhile = false;
            // 	}
            // } while ($doWhile);
            if (
                ($req->sell_termin2_amt_type == OrdersTermins::AMT_TYPE_FLAT ||
                    $req->sell_termin2_amt_type ==
                        OrdersTermins::AMT_TYPE_PERCENT) &&
                $req->sell_termin2_amt > 0
            ) {
                $ord_code_type = 6;
            } else {
                if ($req->sell_termin1_at < $req->points[0]["pickup_at"]) {
                    $ord_code_type = 5;
                } else {
                    $ord_code_type = 7;
                }
            }
            $ord_code = Helper::gnrtOrdCode($ord_code_type);

            $rate_code = $nanoid->formattedId("123456789", 6);
            $doWhile = true;
            do {
                $uniqRateCode = ConfRates::getRateByCode($rate_code);
                if (count($uniqRateCode) > 0) {
                    $rate_code = $nanoid->formattedId("123456789", 6);
                } else {
                    $doWhile = false;
                }
            } while ($doWhile);

            $client = Clients::getClientById($clientAuth->client_group_id);
            // $rate = ConfRates::getRateById($req->lead_time_id);
            // $pck_pic = Clients::getClientById($pckPoints[0]->client_group_id);
            // $drop_pic = Clients::getClientById($dropPoints[0]->client_group_id);
            $admins = Users::getUsersActiveByRole(Users::ROLE_ADMIN);
            $device = Devices::getDeviceByDeviceId($device_id);
            if (count($device) < 1 || $device === false) {
                $device = [];
                $device[0] = new \StdClass();
                $device[0]->id = 0;
                $device[0]->name = "-";
                $device[0]->type = Devices::TYPE_BUILT_IN;
                $device[0]->simcard_code = 62;
                $device[0]->simcard = 0;
            }
            // $insurance = [];
            // if ($req->is_insurance === 'true') {
            // 	$insurance = Insurances::getInsuranceById($req->insurance_id);
            // 	if (count($insurance) < 1) {
            // 		$apiResp = Responses::bad_request('Insurance not found');
            // 		return new Response($apiResp, $apiResp['meta']['code']);
            // 	}
            // }

            $admins_data = [];
            foreach ($admins as $k => $v) {
                array_push($admins_data, [
                    "admin_id" => $v->id,
                    "admin_name" => $v->first_name,
                    "admin_phone" =>
                        $v->phone_code .
                        " " .
                        implode(" ", str_split($v->phone, 4)),
                    "admin_mail" => $v->email,
                    "admin_addr" => "",
                ]);
            }

            $rate_id = 0;
            if ($req->is_vdr_bcng != Users::IS_VDR_BCNG_YES) {
                $insRate = [
                    "code" => $rate_code,
                    "origin_prov" => $pckPoints[0]->prid,
                    "origin_city" => $pckPoints[0]->ktid,
                    "origin_district" => $pckPoints[0]->kcid,
                    "origin_village" => $pckPoints[0]->klid,
                    "lane" => ConfRates::LANE_EARTH,
                    "dest_prov" => $dropPoints[0]->prid,
                    "dest_city" => $dropPoints[0]->ktid,
                    "dest_district" => $dropPoints[0]->kcid,
                    "dest_village" => $dropPoints[0]->klid,
                    "vdr_id" => $vdr_id,
                    "vhc_type" => $req->truck_type_id,
                    "fast_time" => $req->lead_time,
                    "long_time" => $req->lead_time,
                    "unit_time" => ConfRates::UNIT_DAY,
                    "sell_kg" => 0,
                    "buy_kg" => 0,
                    "margin_kg" => 0,
                    "percent_kg" => 0,
                    "sell_cbm" => 0,
                    "buy_cbm" => 0,
                    "margin_cbm" => 0,
                    "percent_cbm" => 0,
                    "sell_ftl" => $req->sell_price,
                    "buy_ftl" => $req->buy_price,
                    "margin_ftl" => $req->margin_price ?? 0,
                    "percent_ftl" => $req->percent_price ?? 0,
                    "is_active" => ConfRates::IS_ACTIVE,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "crt_type" => ConfRates::CRT_TYPE_SYSTEM,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ];

                $rates = ConfRates::getUniqRate([
                    "origin_prov" => $insRate["origin_prov"],
                    "dest_city" => $insRate["dest_city"],
                    "dest_district" => $insRate["dest_district"],
                    "vhc_type" => $insRate["vhc_type"],
                    "sell_ftl" => $insRate["sell_ftl"],
                    "long_time" => $insRate["long_time"],
                    "origin_prov_dest_ktid_dest_kcid_vhc_type_sell_ftl_long_time" => 1,
                    "is_active" => $insRate["is_active"],
                ]);
                if (count($rates) > 0) {
                    $rate_id = $rates[0]->id;
                }
            }

            /**
             * DONE status_order,
             * DONE vhc_in_ord,
             * DONE drv_in_ord,
             * DONE insert_orders_vendors,
             * DONE insert_orders_vehicles,
             * DONE insert_orders_drivers
             */
            DB::beginTransaction();

            if ($vdr_id === 0) {
                $data = [
                    "first_name" => $req->vdr_name,
                    "last_name" => $req->last_name ?? null,
                    "email" => $req->vdr_email,
                    "phone" => (int) $req->vdr_phone,
                    "phone_code" => Users::DEFAULT_PHONE_CODE,
                    "fulladdress" => $req->vdr_addr,
                    "password" => Hash::make((int) $req->vdr_phone),
                    "role" => Users::ROLE_VENDOR,
                    "client_group_id" => Clients::DEFAULT_CID,
                    "status" => Users::STATUS_ACTIVE,
                    "is_tracking" => Users::IS_TRACK_VHC_DEFAULT,
                    "bank_id" => $req->vdr_bank_id,
                    "bank_code" => $req->vdr_bank_code,
                    "bank_short_name" => $req->vdr_bank_short,
                    "bank_name" => $req->vdr_bank_name,
                    "bank_branch_name" => $req->vdr_bank_branch_name,
                    "bank_acc_number" => $req->vdr_bank_acc_number,
                    "bank_acc_name" => $req->vdr_bank_acc_name,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ];
                $vdr_id = Users::addUser($data);
            } else {
                Users::updateUser($vdr_id, [
                    "first_name" => $req->vdr_name,
                    "email" => $req->vdr_email,
                    "phone" => (int) $req->vdr_phone,
                    "fulladdress" => $req->vdr_addr,
                    "bank_id" => $req->vdr_bank_id,
                    "bank_code" => $req->vdr_bank_code,
                    "bank_short_name" => $req->vdr_bank_short,
                    "bank_name" => $req->vdr_bank_name,
                    "bank_branch_name" => $req->vdr_bank_branch_name,
                    "bank_acc_number" => $req->vdr_bank_acc_number,
                    "bank_acc_name" => $req->vdr_bank_acc_name,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ]);
            }
            $vendor = Users::getUserById($vdr_id);

            if ($req->is_vdr_bcng != Users::IS_VDR_BCNG_YES) {
                if ($rate_id === 0) {
                    $rate_id = ConfRates::addRate($insRate);
                }
            }

            $buy_price = $req->buy_price_total_tax;
            if (
                $req->buy_price_tax_type == OrdersAItems::AMT_TAX_TYPE_INCLUDE
            ) {
                $buy_price = $req->buy_price_base;
            } elseif (
                $req->buy_price_tax_type == OrdersAItems::AMT_TAX_TYPE_EXCLUDE
            ) {
                $buy_price = $req->buy_price_total_tax;
            }
            $insOrd = [
                "code" => $ord_code,
                "type" => Orders::TYPE_FCL,
                "pck_total" => count($pckPoints),
                "drop_total" => count($dropPoints),
                "est_lead_time" => $req->lead_time,
                "lead_time" => $req->lead_time,
                "est_price" => $req->price,
                "price" => $req->price,
                "est_real_price" => $req->real_price,
                "real_price" => $req->real_price,
                "est_disc_price" => $req->disc_price,
                "disc_price" => $req->disc_price,
                "est_buy_price" => $buy_price,
                "buy_price" => $buy_price,
                "est_real_buy_price" => $buy_price,
                "real_buy_price" => $buy_price,
                "est_disc_buy_price" => $req->disc_buy_price ?? 0,
                "disc_buy_price" => $req->disc_buy_price ?? 0,
                "est_rate_id" => $rate_id,
                "rate_id" => $rate_id,
                "status" => Orders::STTS_HAVE_GET_VHC,
                "crt_type_order" => $crt_type_order,
                "crt" => $now,
                "crt_by" => $req->auth->uid,
                "crt_adm_by" => $adm_id,
                "updt" => $now,
                "updt_by" => $req->auth->uid,
                "confirm_at" => $now,
                "confirm_by" => $req->auth->id,
                // 'find_vhc_at' => $now,
                // 'find_vhc_by' => $req->auth->id,
            ];
            $ord_id = Orders::addOrder($insOrd);

            if ($drv_id === 0) {
                $insDriver = [
                    "nik" => 0,
                    "fullname" => $req->drv_name,
                    "fullname2" => $req->drv_name2,
                    "email" => null,
                    "phone" => (int) $req->drv_phone,
                    "phone_code" => Drivers::DEFAULT_PHONE_CODE,
                    "phone2" => $req->drv_phone2 ?? 0,
                    "phone2_code" => Drivers::DEFAULT_PHONE_CODE,
                    "dob" => null,
                    "age" => 0,
                    "blood" => null,
                    "fulladdress" => null,
                    "client_group_id" => Clients::DEFAULT_CID ?? null,
                    "vendor_id" => $vdr_id,
                    "status" => Drivers::STTS_ACTIVE,
                    "is_in_ord" => Drivers::IN_ORD_YES,
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "ord_ids" => json_encode([$ord_id]),
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ];
                $drv_id = Drivers::addDriver($insDriver);
                $insDetail = [
                    "did" => $drv_id,
                    "bank_id" => $req->drv_bank_id ?? 0,
                    "bank_code" => $req->drv_bank_code ?? null,
                    "bank_name" => $req->drv_bank_name ?? null,
                    "bank_short_name" => $req->drv_bank_short ?? null,
                    "bank_branch_name" => $req->drv_bank_branch_name,
                    "bank_acc_number" => $req->drv_bank_acc_number ?? null,
                    "bank_acc_name" => $req->drv_bank_acc_name ?? null,
                ];
                DriversDetail::addDetail($insDetail);
            } else {
                $driver = Drivers::showDriverById($drv_id);
                $ord_ids = [];
                if ($driver[0]->ord_ids) {
                    $ord_ids = json_decode($driver[0]->ord_ids);
                    array_push($ord_ids, $ord_id);
                } else {
                    array_push($ord_ids, $ord_id);
                }
                $updtDriver = [
                    "fullname" => $req->drv_name,
                    "fullname2" => $req->drv_name2,
                    "phone" => (int) $req->drv_phone,
                    "phone2" => $req->drv_phone2 ?? 0,
                    "phone2_code" => Drivers::DEFAULT_PHONE_CODE,
                    "status" => Drivers::STTS_ACTIVE,
                    "is_in_ord" => Drivers::IN_ORD_YES,
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "ord_ids" => json_encode($ord_ids),
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ];
                Drivers::updateDriver($drv_id, $updtDriver);
                $updtDetailDriver = [
                    "bank_id" => $req->drv_bank_id ?? 0,
                    "bank_code" => $req->drv_bank_code ?? null,
                    "bank_name" => $req->drv_bank_name ?? null,
                    "bank_short_name" => $req->drv_bank_short ?? null,
                    "bank_branch_name" => $req->drv_bank_branch_name,
                    "bank_acc_number" => $req->drv_bank_acc_number ?? null,
                    "bank_acc_name" => $req->drv_bank_acc_name ?? null,
                ];
                DriversDetail::updateDetailByDid($drv_id, $updtDetailDriver);
            }
            $driver = Drivers::showDriverById($drv_id);

            if ($vhc_id === 0) {
                $insVhc = [
                    "name" =>
                        strtoupper($nopol[0]) .
                        " " .
                        strtoupper($nopol[1]) .
                        " " .
                        strtoupper($nopol[2]),
                    "dvc_id" => $device[0]->id,
                    "device_id" => $device_id,
                    "simcard" => $device[0]->simcard,
                    "cat_id" => Vehicles::DEFAULT_CAT_ID,
                    "brand_id" => 0,
                    "type_id" => $req->truck_type_id,
                    "nopol1" => strtoupper($nopol[0]),
                    "nopol2" => strtoupper($nopol[1]),
                    "nopol3" => strtoupper($nopol[2]),
                    "c_did" => $drv_id,
                    "a_did" => $drv_id,
                    "is_track_holiday" => Vehicles::DEFAULT_TRACK_HOLIDAY,
                    "track_sch_d" => Vehicles::DEFAULT_TRACK_SCH_D,
                    "track_sch_h" => Vehicles::DEFAULT_TRACK_SCH_H,
                    "client_group_id" => Clients::DEFAULT_CID,
                    "vendor_id" => $vdr_id,
                    "status" => Vehicles::STTS_ACTIVE,
                    "is_in_ord" => Vehicles::IN_ORD_YES,
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "ord_ids" => json_encode([$ord_id]),
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ];
                $vhc_id = Vehicles::addVehicle($insVhc);
                $insVhcDetail = [
                    "vid" => $vhc_id,
                    "tax_exp" => $req->vhc_stnk_taxexp,
                    "kir_exp" => $req->vhc_kir_exp,
                ];
                VehiclesDetail::addDetail($insVhcDetail);
            } else {
                $vehicle = Vehicles::showVehicleById($vhc_id);
                $ord_ids = [];
                if ($vehicle[0]->ord_ids) {
                    $ord_ids = json_decode($vehicle[0]->ord_ids);
                    array_push($ord_ids, $ord_id);
                } else {
                    array_push($ord_ids, $ord_id);
                }
                $updtVhc = [
                    "name" =>
                        strtoupper($nopol[0]) .
                        " " .
                        strtoupper($nopol[1]) .
                        " " .
                        strtoupper($nopol[2]),
                    "dvc_id" => $device[0]->id,
                    "device_id" => $device_id,
                    "simcard" => $device[0]->simcard,
                    "type_id" => $req->truck_type_id,
                    "nopol1" => strtoupper($nopol[0]),
                    "nopol2" => strtoupper($nopol[1]),
                    "nopol3" => strtoupper($nopol[2]),
                    "c_did" => $drv_id,
                    "a_did" => $drv_id,
                    "status" => Vehicles::STTS_ACTIVE,
                    "is_in_ord" => Vehicles::IN_ORD_YES,
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "ord_ids" => json_encode($ord_ids),
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ];
                if (
                    $updtVhc["dvc_id"] == 0 &&
                    $updtVhc["device_id"] == "0000000000000000"
                ) {
                    $updtVhc["dvc_id"] = $vehicle[0]->dvc_id;
                    $updtVhc["device_id"] = $vehicle[0]->device_id;
                }
                Vehicles::updateVehicle($vhc_id, $updtVhc);
                $updtVhcDetail = [
                    "tax_exp" => $req->vhc_stnk_taxexp,
                    "kir_exp" => $req->vhc_kir_exp,
                ];
                VehiclesDetail::updateDetailByVid($vhc_id, $updtVhcDetail);
            }
            $vehicle = Vehicles::showVehicleById($vhc_id);

            if ($device[0]->id > 0) {
                Devices::updateDevice($device[0]->id, [
                    "is_assigned" => Devices::IS_ASSIGNED,
                    "is_available" => Devices::IS_UNAVAIL,
                ]);
            }

            // if ($pckPoints[0]->boundary_bounds) {
            // 	// $pckPoints[0]->boundary_bounds = json_encode($pckPoints[0]->boundary_bounds);
            // }
            // if ($pckPoints[0]->boundary_latlngs) {
            // 	// $pckPoints[0]->boundary_latlngs = json_encode($pckPoints[0]->boundary_latlngs);
            // }

            $pck_ids = [];
            foreach ($pckPoints as $i => $pck) {
                $insPck = [
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "set_pck_at" => $pck->inpt_set_pck_at,
                    "stts_pck" => OrdersPickups::STTS_WAIT,
                    "pck_id" => $pck->id,
                    "pck_name" => $pck->name,
                    "pck_desc" => $pck->desc,
                    "pck_type" => $pck->type,
                    "pck_workflow" => $pck->workflow_type,
                    "pck_shiptocode" => $pck->shiptocode,
                    "pck_prid" => $pck->prid,
                    "pck_ktid" => $pck->ktid,
                    "pck_kcid" => $pck->kcid,
                    "pck_klid" => $pck->klid,
                    "pck_addr" => $pck->fulladdress,
                    "pck_cgroup_id" => $pck->client_group_id,
                    "pck_cdiv_id" => $pck->client_div_id,
                    "pck_cgp_id" => $pck->client_gp_id,
                    "pck_hex_color" => $pck->boundary_hex_color,
                    "pck_shape" => $pck->boundary_type,
                    "pck_radius" => $pck->boundary_radius,
                    "pck_diameter" => $pck->boundary_diameter,
                    "pck_area" => $pck->boundary_area,
                    "pck_ha" => $pck->boundary_ha,
                    "pck_bounds" => $pck->boundary_bounds,
                    "pck_latlngs" => $pck->boundary_latlngs,
                    "pck_points" => $pck->boundary_points,
                    "pic_name" => $pck->inpt_pic_name,
                    "pic_phone_code" => $pck->inpt_pic_phone_code,
                    "pic_phone_val" => $pck->inpt_pic_phone_val,
                    "pic_mail" => $pck->inpt_pic_mail,
                    // 'pic_name' => $clientAuth->first_name,
                    // 'pic_phone_code' => $clientAuth->phone_code,
                    // 'pic_phone_val' => $clientAuth->phone,
                    // 'pic_mail' => $clientAuth->email,
                ];
                $pck_id = OrdersPickups::add($insPck);
                $pck_ids[] = $pck_id;
            }

            // if ($dropPoints[0]->boundary_bounds) {
            // 	// $dropPoints[0]->boundary_bounds = json_encode($dropPoints[0]->boundary_bounds);
            // }
            // if ($dropPoints[0]->boundary_latlngs) {
            // 	// $dropPoints[0]->boundary_latlngs = json_encode($dropPoints[0]->boundary_latlngs);
            // }

            $drop_ids = [];
            foreach ($dropPoints as $i => $drop) {
                $insDrop = [
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "stts_drop" => OrdersDrops::STTS_WAIT,
                    "drop_id" => $drop->id,
                    "drop_name" => $drop->name,
                    "drop_desc" => $drop->desc,
                    "drop_type" => $drop->type,
                    "drop_workflow" => $drop->workflow_type,
                    "drop_shiptocode" => $drop->shiptocode,
                    "drop_prid" => $drop->prid,
                    "drop_ktid" => $drop->ktid,
                    "drop_kcid" => $drop->kcid,
                    "drop_klid" => $drop->klid,
                    "drop_addr" => $drop->fulladdress,
                    "drop_cgroup_id" => $drop->client_group_id,
                    "drop_cdiv_id" => $drop->client_div_id,
                    "drop_cgp_id" => $drop->client_gp_id,
                    "drop_hex_color" => $drop->boundary_hex_color,
                    "drop_shape" => $drop->boundary_type,
                    "drop_radius" => $drop->boundary_radius,
                    "drop_diameter" => $drop->boundary_diameter,
                    "drop_area" => $drop->boundary_area,
                    "drop_ha" => $drop->boundary_ha,
                    "drop_bounds" => $drop->boundary_bounds,
                    "drop_latlngs" => $drop->boundary_latlngs,
                    "drop_points" => $drop->boundary_points,
                    "pic_name" => $drop->inpt_pic_name,
                    "pic_phone_code" => $drop->inpt_pic_phone_code,
                    "pic_phone_val" => $drop->inpt_pic_phone_val,
                    "pic_mail" => $drop->inpt_pic_mail,
                    // 'pic_name' => $clientAuth->first_name,
                    // 'pic_phone_code' => $clientAuth->phone_code,
                    // 'pic_phone_val' => $clientAuth->phone,
                    // 'pic_mail' => $clientAuth->email,
                ];
                $drop_id = OrdersDrops::add($insDrop);
                $drop_ids[] = $drop_id;

                OrdersPckDrop::add([
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "pck_id" => $pck_ids[$i],
                    "drop_id" => $drop_ids[$i],
                    "is_active" => 1,
                    "stts" => OrdersPckDrop::STTS_DELIVERY_OTW_PICKUP,
                    "crt" => $now,
                    "crt_by" => 0,
                    "updt" => $now,
                    "updt_by" => 0,
                ]);
            }

            $insClient = [
                "ord_id" => $ord_id,
                "ord_code" => $ord_code,
                "c_id" => $clientAuth->uid,
                "c_name" => $clientAuth->first_name,
                "c_phone_code" => $clientAuth->phone_code,
                "c_phone_val" => $clientAuth->phone,
                "c_mail" => $clientAuth->email,
                "c_addr" => $clientAuth->fulladdress,
                "c_disc_type" => $client[0]->disc_type,
                "c_disc_amount" => $client[0]->disc_amount,
                "c_pt_id" => $client[0]->id,
                "c_pt_div_id" => $clientAuth->client_div_id,
                "c_pt_gp_id" => $clientAuth->client_gp_id,
                "c_pt_name" => $client[0]->c_name,
                "c_pt_phone_code" => $client[0]->c_phone_code,
                "c_pt_phone_val" => $client[0]->c_phone,
                "c_pt_mail" => $client[0]->c_mail,
                "c_pt_addr" => $client[0]->c_addr_office,
                "c_pt_pic_name" => $client[0]->pic_name,
                "c_pt_pic_phone_code" => $client[0]->pic_phone_code,
                "c_pt_pic_phone_val" => $client[0]->pic_phone,
                "c_pt_pic_mail" => $client[0]->pic_mail,
                "c_pt_pic_addr" => null,
                "prefer_truck_type" => $req->truck_type_id,
                "is_pkp" => $req->is_client_pkp,
            ];
            $ord_client_id = OrdersClients::add($insClient);

            if ($req->is_vdr_bcng != Users::IS_VDR_BCNG_YES) {
                $insRate = [
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "rate_id" => $rate_id,
                    "rate_code" => $rate_code,
                    "origin_prov" => $insRate["origin_prov"],
                    "origin_city" => $insRate["origin_city"],
                    "origin_district" => $insRate["origin_district"],
                    "origin_village" => $insRate["origin_village"],
                    "lane" => $insRate["lane"],
                    "dest_prov" => $insRate["dest_prov"],
                    "dest_city" => $insRate["dest_city"],
                    "dest_district" => $insRate["dest_district"],
                    "dest_village" => $insRate["dest_village"],
                    "fast_time" => $insRate["fast_time"],
                    "long_time" => $insRate["long_time"],
                    "unit_time" => $insRate["unit_time"],
                    "sell_kg" => $insRate["sell_kg"],
                    "buy_kg" => $insRate["buy_kg"],
                    "margin_kg" => $insRate["margin_kg"],
                    "percent_kg" => $insRate["percent_kg"],
                    "sell_cbm" => $insRate["sell_cbm"],
                    "buy_cbm" => $insRate["buy_cbm"],
                    "margin_cbm" => $insRate["margin_cbm"],
                    "percent_cbm" => $insRate["percent_cbm"],
                    "sell_ftl" => $insRate["sell_ftl"],
                    "buy_ftl" => $insRate["buy_ftl"],
                    "margin_ftl" => $insRate["margin_ftl"],
                    "percent_ftl" => $insRate["percent_ftl"],
                    "vdr_id" => $insRate["vdr_id"],
                    "vhc_type" => $insRate["vhc_type"],
                    "crt_type" => $insRate["crt_type"],
                ];
                OrdersRates::add($insRate);
            }

            if ($req->is_insurance == "true") {
                // if (count($insurance) > 0) {
                $insurance = StaticInsurances::listStaticInsurances([
                    "is_active" => StaticInsurances::IS_ACTIVE,
                ]);
                $beneficiary = $req->amt_beneficiary ?? 0; // nilai pertangguhan
                $calcPercent =
                    ($beneficiary * $insurance[0]->amt_percent) / 100;
                $flatPercent = $beneficiary - $calcPercent;
                $insInsurance = [
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "insurance_id" => 0,
                    "premi_name" => $insurance[0]->desc,
                    "premi_price" => $calcPercent,
                    "amt_beneficiary" => $beneficiary,
                    "amt_percent" => $insurance[0]->amt_percent,
                    "amt_type" => OrdersInsurances::AMT_TYPE_PERCENT,
                    "premi_min_price" => $beneficiary,
                    "premi_max_price" => $beneficiary,
                    "desc" => $insurance[0]->desc,
                ];
                OrdersInsurances::add($insInsurance);
            }

            $vdrCompany = Clients::getClientById($vendor[0]->client_group_id);
            $insVendors = [
                "ord_id" => $ord_id,
                "ord_code" => $ord_code,
                "vdr_id" => $vendor[0]->id,
                "vdr_name" => $vendor[0]->first_name,
                "vdr_mail" => $vendor[0]->email,
                "vdr_phone_code" => $vendor[0]->phone_code,
                "vdr_phone_val" => $vendor[0]->phone,
                "vdr_addr" => $vendor[0]->fulladdress,
                "vdr_cgroup_id" => $vendor[0]->client_group_id,
                "vdr_pt_name" => $vdrCompany[0]->c_name,
                "vdr_pt_phone_code" => $vdrCompany[0]->c_phone_code,
                "vdr_pt_phone_val" => $vdrCompany[0]->c_phone,
                "vdr_pt_mail" => $vdrCompany[0]->c_mail,
                "vdr_pt_addr" => $vdrCompany[0]->c_addr_office,
                "vdr_pt_pic_name" => $vdrCompany[0]->pic_name,
                "vdr_pt_pic_phone_code" => $vdrCompany[0]->pic_phone_code,
                "vdr_pt_pic_phone_val" => $vdrCompany[0]->pic_phone,
                "vdr_pt_pic_mail" => $vdrCompany[0]->pic_mail,
                "vdr_bank_id" => $vendor[0]->bank_id,
                "vdr_bank_code" => $vendor[0]->bank_code,
                "vdr_bank_short_name" => $vendor[0]->bank_short_name,
                "vdr_bank_name" => $vendor[0]->bank_name,
                "vdr_bank_branch_name" => $vendor[0]->bank_branch_name,
                "vdr_bank_acc_number" => $vendor[0]->bank_acc_number,
                "vdr_bank_acc_name" => $vendor[0]->bank_acc_name,
                "is_vdr_bcng" => $req->is_vdr_bcng,
                "find_vhcs" => $vhc_id,
                "find_radius" => 0,
                "find_shape" => Zone::ZONE_BOUNDARY_CIRCLE,
                "find_center_lat" => 0,
                "find_center_lng" => 0,
                "distance" => 0,
                "is_exp" => OrdersVendors::LINK_NOT_EXP,
                "exp_at" => 0, // strtotime('+10 minutes', $now), // strtotime('+1 day', $now)
                "bid_token" => (new Nanoid())->generateId(36),
                "is_mailing_bid" => OrdersVendors::IS_MAILING_BID_NOT,
                "is_mailing_bid_at" => 0,
                "is_want" => OrdersVendors::IS_WANT_YES,
                "is_want_at" => $now,
                "status" => OrdersVendors::STTS_ACC,
                "respond_at" => $now,
                "is_pkp" => $req->is_vendor_pkp,
                "crt" => $now,
            ];
            OrdersVendors::add($insVendors);

            OrdersDrivers::add([
                "ord_id" => $ord_id,
                "ord_code" => $ord_code,
                "vdr_id" => $driver[0]->vendor_id,
                "drv_id" => $driver[0]->id,
                "drv_name" => $driver[0]->fullname,
                "drv_mail" => $driver[0]->email,
                "drv_name2" => $driver[0]->fullname2,
                "drv_phone_code" => $driver[0]->phone_code,
                "drv_phone_val" => $driver[0]->phone,
                "drv_phone2_code" => $driver[0]->phone2_code,
                "drv_phone2_val" => $driver[0]->phone2,
                "drv_addr" => $driver[0]->fulladdress,
                "drv_cgroup_id" => $driver[0]->client_group_id,
                "drv_nik" => $driver[0]->nik,
                "drv_dob" => $driver[0]->dob,
                "drv_age" => Helper::countAge($driver[0]->dob),
                "drv_gender" => $driver[0]->gender,
                "drv_blood" => $driver[0]->blood,
                "em_fullname" => $driver[0]->em_fullname,
                "em_phone_code" => $driver[0]->em_phone_code,
                "em_phone_val" => $driver[0]->em_phone,
                "em_relationship" => $driver[0]->em_relationship,
                "drv_ktp_img" => $driver[0]->ktp_img,
                "drv_npwp_img" => $driver[0]->npwp_img,
                "drv_npwp_number" => $driver[0]->npwp_number,
                "drv_npwp_string" => $driver[0]->npwp_string,
                "drv_license_img" => $driver[0]->license_img,
                "drv_license_number" => $driver[0]->license_number,
                "drv_license_exp" => $driver[0]->license_exp,
                "drv_bank_id" => $req->drv_bank_id ?? 0,
                "drv_bank_code" => $req->drv_bank_code ?? null,
                "drv_bank_short_name" => $req->drv_bank_short ?? null,
                "drv_bank_name" => $req->drv_bank_name ?? null,
                "drv_bank_branch_name" => $req->drv_bank_branch_name ?? null,
                "drv_bank_acc_number" => $req->drv_bank_acc_number ?? null,
                "drv_bank_acc_name" => $req->drv_bank_acc_name ?? null,
            ]);
            OrdersVehicles::add([
                "ord_id" => $ord_id,
                "ord_code" => $ord_code,
                "vhc_id" => $vehicle[0]->vid,
                "vhc_name" => $vehicle[0]->name,
                "vhc_dvc_id" => $device[0]->id,
                "vhc_dvc_name" => $device[0]->name,
                "vhc_dvc_type" => $device[0]->type,
                "vhc_device_id" => $vehicle[0]->device_id,
                "vhc_simcard_code" => $device[0]->simcard_code,
                "vhc_simcard" => $device[0]->simcard,
                "vhc_cat_id" => $vehicle[0]->cat_id,
                "vhc_brand_id" => $vehicle[0]->brand_id,
                "vhc_type_id" => $vehicle[0]->type_id,
                "vhc_model_id" => $vehicle[0]->model_id,
                "vhc_c_did" => $vehicle[0]->c_did,
                "vhc_a_did" => $vehicle[0]->a_did,
                "vhc_nopol1" => $vehicle[0]->nopol1,
                "vhc_nopol2" => $vehicle[0]->nopol2,
                "vhc_nopol3" => $vehicle[0]->nopol3,
                "vhc_is_track_holiday" => $vehicle[0]->is_track_holiday,
                "vhc_track_sch_d" => $vehicle[0]->track_sch_d,
                "vhc_track_sch_h" => $vehicle[0]->track_sch_h,
                "vhc_cgroup_id" => $vehicle[0]->client_group_id,
                "vhc_vdr_id" => $vehicle[0]->vendor_id,
                "vhc_speed_limit" => $vehicle[0]->speed_limit,
                "vhc_fuel_capacity" => $vehicle[0]->fuel_capacity,
                "vhc_fuel_drop_treshold" => $vehicle[0]->fuel_drop_treshold,
                "vhc_max_pressure" => $vehicle[0]->max_pressure,
                "vhc_fvhc_img" => $vehicle[0]->fvhc_img,
                "vhc_stnk_img" => $vehicle[0]->stnk_img,
                "vhc_stnk_exp" => $vehicle[0]->stnk_exp,
                "vhc_vyear" => $vehicle[0]->vyear,
                "vhc_cc" => $vehicle[0]->cc,
                "vhc_vin" => $vehicle[0]->vin,
                "vhc_en" => $vehicle[0]->en,
                "vhc_vcolor" => $vehicle[0]->vcolor,
                "vhc_fuel_type" => $vehicle[0]->fuel_type,
                "vhc_tnkb_color" => $vehicle[0]->tnkb_color,
                "vhc_regis_year" => $vehicle[0]->regis_year,
                "vhc_tax_exp" => $vehicle[0]->tax_exp,
            ]);

            if ($req->is_vdr_bcng == Users::IS_VDR_BCNG_YES) {
                // $req->pocket_id
                // $req->pocket_type
                // $req->pocket_checkpoints
                $pocket = PocketMoney::showPocketById($req->pocket_id);
                if (count($pocket) < 1) {
                    $apiResp = Responses::not_found("uang saku belum dipilih");
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
                $ord_pocket_id = OrdersPockets::addPocket([
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "pocket_id" => $pocket[0]->id,
                    "pocket_code" => $pocket[0]->code,
                    "pocket_name" => $pocket[0]->name,
                    "pck_id" => $pocket[0]->pck_id,
                    "drop_id" => $pocket[0]->drop_id,
                    "pocket_type" => $pocket[0]->type,
                    "pocket_flow" => $pocket[0]->flow,
                    "pocket_is_active" => $pocket[0]->is_active,
                    "pocket_total" => $pocket[0]->total,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ]);
                // order_pocket_id
                $pocket[0]->checkpoints = Checkpoints::listCheckpoints([
                    "pocket_id" => $pocket[0]->id,
                ]);
                foreach ($pocket[0]->checkpoints as $checkpoint) {
                    OrdersCheckpoints::addCheckpoint([
                        "ord_id" => $ord_id,
                        "ord_code" => $ord_code,
                        "ord_pocket_id" => $ord_pocket_id,
                        "pocket_id" => $checkpoint->pocket_id,
                        "pck_id" => $checkpoint->pck_id,
                        "drop_id" => $checkpoint->drop_id,
                        "pocket_sort" => $checkpoint->sort,
                        "pocket_fee" => $checkpoint->pocket_fee,
                        "pocket_tol_fee" => $checkpoint->tol_fee,
                        "pocket_fuel_fee" => $checkpoint->fuel_fee,
                        "pocket_total" => $checkpoint->total,
                        "crt" => $now,
                        "crt_by" => $req->auth->uid,
                        "updt" => $now,
                        "updt_by" => $req->auth->uid,
                    ]);
                }
            }

            // $main_item_dec = "Pengantaran Logistik<br>" . ucwords(strtolower($pckPoints[0]->prid_name)) . " - " . ucwords(strtolower($dropPoints[0]->prid_name)) . "<br>" . date('d F Y', $insPck['set_pck_at']);
            // $main_item_dec = "Pengantaran Logistik<br>" . ucwords(strtolower($pckPoints[0]->prid_name)) . " - " . ucwords(strtolower($dropPoints[0]->prid_name)) . "<br>" . strftime('%d %B %Y', $insPck['set_pck_at']);
            $main_item_dec =
                "Pengantaran Logistik<br>" .
                ucwords(strtolower($pckPoints[0]->ktid_name)) .
                " - " .
                ucwords(strtolower($dropPoints[0]->ktid_name)) .
                "<br>" .
                ucwords(strtolower($dropPoints[0]->name)) .
                ", " .
                ucwords(strtolower($dropPoints[0]->prid_name)) .
                " - " .
                $dropPoints[0]->shiptocode .
                "<br>" .
                strftime("%d %m %Y", $insPck["set_pck_at"]) .
                "<br>" .
                $req->note_tonase;

            if ($req->is_vdr_bcng == Users::IS_VDR_BCNG_YES) {
                $req->termin1_amt_type = OrdersTermins::AMT_TYPE_PERCENT;
                $req->buy_price = 0;
                $req->buy_price_tax_type = 0;
                $req->buy_price_tax_ppn_percent = 0;
                $req->buy_price_tax_ppn_flat = 0;
                $req->buy_price_tax_pph_percent = 0;
                $req->buy_price_tax_pph_flat = 0;
                $req->buy_price_total_tax = 0;
                $req->termin1_amt = 0;
                $req->termin1_calc_percent = 0;
                $req->termin1_at = 0;
                $req->termin1_calc_percent_base = 0;
            }

            $v_termin_sequence = 0;
            $v_termin1_id = 0;
            $v_termin2_id = 0;
            if (
                $req->termin1_amt_type == OrdersTermins::AMT_TYPE_FLAT ||
                $req->termin1_amt_type == OrdersTermins::AMT_TYPE_PERCENT
            ) {
                ++$v_termin_sequence;
                $insTerminsVdr1 = [
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "flow_type" => OrdersTermins::FLOW_TYPE_PAYMENT,
                    "cash_type" => OrdersTermins::TYPE_CASH_OUT,
                    "sequence" => $v_termin_sequence,
                    "termin_base_flat" => $req->buy_price,
                    "termin_tax_type" => $req->buy_price_tax_type,
                    "termin_tax_ppn_percent" =>
                        $req->buy_price_tax_ppn_percent ?? 0,
                    "termin_tax_ppn_flat" => $req->buy_price_tax_ppn_flat ?? 0,
                    "termin_tax_pph_percent" =>
                        $req->buy_price_tax_pph_percent ?? 0,
                    "termin_tax_pph_flat" => $req->buy_price_tax_pph_flat ?? 0,
                    "termin_total_tax_flat" => $req->buy_price_total_tax ?? 0,
                    "termin_amt_type" => $req->termin1_amt_type ?? 0,
                    "termin_amt" => $req->termin1_amt ?? 0,
                    "termin_calc_percent" => $req->termin1_calc_percent ?? 0,
                    "termin_result_flat" =>
                        $req->termin1_amt_type == OrdersTermins::AMT_TYPE_FLAT
                            ? $req->termin1_amt
                            : $req->termin1_calc_percent,
                    "termin_ddln_at" => $req->termin1_at ?? 0,
                    "termin_ddln_type" => OrdersTermins::DDLN_TERMIN_TYPE_TIME,
                    "termin_for" => OrdersTermins::TERMIN_FOR_VENDOR,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "crt_type" => OrdersTermins::CRT_TYPE_ADMIN,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ];
                $v_termin1_id = OrdersTermins::add($insTerminsVdr1);
                $qty = 1;
                $amt_base_flat =
                    $req->termin1_amt_type == OrdersTermins::AMT_TYPE_FLAT
                        ? $req->termin1_amt
                        : $req->termin1_calc_percent_base;
                $yang_dijadiin_summary = $insTerminsVdr1["termin_result_flat"];
                if (
                    $req->buy_price_tax_type ==
                    OrdersAItems::AMT_TAX_TYPE_INCLUDE
                ) {
                    // $yang_dijadiin_summary = $amt_base_flat;
                    $yang_dijadiin_summary =
                        $insTerminsVdr1["termin_result_flat"];
                } elseif (
                    $req->buy_price_tax_type ==
                    OrdersAItems::AMT_TAX_TYPE_EXCLUDE
                ) {
                    $yang_dijadiin_summary =
                        $insTerminsVdr1["termin_result_flat"];
                }
                OrdersAItems::add([
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "flow_type" => OrdersAItems::FLOW_TYPE_PAYMENT,
                    "cash_type" => OrdersAItems::TYPE_CASH_OUT,
                    "v_termin_id" => $v_termin1_id,
                    "a_item_type" => OrdersAItems::A_TYPE_PRIMARY,
                    // 'desc' => $main_item_dec . "<br>Pembayaran termin 1",
                    "desc" => $main_item_dec,
                    "unit_id" => 0,
                    "unit_type" => UnitTypes::UNIT_TYPE_PAKET,
                    "unit_qty" => $qty,
                    "amt_base_flat" => $amt_base_flat,
                    "amt_tax_type" => $req->buy_price_tax_type,
                    "amt_tax_ppn_percent" =>
                        $req->buy_price_tax_ppn_percent ?? 0,
                    "amt_tax_ppn_flat" => $req->buy_price_tax_ppn_flat ?? 0,
                    "amt_tax_pph_percent" =>
                        $req->buy_price_tax_pph_percent ?? 0,
                    "amt_tax_pph_flat" => $req->buy_price_tax_pph_flat ?? 0,
                    "amt_total_tax_flat" =>
                        $insTerminsVdr1["termin_result_flat"],
                    "amt_result_flat" => $insTerminsVdr1["termin_result_flat"],
                    "amt_total_flat" => $yang_dijadiin_summary * $qty,
                    "ddln_pay_at" => $insTerminsVdr1["termin_ddln_at"],
                    "ddln_pay_type" => OrdersAItems::DDLN_PAY_TYPE_TIME,
                    "img_proof_submission" => null,
                    "img_proof_payment" => null,
                    "bank_id" => $insVendors["vdr_bank_id"],
                    "bank_code" => $insVendors["vdr_bank_code"],
                    "bank_name" => $insVendors["vdr_bank_name"],
                    "bank_short_name" => $insVendors["vdr_bank_short_name"],
                    "bank_acc_number" => $insVendors["vdr_bank_acc_number"],
                    "bank_acc_name" => $insVendors["vdr_bank_acc_name"],
                    "invc_to_client" => OrdersAItems::INVC_TO_CLIENT_NO,
                    "calc_to_vdr" => OrdersAItems::CALC_TO_VDR_YES,
                    "only_vdr" => OrdersAItems::ONLY_VDR_YES,
                    "ref_ord_id" => $ord_id,
                    "ref_ord_code" => $ord_code,
                    "ref_v_termin_id" => $v_termin1_id,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ]);
            }
            if (
                ($req->termin2_amt_type == OrdersTermins::AMT_TYPE_FLAT ||
                    $req->termin2_amt_type ==
                        OrdersTermins::AMT_TYPE_PERCENT) &&
                $req->termin2_amt > 0
            ) {
                ++$v_termin_sequence;
                $insTerminsVdr2 = [
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "flow_type" => OrdersTermins::FLOW_TYPE_PAYMENT,
                    "cash_type" => OrdersTermins::TYPE_CASH_OUT,
                    "sequence" => $v_termin_sequence,
                    "termin_base_flat" => $req->buy_price,
                    "termin_tax_type" => $req->buy_price_tax_type,
                    "termin_tax_ppn_percent" =>
                        $req->buy_price_tax_ppn_percent ?? 0,
                    "termin_tax_ppn_flat" => $req->buy_price_tax_ppn_flat ?? 0,
                    "termin_tax_pph_percent" =>
                        $req->buy_price_tax_pph_percent ?? 0,
                    "termin_tax_pph_flat" => $req->buy_price_tax_pph_flat ?? 0,
                    "termin_total_tax_flat" => $req->buy_price_total_tax ?? 0,
                    "termin_amt_type" => $req->termin2_amt_type ?? 0,
                    "termin_amt" => $req->termin2_amt ?? 0,
                    "termin_calc_percent" => $req->termin2_calc_percent ?? 0,
                    "termin_result_flat" =>
                        $req->termin2_amt_type == OrdersTermins::AMT_TYPE_FLAT
                            ? $req->termin2_amt
                            : $req->termin2_calc_percent,
                    "termin_ddln_at" => $req->termin2_at ?? 0,
                    "termin_ddln_type" =>
                        OrdersTermins::DDLN_TERMIN_TYPE_ORD_FINISH,
                    "termin_for" => OrdersTermins::TERMIN_FOR_VENDOR,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "crt_type" => OrdersTermins::CRT_TYPE_ADMIN,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ];
                $v_termin2_id = OrdersTermins::add($insTerminsVdr2);
                $qty = 1;
                $amt_base_flat =
                    $req->termin2_amt_type == OrdersTermins::AMT_TYPE_FLAT
                        ? $req->termin2_amt
                        : $req->termin2_calc_percent_base;
                $yang_dijadiin_summary = $insTerminsVdr2["termin_result_flat"];
                if (
                    $req->buy_price_tax_type ==
                    OrdersAItems::AMT_TAX_TYPE_INCLUDE
                ) {
                    // $yang_dijadiin_summary = $amt_base_flat;
                    $yang_dijadiin_summary =
                        $insTerminsVdr2["termin_result_flat"];
                } elseif (
                    $req->buy_price_tax_type ==
                    OrdersAItems::AMT_TAX_TYPE_EXCLUDE
                ) {
                    $yang_dijadiin_summary =
                        $insTerminsVdr2["termin_result_flat"];
                }
                OrdersAItems::add([
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "flow_type" => OrdersAItems::FLOW_TYPE_PAYMENT,
                    "cash_type" => OrdersAItems::TYPE_CASH_OUT,
                    "v_termin_id" => $v_termin2_id,
                    "a_item_type" => OrdersAItems::A_TYPE_PRIMARY,
                    // 'desc' => $main_item_dec . "<br>Pembayaran termin 2",
                    "desc" => $main_item_dec,
                    "unit_id" => 0,
                    "unit_type" => UnitTypes::UNIT_TYPE_PAKET,
                    "unit_qty" => $qty,
                    "amt_base_flat" => $amt_base_flat,
                    "amt_tax_type" => $req->buy_price_tax_type,
                    "amt_tax_ppn_percent" =>
                        $req->buy_price_tax_ppn_percent ?? 0,
                    "amt_tax_ppn_flat" => $req->buy_price_tax_ppn_flat ?? 0,
                    "amt_tax_pph_percent" =>
                        $req->buy_price_tax_pph_percent ?? 0,
                    "amt_tax_pph_flat" => $req->buy_price_tax_pph_flat ?? 0,
                    "amt_total_tax_flat" =>
                        $insTerminsVdr2["termin_result_flat"],
                    "amt_result_flat" => $insTerminsVdr2["termin_result_flat"],
                    "amt_total_flat" => $yang_dijadiin_summary * $qty,
                    "ddln_pay_at" => $insTerminsVdr2["termin_ddln_at"],
                    "ddln_pay_type" => OrdersAItems::DDLN_PAY_TYPE_ORD_FINISH,
                    "img_proof_submission" => null,
                    "img_proof_payment" => null,
                    "bank_id" => $insVendors["vdr_bank_id"],
                    "bank_code" => $insVendors["vdr_bank_code"],
                    "bank_name" => $insVendors["vdr_bank_name"],
                    "bank_short_name" => $insVendors["vdr_bank_short_name"],
                    "bank_acc_number" => $insVendors["vdr_bank_acc_number"],
                    "bank_acc_name" => $insVendors["vdr_bank_acc_name"],
                    "invc_to_client" => OrdersAItems::INVC_TO_CLIENT_NO,
                    "calc_to_vdr" => OrdersAItems::CALC_TO_VDR_YES,
                    "only_vdr" => OrdersAItems::ONLY_VDR_YES,
                    "ref_ord_id" => $ord_id,
                    "ref_ord_code" => $ord_code,
                    "ref_v_termin_id" => $v_termin2_id,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ]);
            }
            if ($v_termin_sequence === 0) {
                $req->termin1_amt_type = OrdersTermins::AMT_TYPE_FLAT;
                $req->termin1_amt = $req->buy_price;
                $req->termin1_amt_at = strtotime("+2 days", $now);
                $req->termin1_calc_percent = 0;
                ++$v_termin_sequence;
                $insTerminsVdr1 = [
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "flow_type" => OrdersTermins::FLOW_TYPE_PAYMENT,
                    "cash_type" => OrdersTermins::TYPE_CASH_OUT,
                    "sequence" => $v_termin_sequence,
                    "termin_base_flat" => $req->buy_price,
                    "termin_tax_type" => $req->buy_price_tax_type,
                    "termin_tax_ppn_percent" =>
                        $req->buy_price_tax_ppn_percent ?? 0,
                    "termin_tax_ppn_flat" => $req->buy_price_tax_ppn_flat ?? 0,
                    "termin_tax_pph_percent" =>
                        $req->buy_price_tax_pph_percent ?? 0,
                    "termin_tax_pph_flat" => $req->buy_price_tax_pph_flat ?? 0,
                    "termin_total_tax_flat" => $req->buy_price_total_tax ?? 0,
                    "termin_amt_type" => $req->termin1_amt_type ?? 0,
                    "termin_amt" => $req->termin1_amt ?? 0,
                    "termin_calc_percent" => $req->termin1_calc_percent ?? 0,
                    "termin_result_flat" =>
                        $req->termin1_amt_type == OrdersTermins::AMT_TYPE_FLAT
                            ? $req->termin1_amt
                            : $req->termin1_calc_percent,
                    "termin_ddln_at" => $req->termin1_at ?? 0,
                    "termin_ddln_type" =>
                        OrdersTermins::DDLN_TERMIN_TYPE_ORD_FINISH,
                    "termin_for" => OrdersTermins::TERMIN_FOR_VENDOR,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "crt_type" => OrdersTermins::CRT_TYPE_ADMIN,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ];
                $v_termin1_id = OrdersTermins::add($insTerminsVdr1);
                $qty = 1;
                $amt_base_flat =
                    $req->termin1_amt_type == OrdersTermins::AMT_TYPE_FLAT
                        ? $req->termin1_amt
                        : $req->termin1_calc_percent_base;
                $yang_dijadiin_summary = $insTerminsVdr1["termin_result_flat"];
                if (
                    $req->buy_price_tax_type ==
                    OrdersAItems::AMT_TAX_TYPE_INCLUDE
                ) {
                    // $yang_dijadiin_summary = $amt_base_flat;
                    $yang_dijadiin_summary =
                        $insTerminsVdr1["termin_result_flat"];
                } elseif (
                    $req->buy_price_tax_type ==
                    OrdersAItems::AMT_TAX_TYPE_EXCLUDE
                ) {
                    $yang_dijadiin_summary =
                        $insTerminsVdr1["termin_result_flat"];
                }
                OrdersAItems::add([
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "flow_type" => OrdersAItems::FLOW_TYPE_PAYMENT,
                    "cash_type" => OrdersAItems::TYPE_CASH_OUT,
                    "v_termin_id" => $v_termin1_id,
                    "a_item_type" => OrdersAItems::A_TYPE_PRIMARY,
                    // 'desc' => $main_item_dec . "<br>Pembayaran termin 1",
                    "desc" => $main_item_dec,
                    "unit_id" => 0,
                    "unit_type" => UnitTypes::UNIT_TYPE_PAKET,
                    "unit_qty" => $qty,
                    "amt_base_flat" => $amt_base_flat,
                    "amt_tax_type" => $req->buy_price_tax_type,
                    "amt_tax_ppn_percent" =>
                        $req->buy_price_tax_ppn_percent ?? 0,
                    "amt_tax_ppn_flat" => $req->buy_price_tax_ppn_flat ?? 0,
                    "amt_tax_pph_percent" =>
                        $req->buy_price_tax_pph_percent ?? 0,
                    "amt_tax_pph_flat" => $req->buy_price_tax_pph_flat ?? 0,
                    "amt_total_tax_flat" =>
                        $insTerminsVdr1["termin_result_flat"],
                    "amt_result_flat" => $insTerminsVdr1["termin_result_flat"],
                    "amt_total_flat" => $yang_dijadiin_summary * $qty,
                    "ddln_pay_at" => $insTerminsVdr1["termin_ddln_at"],
                    "ddln_pay_type" => OrdersAItems::DDLN_PAY_TYPE_ORD_FINISH,
                    "img_proof_submission" => null,
                    "img_proof_payment" => null,
                    "bank_id" => $insVendors["vdr_bank_id"],
                    "bank_code" => $insVendors["vdr_bank_code"],
                    "bank_name" => $insVendors["vdr_bank_name"],
                    "bank_short_name" => $insVendors["vdr_bank_short_name"],
                    "bank_acc_number" => $insVendors["vdr_bank_acc_number"],
                    "bank_acc_name" => $insVendors["vdr_bank_acc_name"],
                    "invc_to_client" => OrdersAItems::INVC_TO_CLIENT_NO,
                    "calc_to_vdr" => OrdersAItems::CALC_TO_VDR_YES,
                    "only_vdr" => OrdersAItems::ONLY_VDR_YES,
                    "ref_ord_id" => $ord_id,
                    "ref_ord_code" => $ord_code,
                    "ref_v_termin_id" => $v_termin1_id,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ]);
            }

            $c_termin_sequence = 0;
            $c_termin1_id = 0;
            $c_termin2_id = 0;
            if (
                $req->sell_termin1_amt_type == OrdersTermins::AMT_TYPE_FLAT ||
                $req->sell_termin1_amt_type == OrdersTermins::AMT_TYPE_PERCENT
            ) {
                ++$c_termin_sequence;
                $insTerminsC1 = [
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "flow_type" => OrdersTermins::FLOW_TYPE_BILLING,
                    "cash_type" => OrdersTermins::TYPE_CASH_IN,
                    "sequence" => $c_termin_sequence,
                    "termin_base_flat" => $req->sell_price,
                    "termin_tax_type" => OrdersAItems::AMT_TAX_TYPE_EXCLUDE,
                    "termin_tax_ppn_percent" => OrdersAItems::PPN_PERCENT,
                    "termin_tax_pph_percent" => OrdersAItems::PPH_PERCENT,
                    "termin_amt_type" => $req->sell_termin1_amt_type ?? 0,
                    "termin_amt" => $req->sell_termin1_amt ?? 0,
                    "termin_calc_percent" =>
                        $req->sell_termin1_calc_percent ?? 0,
                    "termin_result_flat" =>
                        $req->sell_termin1_amt_type ==
                        OrdersTermins::AMT_TYPE_FLAT
                            ? $req->sell_termin1_amt
                            : $req->sell_termin1_calc_percent,
                    "termin_ddln_at" => $req->sell_termin1_at ?? 0,
                    "termin_ddln_type" => OrdersTermins::DDLN_TERMIN_TYPE_TIME,
                    "termin_for" => OrdersTermins::TERMIN_FOR_CLIENT,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "crt_type" => OrdersTermins::CRT_TYPE_ADMIN,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ];
                $c_termin1_id = OrdersTermins::add($insTerminsC1);
                $qty = 1;
                OrdersAItems::add([
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "flow_type" => OrdersAItems::FLOW_TYPE_BILLING,
                    "cash_type" => OrdersAItems::TYPE_CASH_IN,
                    "c_termin_id" => $c_termin1_id,
                    "a_item_type" => OrdersAItems::A_TYPE_PRIMARY,
                    // 'desc' => $main_item_dec . "<br>Pembayaran termin 1",
                    "desc" => $main_item_dec,
                    "unit_id" => 0,
                    "unit_type" => UnitTypes::UNIT_TYPE_PAKET,
                    "unit_qty" => $qty,
                    "amt_bill_base_flat" => $insTerminsC1["termin_result_flat"],
                    "amt_bill_result_flat" =>
                        $insTerminsC1["termin_result_flat"],
                    "amt_bill_total_flat" =>
                        $insTerminsC1["termin_result_flat"] * $qty,
                    "ddln_pay_at" => $insTerminsC1["termin_ddln_at"],
                    "ddln_pay_type" => OrdersAItems::DDLN_PAY_TYPE_TIME,
                    "img_proof_submission" => null,
                    "img_proof_payment" => null,
                    "bank_id" => Banks::DFT_BANK_ID,
                    "bank_code" => Banks::DFT_BANK_CODE,
                    "bank_name" => Banks::DFT_BANK_NAME,
                    "bank_short_name" => Banks::DFT_BANK_SHORT_NAME,
                    "bank_acc_number" => Banks::DFT_BANK_ACC_NUMBER,
                    "bank_acc_name" => Banks::DFT_BANK_ACC_NAME,
                    "invc_to_client" => OrdersAItems::INVC_TO_CLIENT_YES,
                    "calc_to_vdr" => OrdersAItems::CALC_TO_VDR_NO,
                    "only_client" => OrdersAItems::ONLY_CLIENT_YES,
                    "ref_ord_id" => $ord_id,
                    "ref_ord_code" => $ord_code,
                    "ref_c_termin_id" => $c_termin1_id,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ]);
            }
            if (
                ($req->sell_termin2_amt_type == OrdersTermins::AMT_TYPE_FLAT ||
                    $req->sell_termin2_amt_type ==
                        OrdersTermins::AMT_TYPE_PERCENT) &&
                $req->sell_termin2_amt > 0
            ) {
                ++$c_termin_sequence;
                $insTerminsC2 = [
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "flow_type" => OrdersTermins::FLOW_TYPE_BILLING,
                    "cash_type" => OrdersTermins::TYPE_CASH_IN,
                    "sequence" => $c_termin_sequence,
                    "termin_base_flat" => $req->sell_price,
                    "termin_tax_type" => OrdersAItems::AMT_TAX_TYPE_EXCLUDE,
                    "termin_tax_ppn_percent" => OrdersAItems::PPN_PERCENT,
                    "termin_tax_pph_percent" => OrdersAItems::PPH_PERCENT,
                    "termin_amt_type" => $req->sell_termin2_amt_type ?? 0,
                    "termin_amt" => $req->sell_termin2_amt ?? 0,
                    "termin_calc_percent" =>
                        $req->sell_termin2_calc_percent ?? 0,
                    "termin_result_flat" =>
                        $req->sell_termin2_amt_type ==
                        OrdersTermins::AMT_TYPE_FLAT
                            ? $req->sell_termin2_amt
                            : $req->sell_termin2_calc_percent,
                    "termin_ddln_at" => $req->sell_termin2_at ?? 0,
                    "termin_ddln_type" =>
                        OrdersTermins::DDLN_TERMIN_TYPE_ORD_FINISH,
                    "termin_for" => OrdersTermins::TERMIN_FOR_CLIENT,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "crt_type" => OrdersTermins::CRT_TYPE_ADMIN,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ];
                $c_termin2_id = OrdersTermins::add($insTerminsC2);
                $qty = 1;
                OrdersAItems::add([
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "flow_type" => OrdersAItems::FLOW_TYPE_BILLING,
                    "cash_type" => OrdersAItems::TYPE_CASH_IN,
                    "c_termin_id" => $c_termin2_id,
                    "a_item_type" => OrdersAItems::A_TYPE_PRIMARY,
                    // 'desc' => $main_item_dec . "<br>Pembayaran termin 2",
                    "desc" => $main_item_dec,
                    "unit_id" => 0,
                    "unit_type" => UnitTypes::UNIT_TYPE_PAKET,
                    "unit_qty" => $qty,
                    "amt_bill_base_flat" => $insTerminsC2["termin_result_flat"],
                    "amt_bill_result_flat" =>
                        $insTerminsC2["termin_result_flat"],
                    "amt_bill_total_flat" =>
                        $insTerminsC2["termin_result_flat"] * $qty,
                    "ddln_pay_at" => $insTerminsC2["termin_ddln_at"],
                    "ddln_pay_type" => OrdersAItems::DDLN_PAY_TYPE_ORD_FINISH,
                    "img_proof_submission" => null,
                    "img_proof_payment" => null,
                    "bank_id" => Banks::DFT_BANK_ID,
                    "bank_code" => Banks::DFT_BANK_CODE,
                    "bank_name" => Banks::DFT_BANK_NAME,
                    "bank_short_name" => Banks::DFT_BANK_SHORT_NAME,
                    "bank_acc_number" => Banks::DFT_BANK_ACC_NUMBER,
                    "bank_acc_name" => Banks::DFT_BANK_ACC_NAME,
                    "invc_to_client" => OrdersAItems::INVC_TO_CLIENT_YES,
                    "calc_to_vdr" => OrdersAItems::CALC_TO_VDR_NO,
                    "only_client" => OrdersAItems::ONLY_CLIENT_YES,
                    "ref_ord_id" => $ord_id,
                    "ref_ord_code" => $ord_code,
                    "ref_c_termin_id" => $c_termin2_id,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ]);
            }
            if ($c_termin_sequence === 0) {
                $req->sell_termin1_amt_type = OrdersTermins::AMT_TYPE_FLAT;
                $req->sell_termin1_amt = $req->sell_price;
                $req->sell_termin1_amt_at = strtotime("+2 days", $now);
                $req->sell_termin1_calc_percent = 0;
                ++$c_termin_sequence;
                $insTerminsC1 = [
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "flow_type" => OrdersTermins::FLOW_TYPE_BILLING,
                    "cash_type" => OrdersTermins::TYPE_CASH_IN,
                    "sequence" => $c_termin_sequence,
                    "termin_base_flat" => $req->sell_price,
                    "termin_tax_type" => OrdersAItems::AMT_TAX_TYPE_EXCLUDE,
                    "termin_tax_ppn_percent" => OrdersAItems::PPN_PERCENT,
                    "termin_tax_pph_percent" => OrdersAItems::PPH_PERCENT,
                    "termin_amt_type" => $req->sell_termin1_amt_type ?? 0,
                    "termin_amt" => $req->sell_termin1_amt ?? 0,
                    "termin_calc_percent" =>
                        $req->sell_termin1_calc_percent ?? 0,
                    "termin_result_flat" =>
                        $req->sell_termin1_amt_type ==
                        OrdersTermins::AMT_TYPE_FLAT
                            ? $req->sell_termin1_amt
                            : $req->sell_termin1_calc_percent,
                    "termin_ddln_at" => $req->sell_termin1_at ?? 0,
                    "termin_ddln_type" =>
                        OrdersTermins::DDLN_TERMIN_TYPE_ORD_FINISH,
                    "termin_for" => OrdersTermins::TERMIN_FOR_CLIENT,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "crt_type" => OrdersTermins::CRT_TYPE_ADMIN,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ];
                $c_termin1_id = OrdersTermins::add($insTerminsC1);
                $qty = 1;
                OrdersAItems::add([
                    "ord_id" => $ord_id,
                    "ord_code" => $ord_code,
                    "flow_type" => OrdersAItems::FLOW_TYPE_BILLING,
                    "cash_type" => OrdersAItems::TYPE_CASH_IN,
                    "c_termin_id" => $c_termin1_id,
                    "a_item_type" => OrdersAItems::A_TYPE_PRIMARY,
                    // 'desc' => $main_item_dec . "<br>Pembayaran termin 1",
                    "desc" => $main_item_dec,
                    "unit_id" => 0,
                    "unit_type" => UnitTypes::UNIT_TYPE_PAKET,
                    "unit_qty" => $qty,
                    "amt_bill_base_flat" => $insTerminsC1["termin_result_flat"],
                    "amt_bill_result_flat" =>
                        $insTerminsC1["termin_result_flat"],
                    "amt_bill_total_flat" =>
                        $insTerminsC1["termin_result_flat"] * $qty,
                    "ddln_pay_at" => $insTerminsC1["termin_ddln_at"],
                    "ddln_pay_type" => OrdersAItems::DDLN_PAY_TYPE_ORD_FINISH,
                    "img_proof_submission" => null,
                    "img_proof_payment" => null,
                    "bank_id" => Banks::DFT_BANK_ID,
                    "bank_code" => Banks::DFT_BANK_CODE,
                    "bank_name" => Banks::DFT_BANK_NAME,
                    "bank_short_name" => Banks::DFT_BANK_SHORT_NAME,
                    "bank_acc_number" => Banks::DFT_BANK_ACC_NUMBER,
                    "bank_acc_name" => Banks::DFT_BANK_ACC_NAME,
                    "invc_to_client" => OrdersAItems::INVC_TO_CLIENT_YES,
                    "calc_to_vdr" => OrdersAItems::CALC_TO_VDR_NO,
                    "only_client" => OrdersAItems::ONLY_CLIENT_YES,
                    "ref_ord_id" => $ord_id,
                    "ref_ord_code" => $ord_code,
                    "ref_c_termin_id" => $c_termin1_id,
                    "crt" => $now,
                    "crt_by" => $req->auth->uid,
                    "updt" => $now,
                    "updt_by" => $req->auth->uid,
                ]);
            }

            $url = env("API_URL_NODE") . "/order/create";
            $guzReq = new GuzzleClient();
            $respNode = $guzReq->request("POST", $url, [
                "headers" => [
                    "Host" => $_SERVER["SERVER_ADDR"] ?? "127.0.0.1",
                    "User-Agent" => "curl/7.65.3",
                    "Accept" => "*/*",
                    "Accept-Encoding" => "gzip, deflate, br",
                    // 'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
                    // 'Connection' => 'keep-alive',
                ],
                "json" => [
                    "trx_code" => $ord_code,
                    "trx_at" => $now,
                    "client_id" => $clientAuth->uid,
                    "client_name" => $clientAuth->first_name,
                    "client_phone" =>
                        $clientAuth->phone_code .
                        " " .
                        implode(" ", str_split($clientAuth->phone, 4)),
                    "client_mail" => $clientAuth->email,
                    "client_addr" => "",
                    "client_prefer_type_truck" => $type_truck_name,
                    "pickup_zone_title" => $pckPoints[0]->name,
                    "pickup_zone_addr" => $pckPoints[0]->fulladdress,
                    "pickup_at" => $req->points[0]["pickup_at"],
                    "drop_zone_title" => $dropPoints[0]->name,
                    "drop_zone_addr" => $dropPoints[0]->fulladdress,
                    "admins" => $admins_data,
                ],
            ]);
            if ($respNode->getStatusCode() != 200) {
                DB::rollBack();
                $apiResp = Responses::bad_request("fail create order 0");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }
            $body = json_decode($respNode->getBody()->getContents());

            $apiResp = Responses::created("success create order");

            DB::commit();
            return new Response($apiResp, $apiResp["meta"]["code"]);
        } catch (\Exception $e) {
            DB::rollBack();
            $apiResp = Responses::error($e->getMessage());
            return new Response($apiResp, $apiResp["meta"]["code"]);
        }
    }
}
