<?php

namespace App\Http\Modules\User;

use Auth;
use App\Models\ContractTemplateObligationDependency;
use App\Models\ContractTemplateObligation;

use App\Http\Modules\User\ContractTemplateObligationModule;

use App\Http\Rules\User\UnderCheck;
use App\Http\Rules\User\ExistCheck;
use App\Http\Rules\User\ContractTemplateObligationDependencyCheck;

use App\Http\Helpers\General;
use App\Http\Helpers\Hasher;
use Carbon\Carbon;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

use App\Http\Controllers\User\BaseController;

class ContractTemplateObligationDependencyModule extends BaseController
{
    public function __construct()
    {
        parent::__construct();
    }

    public static function list(Request $request)
    {
    	General::storeCachePerviousQuery($request->query(), 'contract_template_obligation_dependency_query');
     
        $name = $request->get('name', null);
        $status = $request->get('status', []);
        $page = $request->get('page', null);
        $limit = $request->get('limit', 10);

        $query = ContractTemplateObligationDependency::query();

         if (strlen($name) > 0) {
            $query->where('name', 'like', '%' . $name . '%');
        }

        if (!empty($status) > 0) {
            $query->whereIn('status', $status);
        }

        $query->where('user_id', Auth::guard('user-api')->user()->id);

        $query->orderBy('id', 'desc');

        $params = [
            'name' => $name,
            'status' => $status,
            'page' => $page
        ];

        $contract_template_obligation_dependency_list = $query->paginate($limit);

        $extract = [];
        foreach ($contract_template_obligation_dependency_list as $key => $row) {
            $extract[] = $row;

        }
        $pagination = General::paginationGenerator($contract_template_obligation_dependency_list, $params, $extract);

        return $pagination;
    }

    public static function show(Request $request, $hash_id)
    {
        $id = Hasher::decode('contract_template_obligation_dependencies', $hash_id);
        $contract_template_obligation_dependency = ContractTemplateObligationDependency::find($id);
        if ($contract_template_obligation_dependency) {
            $data = General::returnData($contract_template_obligation_dependency, '');
            return response()->json($data);
        }
        $data = General::returnNotFoundData();
        return response()->json($data);
    }

    public static function store(Request $request)
    {
        $validation = ContractTemplateObligationDependencyModule::validation($request);
        if (!$validation->status) {
            return response()->json($validation, 422);
        }

        DB::beginTransaction();

        $contract_template_obligation_id = $request->input('contract_template_obligation_id');
        $contract_template_obligation_id = Hasher::decode('contract_template_obligations', $contract_template_obligation_id[0]);
        $contarct_template_obligation = ContractTemplateObligation::find($contract_template_obligation_id);

        $depend_contract_template_obligation_id = $request->input('depend_contract_template_obligation_id');
        $depend_contract_template_obligation_id = Hasher::decode('contract_template_obligations', $depend_contract_template_obligation_id[0]);
        $depend_contract_template_obligation = ContractTemplateObligation::find($depend_contract_template_obligation_id);

        $contract_template_obligation_dependency = new ContractTemplateObligationDependency();
        $contract_template_obligation_dependency->user_id = Auth::guard('user-api')->user()->id;
        $contract_template_obligation_dependency->contract_template_obligation_id = $contarct_template_obligation->id;
        $contract_template_obligation_dependency->depend_contract_template_obligation_id = $depend_contract_template_obligation->id;
        $contract_template_obligation_dependency->status = config('constants.contract_template_obligation_dependency.status.active');
        $contract_template_obligation_dependency->save();

        // log
        ContractTemplateObligationModule::makeLog($contract_template_obligation_dependency->contract_template_obligation_id, 'user (' . Auth::guard('user-api')->user()->id . ') created dependency');

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_template_obligation_dependency_query');
        $data = General::returnData($contract_template_obligation_dependency, $query_string);

        return response()->json($data);
    }

    public static function delete(Request $request, $hash_id)
    {
        $id = Hasher::decode('contract_template_obligation_dependencies', $hash_id);
        $validation = ContractTemplateObligationDependencyModule::validation($request, $hash_id, 'DEL');
        if (!$validation->status) {
            return response()->json($validation, 422);
        }

        DB::beginTransaction();

        $contract_template_obligation_dependency = ContractTemplateObligationDependency::find($id);
        $contract_template_obligation_dependency->status = config('constants.contract_template_obligation_dependency.status.delete');
        $contract_template_obligation_dependency->update();

        // log
        ContractTemplateObligationModule::makeLog($contract_template_obligation_dependency->contract_template_obligation_id, 'user (' . Auth::guard('user-api')->user()->id . ') delete dependency');

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_template_obligation_dependency_query');
        $data = General::returnData($contract_template_obligation_dependency, $query_string);

        return response()->json($data);
    }


    private static function validation(Request $request, $id = '', $method = 'POST')
    {
        $data = $request->all();
        $rule= [];

        if ($method == 'POST') {
            $rule = [
                'contract_template_obligation_id' => [
                    'required', 
                    new UnderCheck('contract_template_obligation'), 
                    new ExistCheck('contract_template_obligation'),
                    new ContractTemplateObligationDependencyCheck($data['depend_contract_template_obligation_id'] ?? [])
                ],
                'depend_contract_template_obligation_id' => [
                    'required', 
                    new UnderCheck('contract_template_obligation'), 
                    new ExistCheck('contract_template_obligation')
                ],
            ];
        }

        if ($method == 'DEL') {
            $data['id'] = $id;
            $rule = [
                'id' => [new UnderCheck('contract_template_obligation_dependency'), new ExistCheck('contract_template_obligation_dependency')],
            ];
        }

        $validator = Validator::make($data, $rule, config('error_code'));

        $errors = $validator->errors();

        if ($validator->fails()) {
            $data = General::returnErrorData($errors);
            return $data;
        }
        else {
            return (object)['status' => true];
        }
    }
}
