<?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 Validator;
use Hidehalo\Nanoid\Client as Nanoid;
use Hidehalo\Nanoid\GeneratorInterface as NanoidInterface;
use App\Responses;
use App\Helper;
use App\Models\ConfRates;
use App\Models\ConfTruckTypes;
use App\Models\Vehicles;
use App\Models\UserLogs;
use Auth;

class ConfTruckTypeController extends Controller
{
    /**
     * View
     */

    public function view_truck_types(Request $req)
    {
        $data = [];

		$log = [
			"module" => "Vehicle Type",
			"action" => "View",
			"desc" => "Open Vehicle Type menu",
		];
		UserLogs::insert(Auth::user()->id, $log);
        return view("menu_v1.configs.truck_types", $data);
    }

    /**
     * API
     */

    public function api_list_truck_types(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']);
            // }

            $list = ConfTruckTypes::listTruckTypes();
            foreach ($list as $key => $row) {
                $list[$key]->DT_RowIndex = $key + 1;
                $list[$key]->action = "-";
            }

            $apiResp = Responses::success("success list vehilce types");
            $apiResp["count"] = count($list);
            $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_truck_type(Request $req, $ttid)
    {
        try {
            $now = time();

            $input = [
                "ttid" => $ttid,
            ];
            $rulesInput = [
                "ttid" => "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"]);
            }

            $truckType = ConfTruckTypes::showTruckTypeById($ttid);
            if (count($truckType) < 1) {
                $apiResp = Responses::not_found("truck type not found");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            $apiResp = Responses::success("success get detail vehicle type");
            $apiResp["data"] = $truckType[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_truck_type(Request $req)
    {
        try {
            $now = time();

            $input = [
                "type_name" => $req->type_name,
                "max_kg" => $req->max_kg,
                "max_cbm" => $req->max_cbm,
                "max_koli" => $req->max_koli,
                "status" => $req->status,
                "publish" => $req->publish,
            ];
            $rulesInput = [
                "type_name" => "required|string",
                "max_kg" => "nullable|numeric|min:0",
                "max_cbm" => "nullable|numeric|min:0",
                "max_koli" => "nullable|numeric|min:0",
                "status" => "required|numeric|min:0",
                "publish" => "required|numeric|min: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"]);
            }

            $uniqName = ConfTruckTypes::getTruckTypeByName($req->type_name);
            if (count($uniqName) > 0) {
                $apiResp = Responses::bad_request("type name has been used");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            DB::beginTransaction();

            $type_id = ConfTruckTypes::addTypes([
                "cat_id" => Vehicles::DEFAULT_CAT_ID,
                "name" => $req->type_name,
                "desc" => $req->type_name,
                "is_active" => $req->status,
                "is_publish" => $req->publish,
                "crt" => $now,
                "crt_by" => $req->auth->uid,
                "updt" => $now,
                "updt_by" => $req->auth->uid,
            ]);

            $insTruckType = [
                "type_id" => $type_id,
                "max_kg" => $req->max_kg ?? 0,
                "max_cbm" => $req->max_cbm ?? 0,
                "max_koli" => $req->max_koli ?? 0,
                "is_active" => $req->status,
                "is_publish" => $req->publish,
                "crt" => $now,
                "crt_by" => $req->auth->uid,
                "updt" => $now,
                "updt_by" => $req->auth->uid,
            ];
            $ttid = ConfTruckTypes::addTruckType($insTruckType);

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

            DB::commit();


			$log = [
				"module" => "Vehicle Type",
				"action" => "Create",
				"desc" => "Add new vehicle type: ".$req->type_name,
			];
			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_edit_truck_type(Request $req, $ttid)
    {
        try {
            $now = time();

            $input = [
                "ttid" => $ttid,
                "type_name" => $req->type_name,
                "max_kg" => $req->max_kg,
                "max_cbm" => $req->max_cbm,
                "max_koli" => $req->max_koli,
                "status" => $req->status,
                "publish" => $req->publish,
            ];
            $rulesInput = [
                "ttid" => "required|integer|not_in:0",
                "type_name" => "required|string",
                "max_kg" => "nullable|numeric|min:0",
                "max_cbm" => "nullable|numeric|min:0",
                "max_koli" => "nullable|numeric|min:0",
                "status" => "required|numeric|min:0",
                "publish" => "required|numeric|min: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"]);
            }

            $truckType = ConfTruckTypes::showTruckTypeById($ttid);
            if (count($truckType) < 1) {
                $apiResp = Responses::not_found("truck type not found");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            $uniqName = ConfTruckTypes::getTruckTypeByName($req->type_name);
            if (count($uniqName) > 0) {
                $notSameUser = 1;
                foreach ($uniqName as $key => $row) {
                    if ($row->id == $ttid) {
                        $notSameUser = 0;
                    }
                }
                if ($notSameUser) {
                    $apiResp = Responses::bad_request("type name has been used");
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
            }

            if ($req->status == ConfTruckTypes::IS_INACTIVE) {
                $checkVhcType = ConfRates::checkVhcType($truckType[0]->type_id);
                if (count($checkVhcType) > 0) {
                    $apiResp = Responses::bad_request("cannot change to inactive, still connected on rates");
                    return new Response($apiResp, $apiResp["meta"]["code"]);
                }
            }

            DB::beginTransaction();

            ConfTruckTypes::updtTypes($truckType[0]->type_id, [
                "name" => $req->type_name,
                "desc" => $req->type_name,
                "is_active" => $req->status,
                "is_publish" => $req->publish,
                "updt" => $now,
                "updt_by" => $req->auth->uid,
            ]);

            $insTruckType = [
                "type_id" => $truckType[0]->type_id,
                "max_kg" => $req->max_kg ?? 0,
                "max_cbm" => $req->max_cbm ?? 0,
                "max_koli" => $req->max_koli ?? 0,
                "is_active" => $req->status,
                "is_publish" => $req->publish,
                "updt" => $now,
                "updt_by" => $req->auth->uid,
            ];
            $ttid = ConfTruckTypes::updateTruckType($ttid, $insTruckType);

            $apiResp = Responses::created("success update vehicle type");

            DB::commit();
			
			$log = [
				"module" => "Vehicle Type",
				"action" => "Update",
				"desc" => "Update vehicle type: ".$req->type_name,
			];
			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_del_truck_type(Request $req, $ttid)
    {
        try {
            $now = time();

            $input = [
                "ttid" => $ttid,
            ];
            $rulesInput = [
                "ttid" => "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"]);
            }

            $truckType = ConfTruckTypes::showTruckTypeById($ttid);
            if (count($truckType) < 1) {
                $apiResp = Responses::not_found("vehicle type not found");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            $checkVhcType = ConfRates::checkVhcType($truckType[0]->type_id);
            if (count($checkVhcType) > 0) {
                $apiResp = Responses::bad_request("cannot delete, still connected on rates");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            DB::beginTransaction();

            ConfTruckTypes::updtTypes($truckType[0]->type_id, [
                "dlt" => $now,
                "dlt_by" => $req->auth->uid,
            ]);

            ConfTruckTypes::updateTruckType($ttid, [
                "dlt" => $now,
                "dlt_by" => $req->auth->uid,
            ]);

            DB::commit();

            $apiResp = Responses::success("success delete vehicle type");

			$log = [
				"module" => "Vehicle Type",
				"action" => "Delete",
				"desc" => "Delete vehicle type: ".$truckType[0]->name,
			];
			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"]);
        }
    }
}
