<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Validator;
use App\Responses;
use App\Helper;
use App\Models\LogbookTypes;
use App\Models\LogbookKeys;
use App\Models\DataTypes;

class LogbookKeysController extends Controller
{
	/**
	 * View
	 */

	public function view_lgb_keys(Request $req)
	{
		$data = [
			'types' => LogbookTypes::listLgbTypes(['is_active' => LogbookTypes::IS_ACTIVE]),
			'dtypes' => DataTypes::listDataTypes(['is_active' => DataTypes::IS_ACTIVE]),
		];

		return view('menu_v1.logbook_keys', $data);
	}


	/**
	 * API
	 */

	public function api_list_lgb_keys(Request $req)
	{
		try {
			$now = time();
			$input = [
				'cptid' => $req->cptid,
				'is_active' => $req->is_active,
			];
			$rulesInput = [
				'cptid' => 'nullable|numeric',
				'is_active' => 'nullable|numeric',
			];

			// 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 ($input['cptid'] != null && $input['cptid'] != 0) {
				$filter['cptid'] = $input['cptid'];
			}
			if ($input['is_active'] != null && $input['is_active'] != 0) {
				$filter['is_active'] = $input['is_active'];
			}

			$list = LogbookKeys::listLgbKeys($filter);
			foreach ($list as $key => $row) {
				$list[$key]->DT_RowIndex = $key + 1;
				$list[$key]->action = '-';
			}

			$apiResp = Responses::success('success list lgb_keys');
			$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_lgb_key(Request $req, $lgb_key_id)
	{
		try {
			$now = time();

			$input = [
				'lgb_key_id' => $lgb_key_id,
			];
			$rulesInput = [
				'lgb_key_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']);
			}

			$lgb_key = LogbookKeys::showLgbKey(['lgb_key_id' => $lgb_key_id]);
			if (count($lgb_key) < 1) {
				$apiResp = Responses::not_found('logbook master not found');
				return (new Response($apiResp, $apiResp['meta']['code']));
			}
			
			$apiResp = Responses::success('success get detail logbook master');
			$apiResp['data'] = $lgb_key[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_lgb_key(Request $req)
	{
		try {
			$now = time();

			$input = [
				'name' => $req->add_name,
				'type' => $req->add_type,
				'keys' => $req->add_keys,
				'units' => $req->add_units,
				'dtypes' => $req->add_dtypes,
				'status' => $req->status,
			];
			$rulesInput = [
				'name' => 'required|string|max:255',
				'type' => 'required|numeric|min:0',
				'keys' => 'required|array',
				'units' => 'required|array',
				'dtypes' => 'required|array',
				'status' => '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']);
			}

			DB::beginTransaction();

			$insLgbKey = [
				'name' => $input['name'],
				'type' => $input['type'],
				'keys' => json_encode($input['keys']),
				'units' => json_encode($input['units']),
				'dtypes' => json_encode($input['dtypes']),
				'is_active' => $input['status'],
				'crt' => $now,
				'crt_by' => $req->auth->uid,
				'updt' => $now,
				'updt_by' => $req->auth->uid,
			];
			$lgb_key_id = LogbookKeys::addLgbKey($insLgbKey);

			$apiResp = Responses::created('success add new logbook master');

			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_edit_lgb_key(Request $req, $lgb_key_id)
	{
		try {
			$now = time();

			$input = [
        'lgb_key_id' => $lgb_key_id,
				'name' => $req->updt_name,
				'type' => $req->updt_type,
				'keys' => $req->updt_keys,
				'units' => $req->updt_units,
				'dtypes' => $req->updt_dtypes,
				'status' => $req->status,
			];
			$rulesInput = [
        'lgb_key_id' => 'required|integer|not_in:0',
				'name' => 'required|string|max:255',
				'type' => 'required|numeric|min:0',
				'keys' => 'required|array',
				'units' => 'required|array',
				'dtypes' => 'required|array',
				'status' => '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']);
			}

			$lgb_key = LogbookKeys::showLgbKey(['lgb_key_id' => $lgb_key_id]);
			if (count($lgb_key) < 1) {
				$apiResp = Responses::not_found('logbook master not found');
				return (new Response($apiResp, $apiResp['meta']['code']));
			}

			DB::beginTransaction();

			$updtPocket = [
				'name' => $input['name'],
				'type' => $input['type'],
				'keys' => json_encode($input['keys']),
				'units' => json_encode($input['units']),
				'dtypes' => json_encode($input['dtypes']),
				'is_active' => $input['status'],
				'updt' => $now,
				'updt_by' => $req->auth->uid,
			];
			LogbookKeys::updateLgbKey($input['lgb_key_id'], $updtPocket);

			$apiResp = Responses::created('success update logbook master');

			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_del_lgb_key(Request $req, $lgb_key_id)
	{
		try {
			$now = time();

			$input = [
				'lgb_key_id' => $lgb_key_id,
			];
			$rulesInput = [
				'lgb_key_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']);
			}

			$lgb_key = LogbookKeys::showLgbKey(['lgb_key_id' => $lgb_key_id]);
			if (count($lgb_key) < 1) {
				$apiResp = Responses::not_found('logbook master not found');
				return (new Response($apiResp, $apiResp['meta']['code']));
			}

			DB::beginTransaction();

			LogbookKeys::updateLgbKey($lgb_key_id, [
				'dlt' => $now,
				'dlt_by' => $req->auth->uid,
			]);

			DB::commit();
			
			$apiResp = Responses::success('success delete logbook master');
			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_selection_lgb_keys(Request $req)
	{
		try {
			$now = time();
			$input = [
				'is_active' => $req->is_active,
			];
			$rulesInput = [
				'is_active' => 'nullable|numeric',
			];

			// 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 ($input['is_active'] != null && $input['is_active'] != 0) {
				$filter['is_active'] = $input['is_active'];
			}

			$list = LogbookKeys::listLgbKeys($filter);
			foreach ($list as $key => $row) {
				$list[$key]->DT_RowIndex = $key + 1;
				$list[$key]->action = '-';
			}

			$apiResp = Responses::success('success list logbook master');
			$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']));
		}
	}
}
