<?php

namespace App\Http\Modules\User;

use Auth;
use App\Models\ContractObligationContractDependency;
use App\Models\ContractObligation;
use App\Models\Contract;

use App\Http\Modules\User\ContractObligationModule;

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

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

    public static function list(Request $request)
    {
    	General::storeCachePerviousQuery($request->query(), 'contract_obligation_contract_dependency_query');
        
        $contract_obligation_hash_id = $contract_obligation_id = $request->get('contract_obligation_id', []);

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

        $query = ContractObligationContractDependency::query();

        if (!empty($contract_obligation_id)) {
            $contract_obligation_id = Hasher::decodeArray('contract_obligations', $contract_obligation_id);
            $query->whereIn('contract_obligation_id', $contract_obligation_id);
        }
        
        if (!empty($status) > 0) {
            $query->whereIn('status', $status);
        }

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

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

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

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

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

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

        return $pagination;
    }

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

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

        DB::beginTransaction();

        $contract_obligation_id = $request->input('contract_obligation_id');
        $contract_obligation_id = Hasher::decode('contract_obligations', $contract_obligation_id[0]);
        $contarct_template_obligation = ContractObligation::find($contract_obligation_id);

        $depend_contract_id = $request->input('depend_contract_id');
        $depend_contract_id = Hasher::decode('contracts', $depend_contract_id[0]);
        $depend_contract_template = Contract::find($depend_contract_id);

        $contract_obligation_contract_dependency = new ContractObligationContractDependency();
        $contract_obligation_contract_dependency->user_id = Auth::guard('user-api')->user()->id;
        $contract_obligation_contract_dependency->contract_obligation_id = $contarct_template_obligation->id;
        $contract_obligation_contract_dependency->depend_contract_id = $depend_contract_template->id;
        $contract_obligation_contract_dependency->status = config('constants.contract_obligation_contract_dependency.status.active');
        $contract_obligation_contract_dependency->save();

        // log
        ContractObligationModule::makeLog($contract_obligation_contract_dependency->contract_obligation_id, 'user (' . Auth::guard('user-api')->user()->id . ') created contract dependency');

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_obligation_contract_dependency_query');
        $data = General::returnData($contract_obligation_contract_dependency, $query_string);

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

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

        DB::beginTransaction();

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

        // log
        ContractObligationModule::makeLog($contract_obligation_contract_dependency->contract_obligation_id, 'user (' . Auth::guard('user-api')->user()->id . ') dependency deleted');

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_obligation_contract_dependency_query');
        $data = General::returnData($contract_obligation_contract_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_obligation_id' => [
                    'required', 
                    new UnderCheck('contract_obligation'), 
                    new ExistCheck('contract_obligation'),
                ],
                'depend_contract_id' => [
                    'required', 
                    new UnderCheck('contract'), 
                    new ExistCheck('contract'),
                    // new ContractObligationContractDependencyCheck($data['contract_obligation_id'] ?? [])
                ],
            ];
        }

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