<?php

namespace App\Http\Modules\User;

use Auth;
use App\Models\ContractTemplateObligationContractTemplateDependency;
use App\Models\ContractTemplateObligation;
use App\Models\ContractTemplate;

use App\Http\Modules\User\ContractTemplateObligationModule;

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

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 ContractTemplateObligationContractTemplateDependencyModule extends BaseController
{
    public function __construct()
    {
        parent::__construct();
    }

    public static function list(Request $request)
    {
    	General::storeCachePerviousQuery($request->query(), 'contract_template_obligation_contract_template_dependency_query');
        
        $contract_template_obligation_hash_id = $contract_template_obligation_id = $request->get('contract_template_obligation_id', []);

        $name = $request->get('name', null);
        $status = $request->get('status', []);
        $page = $request->get('page', null);
        $limit = $request->get('limit', 10);

        $query = ContractTemplateObligationContractTemplateDependency::query();

        if (!empty($contract_template_obligation_id)) {
            $contract_template_obligation_id = Hasher::decodeArray('contract_template_obligations', $contract_template_obligation_id);
            $query->whereIn('contract_template_obligation_id', $contract_template_obligation_id);
        }
        
        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 = [
            'contract_template_obligation_id' => $contract_template_obligation_hash_id,
            'name' => $name,
            'status' => $status,
            'page' => $page
        ];

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

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

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

        return $pagination;
    }

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

    public static function store(Request $request)
    {
        $validation = ContractTemplateObligationContractTemplateDependencyModule::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_id = $request->input('depend_contract_template_id');
        $depend_contract_template_id = Hasher::decode('contract_templates', $depend_contract_template_id[0]);
        $depend_contract_template = ContractTemplate::find($depend_contract_template_id);

        $contract_template_obligation_contract_template_dependency = new ContractTemplateObligationContractTemplateDependency();
        $contract_template_obligation_contract_template_dependency->user_id = Auth::guard('user-api')->user()->id;
        $contract_template_obligation_contract_template_dependency->contract_template_obligation_id = $contarct_template_obligation->id;
        $contract_template_obligation_contract_template_dependency->depend_contract_template_id = $depend_contract_template->id;
        $contract_template_obligation_contract_template_dependency->status = config('constants.contract_template_obligation_contract_template_dependency.status.active');
        $contract_template_obligation_contract_template_dependency->save();

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

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_template_obligation_contract_template_dependency_query');
        $data = General::returnData($contract_template_obligation_contract_template_dependency, $query_string);

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

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

        DB::beginTransaction();

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

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

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_template_obligation_contract_template_dependency_query');
        $data = General::returnData($contract_template_obligation_contract_template_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'),
                ],
                'depend_contract_template_id' => [
                    'required', 
                    new UnderCheck('contract_template'), 
                    new ExistCheck('contract_template'),
                    // new ContractTemplateObligationContractTemplateDependencyCheck($data['contract_template_obligation_id'] ?? [])
                ],
            ];
        }

        if ($method == 'DEL') {
            $data['id'] = $id;
            $rule = [
                'id' => [new UnderCheck('contract_template_obligation_contract_template_dependency'), new ExistCheck('contract_template_obligation_contract_template_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];
        }
    }
}