<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Hash;
use Validator;
use Auth;
use App\Responses;
use App\Helper;
use App\Models\Drivers;
use App\Models\DriversDetail;
use App\Models\Users;
use App\Models\DrvPhoneDevices;
use App\Models\UserLogs;

class DriversController extends Controller
{
    public function api_list_drivers(Request $req)
    {
        try {
            $now = time();
            $input = [];
            $rulesInput = [];

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

            $filter = [];
            if ($req->cptid) {
                $filter["company"] = $req->cptid;
            }
            $list = Drivers::listDrivers($req->auth, $filter);
            foreach ($list as $key => $row) {
                $list[$key]->DT_RowIndex = $key + 1;
                $list[$key]->mileage_km = "-";
                $list[$key]->action = "-";
            }

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

    public function api_show_driver(Request $req, $did)
    {
        try {
            $now = time();

            $input = [
                "did" => $did,
            ];
            $rulesInput = [
                "did" => "required|integer|not_in: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"]);
            }

            $driver = Drivers::showDriverById($did);
            if (count($driver) < 1) {
                $apiResp = Responses::not_found("driver not found");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

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

    public function api_add_driver(Request $req)
    {
        $url_ktp = "";
        $url_npwp = "";
        $url_license = "";
        try {
            $now = time();

            $input = [
                "ktp_photo" => $req->ktp_base64,
                "nik" => $req->nik,
                "fullname" => $req->fullname,
                "phone" => $req->phone,
                "email" => $req->email,
                "date_of_birth" => $req->dob,
                "age" => $req->age,
                "blood" => $req->blood,
                "home_address" => $req->fulladdress,
                "license_photo" => $req->license_base64,
                "license_number" => $req->license_number,
                "license_exp" => $req->license_exp,
                "emergency_fullname" => $req->em_fullname,
                "emergency_relationship" => $req->em_relationship,
                "emergency_phone" => $req->em_phone,
                "vendor_id" => Auth::user()->id,
            ];
            $rulesInput = [
                "ktp_photo" => "nullable|string", // required
                "nik" => "nullable", // required
                "fullname" => "required|string|min:3|max:125",
                "phone" => "required|integer|not_in:0",
                "email" => "nullable|email", // required
                "date_of_birth" => "nullable|date_format:Y-m-d", // required
                "age" => "nullable|integer", // required
                "blood" => "nullable|string|max:4", // required
                "license_photo" => "nullable|string", // required
                "license_number" => "nullable|numeric", // required
                "license_exp" => "nullable|date_format:Y-m-d", // required
                "emergency_fullname" => "nullable|string|min:3", // required
                "emergency_relationship" => "nullable|string", // required
                "emergency_phone" => "nullable|integer|not_in:0", // required
                "vendor_id" => "required|integer|not_in: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"]);
            }

            if ($req->nik) {
                $uniqNik = Drivers::getDriverByNik($req->nik);
                if (count($uniqNik) > 0) {
                    $apiResp = Responses::bad_request("ID Number has been used");
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
            }
            if ($req->phone) {
                $uniqPhone = Drivers::getDriverByPhone($req->phone);
                if (count($uniqPhone) > 0) {
                    $apiResp = Responses::bad_request("phone has been used");
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
            }
            if ($req->email) {
                $uniqEmail = Drivers::getDriverByEmail($req->email);
                if (count($uniqEmail) > 0) {
                    $apiResp = Responses::bad_request("email has been used");
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
            }

            DB::beginTransaction();

            $insDriver = [
                "nik" => $req->nik ? $req->nik : 0,
                "fullname" => $req->fullname,
                "email" => $req->email,
                "fullname2" => $req->fullname2,
                "phone" => $req->phone,
                "phone_code" => Drivers::DEFAULT_PHONE_CODE,
                "phone2" => $req->phone2 ?? 0,
                "phone2_code" => Drivers::DEFAULT_PHONE_CODE,
                "dob" => $req->dob,
                "age" => $req->age ? $req->age : 0,
                "blood" => $req->blood,
                "fulladdress" => $req->fulladdress,
                "client_group_id" => $req->auth->client_group_id ?? null,
                "crt" => $now,
                "crt_by" => $req->auth->uid,
                "updt" => $now,
                "updt_by" => $req->auth->uid,
            ];
            if ($req->auth->role == Users::ROLE_VENDOR) {
                $insDriver["vendor_id"] = $req->auth->uid;
            } else {
                $insDriver["vendor_id"] = Auth::user()->id ?? 0;
            }
            $did = Drivers::addDriver($insDriver);

            if ($req->ktp_base64) {
                $url_ktp = "drivers/$did/ktp_$now.jpeg";
                if (!Storage::disk("public")->put($url_ktp, base64_decode($req->ktp_base64))) {
                    DB::rollBack();
                    $apiResp = Responses::bad_request("fail upload ktp photo");
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
            }
            if ($req->license_base64) {
                $url_license = "drivers/$did/license_$now.jpeg";
                if (!Storage::disk("public")->put($url_license, base64_decode($req->license_base64))) {
                    Storage::disk("public")->delete($url_ktp);
                    Storage::disk("public")->delete($url_npwp);
                    DB::rollBack();
                    $apiResp = Responses::bad_request("fail upload license photo");
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
            }

            $insDetail = [
                "did" => $did,
                "ktp_img" => $url_ktp ? $url_ktp : "",
                "npwp_img" => $url_npwp ? $url_npwp : "",
                "npwp_string" => $req->npwp_string,
                "npwp_number" => $req->npwp_number,
                "license_img" => $url_license ? $url_license : "",
                "license_number" => $req->license_number,
                "license_exp" => $req->license_exp,
                "em_fullname" => $req->em_fullname,
                "em_phone" => $req->em_phone,
                "em_relationship" => $req->em_relationship,
                "bank_id" => 1,
                "bank_code" => $req->bank_code,
                "bank_short_name" => $req->bank_short,
                "bank_name" => $req->bank_name,
                "bank_branch_name" => $req->bank_branch_name,
                "bank_acc_number" => $req->bank_acc_number,
                "bank_acc_name" => $req->bank_acc_name,
            ];
            DriversDetail::addDetail($insDetail);

            $insAccount = [
                "client_id" => Auth::user()->client_id,
                "client_group_id" => Auth::user()->client_group_id,
                "first_name" => $req->fullname,
                "last_name" => null,
                "email" => $req->email,
                "phone" => $req->phone,
                "phone_code" => Users::DEFAULT_PHONE_CODE,
                "fulladdress" => $req->fulladdress,
                "password" => Hash::make("0" . $req->phone),
                "role" => Users::ROLE_VENDOR_DRIVER,
                "is_driver" => 0,
                "status" => 1,
                "crt" => $now,
                "crt_by" => $req->auth->uid,
                "updt" => $now,
                "updt_by" => $req->auth->uid,
            ];
            Users::addUser($insAccount);

            $apiResp = Responses::created("success add new driver");

            DB::commit();

			$log = [
				"module" => "Driver",
				"action" => "View",
				"desc" => "Add new driver: ".$req->fullname,
			];
			UserLogs::insert(Auth::user()->id, $log);
            return new Response($apiResp, $apiResp["meta"]["code"]);
        } catch (\Exception $e) {
            Storage::disk("public")->delete($url_ktp);
            Storage::disk("public")->delete($url_npwp);
            Storage::disk("public")->delete($url_license);
            DB::rollBack();
            $apiResp = Responses::error($e->getMessage());
            return new Response($apiResp, $apiResp["meta"]["code"]);
        }
    }

    public function api_edit_driver(Request $req, $did)
    {
        $url_ktp = "";
        $url_npwp = "";
        $url_license = "";
        try {
            $now = time();

            $input = [
                "did" => $did,
                "ktp_photo" => $req->ktp_base64,
                "nik" => $req->nik,
                "fullname" => $req->fullname,
                "phone" => $req->phone,
                "email" => $req->email,
                "date_of_birth" => $req->dob,
                "age" => $req->age,
                "blood" => $req->blood,
                "home_address" => $req->fulladdress,
                "license_photo" => $req->license_base64,
                "license_number" => $req->license_number,
                "license_exp" => $req->license_exp,
                "emergency_fullname" => $req->em_fullname,
                "emergency_relationship" => $req->em_relationship,
                "emergency_phone" => $req->em_phone,
                "vendor_id" => Auth::user()->id,
            ];
            $rulesInput = [
                "did" => "required|integer|not_in:0",
                "ktp_photo" => "nullable|string",
                "nik" => "required|integer",
                "fullname" => "nullable|string|min:3|max:125", // required
                "phone" => "required|integer|not_in:0",
                "email" => "nullable|email", // required
                "date_of_birth" => "nullable|date_format:Y-m-d", // required
                "age" => "nullable|integer", // required
                "blood" => "nullable|string|max:4", // required
                "home_address" => "nullable|string|min:25", // required
                "license_photo" => "nullable|string",
                "license_number" => "nullable|numeric", // required
                "license_exp" => "nullable|date_format:Y-m-d", // required
                "emergency_fullname" => "nullable|string|min:3", // required
                "emergency_relationship" => "nullable|string", // required
                "emergency_phone" => "nullable|integer|not_in:0", // required
                "vendor_id" => "required|integer|not_in: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"]);
            }

            $driver = Drivers::showDriverById($did);
            if (count($driver) < 1) {
                $apiResp = Responses::not_found("driver not found");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            if ($req->nik) {
                $uniqNik = Drivers::getDriverByNik($req->nik);
                if (count($uniqNik) > 0) {
                    $notSameUser = 1;
                    foreach ($uniqNik as $key => $row) {
                        if ($row->id == $did) {
                            $notSameUser = 0;
                        }
                    }
                    if ($notSameUser) {
                        $apiResp = Responses::bad_request("nik has been used");
                        return new Response($apiResp, $apiResp["meta"]["code"]);
                    }
                }
            }
            if ($req->phone) {
                $uniqPhone = Drivers::getDriverByPhone($req->phone);
                if (count($uniqPhone) > 0) {
                    $notSameUser = 1;
                    foreach ($uniqPhone as $key => $row) {
                        if ($row->id == $did) {
                            $notSameUser = 0;
                        }
                    }
                    if ($notSameUser) {
                        $apiResp = Responses::bad_request("phone has been used");
                        return new Response($apiResp, $apiResp["meta"]["code"]);
                    }
                }
            }
            if ($req->email) {
                $uniqEmail = Drivers::getDriverByEmail($req->email);
                if (count($uniqEmail) > 0) {
                    $notSameUser = 1;
                    foreach ($uniqEmail as $key => $row) {
                        if ($row->id == $did) {
                            $notSameUser = 0;
                        }
                    }
                    if ($notSameUser) {
                        $apiResp = Responses::bad_request("email has been used");
                        return new Response($apiResp, $apiResp["meta"]["code"]);
                    }
                }
            }

            DB::beginTransaction();

            $updtDriver = [
                "nik" => $req->nik ? $req->nik : 0,
                "fullname" => $req->fullname,
                "email" => $req->email,
                "phone" => $req->phone,
                "phone_code" => Drivers::DEFAULT_PHONE_CODE,
                "dob" => $req->dob,
                "age" => $req->age ? $req->age : 0,
                "blood" => $req->blood,
                "fulladdress" => $req->fulladdress,
                "updt" => $now,
                "updt_by" => $req->auth->uid,
            ];
            if ($req->auth->role == Users::ROLE_VENDOR) {
                $updtDriver["vendor_id"] = $req->auth->uid;
            } else {
                $updtDriver["vendor_id"] = Auth::user()->id ?? 0;
            }
            Drivers::updateDriver($did, $updtDriver);

            if ($req->ktp_base64) {
                $url_ktp = "drivers/$did/ktp_$now.jpeg";
                if (!Storage::disk("public")->put($url_ktp, base64_decode($req->ktp_base64))) {
                    DB::rollBack();
                    $apiResp = Responses::bad_request("fail upload ktp photo");
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
                Storage::disk("public")->delete($driver[0]->ktp_img);
            }
            if ($req->npwp_base64) {
                $url_npwp = "drivers/$did/npwp_$now.jpeg";
                if (!Storage::disk("public")->put($url_npwp, base64_decode($req->npwp_base64))) {
                    Storage::disk("public")->delete($url_ktp);
                    DB::rollBack();
                    $apiResp = Responses::bad_request("fail upload npwp photo");
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
                Storage::disk("public")->delete($driver[0]->npwp_img);
            }
            if ($req->license_base64) {
                $url_license = "drivers/$did/license_$now.jpeg";
                if (!Storage::disk("public")->put($url_license, base64_decode($req->license_base64))) {
                    Storage::disk("public")->delete($url_ktp);
                    Storage::disk("public")->delete($url_npwp);
                    DB::rollBack();
                    $apiResp = Responses::bad_request("fail upload license photo");
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
                Storage::disk("public")->delete($driver[0]->license_img);
            }

            $updtDetail = [
                "npwp_string" => $req->npwp_string,
                "npwp_number" => $req->npwp_number,
                "license_number" => $req->license_number,
                "license_exp" => $req->license_exp,
                "em_fullname" => $req->em_fullname,
                "em_phone" => $req->em_phone,
                "em_relationship" => $req->em_relationship,
                "bank_id" => 1,
                "bank_code" => $req->bank_code,
                "bank_short_name" => $req->bank_short,
                "bank_name" => $req->bank_name,
                "bank_branch_name" => $req->bank_branch_name,
                "bank_acc_number" => $req->bank_acc_number,
                "bank_acc_name" => $req->bank_acc_name,
            ];
            if ($req->ktp_base64) {
                $updtDetail["ktp_img"] = $url_ktp;
            }
            if ($req->npwp_base64) {
                $updtDetail["npwp_img"] = $url_npwp;
            }
            if ($req->license_base64) {
                $updtDetail["license_img"] = $url_license;
            }
            DriversDetail::updateDetailByDid($did, $updtDetail);
            DB::commit();

            $apiResp = Responses::success("success update driver");

			$log = [
				"module" => "Driver",
				"action" => "Update",
				"desc" => "Edit driver: ".$req->fullname,
			];
			UserLogs::insert(Auth::user()->id, $log);
            return new Response($apiResp, $apiResp["meta"]["code"]);
        } catch (\Exception $e) {
            Storage::disk("public")->delete($url_ktp);
            Storage::disk("public")->delete($url_npwp);
            Storage::disk("public")->delete($url_license);
            DB::rollBack();
            $apiResp = Responses::error($e->getMessage());
            return new Response($apiResp, $apiResp["meta"]["code"]);
        }
    }

    public function api_del_driver(Request $req, $did)
    {
        try {
            $now = time();

            $input = [
                "did" => $did,
            ];
            $rulesInput = [
                "did" => "required|integer|not_in: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"]);
            }

            $driver = Drivers::showDriverById($did);
            if (count($driver) < 1) {
                $apiResp = Responses::not_found("driver not found");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            DB::beginTransaction();

            Drivers::updateDriver($did, [
                "dlt" => $now,
                "dlt_by" => $req->auth->uid,
            ]);

            // Storage::disk('public')->delete($driver[0]->ktp_img);
            // Storage::disk('public')->delete($driver[0]->npwp_img);
            // Storage::disk('public')->delete($driver[0]->license_img);

            DB::commit();

            $apiResp = Responses::success("success delete driver");

			$log = [
				"module" => "Driver",
				"action" => "Delete",
				"desc" => "Delete driver : ".$driver[0]->fullname,
			];
			UserLogs::insert(Auth::user()->id, $log);
            return new Response($apiResp, $apiResp["meta"]["code"]);
        } catch (\Exception $e) {
            DB::rollBack();
            $apiResp = Responses::error($e->getMessage());
            return new Response($apiResp, $apiResp["meta"]["code"]);
        }
    }

    public function api_search_driver_name(Request $req)
    {
        try {
            $now = time();

            $input = [
                "name" => $req->name,
            ];
            $rulesInput = [
                "name" => "required|string|max:125",
            ];

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

            $drivers = Drivers::likeName($req->name);

            if (count($drivers) < 1) {
                $apiResp = Responses::not_found("driver not found");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            $apiResp = Responses::success("success search driver by name");
            $apiResp["data"] = $drivers;

            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"]);
        }
    }

    public function api_reset_login_driver(Request $req, $did)
    {
        try {
            $now = time();

            $input = [
                "did" => $did,
            ];
            $rulesInput = [
                "did" => "required|integer|not_in: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"]);
            }

            $driver = Drivers::showDriverById($did);
            if (count($driver) < 1) {
                $apiResp = Responses::not_found("driver not found");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            DB::beginTransaction();

            DrvPhoneDevices::dltByOrdDrvId($did);

            $_dtUpdate = [
                "phone" => $driver[0]->phone,
                "password" => Hash::make("0" . $driver[0]->phone),
                "updt" => $now,
                "updt_by" => Auth::user()->id,
            ];
            DB::table("t_users")
                ->where("email", $driver[0]->email)
                ->where("status", 1)
                ->whereNull("dlt")
                ->update($_dtUpdate);

            DB::commit();

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