<?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 ConfDistributionController extends Controller
{
    /**
     * View
     */

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

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

    /**
     * API
     */

    public function api_add_distribution_category(Request $req)
    {
        try {
            $now = time();
			// new or edit
			$tipe = $req->tipe ?? "new";

            $input = [
                "dc_code" => $req->dc_code,
                "dc_name" => $req->dc_name,
            ];
            $rulesInput = [
                "dc_code" => "required|string|max:10",
                "dc_name" => "required|string|max:100",
            ];

            // 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($tipe == "new"){
            	$uniqCode = DB::select("SELECT * FROM t_conf_distribution_category WHERE dc_code = ?", [$req->dc_code]);
			}
			if($tipe == "edit"){
				$uniqCode = DB::select("SELECT * FROM t_conf_distribution_category WHERE dc_code = ? AND id != ?", [$req->dc_code, $req->id]);
			}
            if (count($uniqCode) > 0) {
                $apiResp = Responses::bad_request("type code has been used");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            DB::beginTransaction();

			$insD = [
				"dc_code" => $req->dc_code,
				"dc_name" => $req->dc_name,
                "crt" => $now,
                "crt_by" => $req->auth->uid,
                "updt" => $now,
                "updt_by" => $req->auth->uid,
			];
			// $insQ = DB::insert("INSERT
			// 	INTO t_conf_distribution_category (dc_code, dc_name, crt, crt_by, updt, updt_by)
			// 	VALUES (?, ?, ?, ?, ?, ?)
			// ", array_values($insD));
			$insQ = DB::insert("INSERT into t_conf_distribution_category set
					dc_code = ?,
					dc_name = ?,
					crt = ?,
					crt_by = ?,
					updt = ?,
					updt_by = ?
				on duplicate key update
					dc_code = values(dc_code),
					dc_name = values(dc_name),
					updt = values(updt),
					updt_by = values(updt_by)					
			", array_values($insD));


            $apiResp = Responses::created("success " . ($tipe == "new" ? "add new" : "edit") . " distribution category");

            DB::commit();

			$log = [
				"module" => "Distribution Category",
				"action" => "".($tipe == "new" ? "Create" : "Update")."",
				"desc" => "".($tipe == "new" ? "Add new" : "Update")." distribution category: ".$req->dc_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_list_distribution_category(Request $req)
    {
        try {
            $now = time();

            $list = DB::select("SELECT * FROM t_conf_distribution_category WHERE dlt IS NULL ORDER BY dc_code ASC");
			foreach ($list as $key => $row) {
                $list[$key]->DT_RowIndex = $key + 1;
                $list[$key]->action = "-";
            }

            $apiResp = Responses::success("success list distribution category");
            $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_distribution_category(Request $req, $id)
    {
        try {
            $input = [
                "id" => $id,
            ];
            $rulesInput = [
                "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"]);
            }

			$dtl = DB::select("SELECT * FROM t_conf_distribution_category WHERE id = ? AND dlt IS NULL limit 1", [$id]);
            if (count($dtl) < 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"] = $dtl[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_del_distribution_category(Request $req, $id)
    {
        try {
            $now = time();

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

            $dtl = DB::select("SELECT * FROM t_conf_distribution_category WHERE id = ? AND dlt IS NULL limit 1", [$id]);
            if (count($dtl) < 1) {
                $apiResp = Responses::not_found("vehicle type not found");
                return new Response($apiResp, $apiResp["meta"]["code"]);
            }

            DB::beginTransaction();

			$updtQ = DB::update("UPDATE t_conf_distribution_category
				SET
					dlt = ?,
					dlt_by = ?,
					updt = ?,
					updt_by = ?
				WHERE id = ? AND dlt IS NULL
			", [1, $req->user()->id, $now, $req->user()->id, $id]);
			
            DB::commit();

            $apiResp = Responses::success("success delete vehicle type");
			
			$log = [
				"module" => "Distribution Category",
				"action" => "Delete",
				"desc" => "Delete distribution category: ".$dtl[0]->dc_name,
			];
			UserLogs::insert(Auth::user()->id, "Delete distribution category: ".$dtl[0]->dc_name);
            return new Response($apiResp, $apiResp["meta"]["code"]);
        } catch (\Exception $e) {
            DB::rollBack();
            $apiResp = Responses::error($e->getMessage());
            return new Response($apiResp, $apiResp["meta"]["code"]);
        }
    }
}
