<?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\DataTypes;

class DataTypesController extends Controller
{
	/**
	 * API
	 */

	public function api_list_dtypes(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 = DataTypes::listDataTypes($filter);
			foreach ($list as $key => $row) {
				$list[$key]->DT_RowIndex = $key + 1;
				$list[$key]->action = '-';
			}

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

			$input = [
				'dtypes_id' => $dtypes_id,
			];
			$rulesInput = [
				'dtypes_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 = DataTypes::showDataType(['dtypes_id' => $dtypes_id]);
			if (count($lgb_key) < 1) {
				$apiResp = Responses::not_found('data type key not found');
				return (new Response($apiResp, $apiResp['meta']['code']));
			}
			
			$apiResp = Responses::success('success get detail data type key');
			$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']));
		}
	}
}
