<?php

namespace App\Http\Modules\User;

use Auth;
use App\Models\ContractObligation;
use App\Models\ContractObligationLog;
use App\Models\Contract;
use App\Models\ContractTemplateObligation;
use App\Models\ContractEntity;

use App\Http\Modules\User\ContractModule;

use App\Http\Rules\User\UnderCheck;
use App\Http\Rules\User\ExistCheck;
use App\Http\Rules\User\ContractObligationCompleteOrAcceptCheck;
use App\Http\Rules\User\ContractObligationEntitySignatureCheck;
use App\Http\Rules\User\ContractObligationDoneCheck;
use App\Http\Rules\User\StatusCheck;

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

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

        $query = ContractObligation::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_list = $query->paginate($limit);

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

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

        return $pagination;
    }

    public static function show(Request $request, $hash_id)
    {
        $id = Hasher::decode('contract_obligations', $hash_id);
        $user_id = Auth::guard('user-api')->user()->id;
        $contract = ContractObligation::
            where('id', $id)
            ->where('user_id', $user_id)
            ->first();
        if ($contract) {
            $data = General::returnData($contract, '');
            return response()->json($data);
        }
        $data = General::returnNotFoundData();
        return response()->json($data);
    }

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

        DB::beginTransaction();

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

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

        $contract_obligation = new ContractObligation();
        $contract_obligation->user_id = Auth::guard('user-api')->user()->id;
        $contract_obligation->contract_id = $contract->id;
        $contract_obligation->contract_template_obligation_id = $contract_template_obligation->id;
        $contract_obligation->name = $contract_template_obligation->name;
        $contract_obligation->reference = $contract_template_obligation->reference;
        $contract_obligation->sequence = $contract_template_obligation->sequence;
        $contract_obligation->content = json_encode($contract_template_obligation->content);
        $contract_obligation->must_complete = $contract_template_obligation->must_complete;
        $contract_obligation->must_accept = $contract_template_obligation->must_accept;
        $contract_obligation->in_time_contract_obligation_template = json_encode($contract_template_obligation);
        $contract_obligation->type = $contract_template_obligation->type;
        $contract_obligation->status = config('constants.contract_obligation.status.active');
        $contract_obligation->save();

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

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_query');
        $data = General::returnData($contract, $query_string);

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

    public static function assignContractEntity(Request $request, $hash_id)
    {
        $id = Hasher::decode('contract_obligations', $hash_id);
        $validation = ContractObligationModule::validation($request, $hash_id, 'ASSIGN');
        if (!$validation->status) {
            return response()->json($validation, 422);
        }

        DB::beginTransaction();

        $contract_entity_id = $request->input('contract_entity_id');
        $contract_entity_id = Hasher::decode('contract_entities', $contract_entity_id[0]);
        $contract_entity = ContractEntity::find($contract_entity_id);

        $contract_obligation = ContractObligation::find($id);
        $contract_obligation->contract_entity_id = $contract_entity->id;
        $contract_obligation->update();

        // log
        ContractObligationModule::makeLog($contract_obligation->id, 'user (' . Auth::guard('user-api')->user()->id . ') assigned contract entity');

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_obligation_query');
        $data = General::returnData($contract_obligation, $query_string);

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

    public static function updateComplete(Request $request, $hash_id)
    {
        $id = Hasher::decode('contract_obligations', $hash_id);
        $validation = ContractObligationModule::validation($request, $hash_id, 'COMPLETE');
        if (!$validation->status) {
            return response()->json($validation, 422);
        }

        DB::beginTransaction();
        
        $contract_obligation = ContractObligation::find($id);
        $contract_obligation->complete_status = config('constants.contract_obligation.complete_status.completed');
        $contract_obligation->completed_at = Carbon::now();
        $contract_obligation->update();

        // log
        ContractObligationModule::makeLog($contract_obligation->id, 'user (' . Auth::guard('user-api')->user()->id . ') complete status updated');

        ContractObligationModule::updateDone($request, $hash_id);

        $contract_obligation = ContractObligation::find($id);
        
        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_obligation_query');
        $data = General::returnData($contract_obligation, $query_string);

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

    public static function updateAccept(Request $request, $hash_id)
    {
        $id = Hasher::decode('contract_obligations', $hash_id);
        $validation = ContractObligationModule::validation($request, $hash_id, 'ACCEPT');
        if (!$validation->status) {
            return response()->json($validation, 422);
        }

        DB::beginTransaction();

        $contract_obligation = ContractObligation::find($id);
        $contract_obligation->accept_status = config('constants.contract_obligation.accept_status.accepted');
        $contract_obligation->update();

        // log
        ContractObligationModule::makeLog($contract_obligation->id, 'user (' . Auth::guard('user-api')->user()->id . ') accept status updated');

        ContractObligationModule::updateDone($request, $hash_id);

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_obligation_query');
        $data = General::returnData($contract_obligation, $query_string);

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

    public static function updateDone(Request $request, $hash_id)
    {
        $id = Hasher::decode('contract_obligations', $hash_id);
        $validation = ContractObligationModule::validation($request, $hash_id, 'DONE');
        if (!$validation->status) {
            return response()->json($validation, 422);
        }
        DB::beginTransaction();

        $contract_obligation = ContractObligation::find($id);
        $contract_obligation->status = config('constants.contract_obligation.status.done');
        $contract_obligation->update();

        // log
        ContractObligationModule::makeLog($contract_obligation->id, 'user (' . Auth::guard('user-api')->user()->id . ') done status updated');

        ContractModule::updateDone($request, $contract_obligation->contract_hash_id);

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_obligation_query');
        $data = General::returnData($contract_obligation, $query_string);

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

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

        if ($method == 'POST') {
           
        }

        if ($method == 'ASSIGN') {
            $data['id'] = $id;
            $rule = [
                'id' => [new UnderCheck('contract_obligation'), new ExistCheck('contract_obligation')],
                'contract_entity_id' => ['required', new UnderCheck('contract_entity'), new ExistCheck('contract_entity')]
            ];
        }

        if ($method == 'COMPLETE') {
            $data['id'] = $id;
            $rule = [
                'id' => [
                    new UnderCheck('contract_obligation'), 
                    new ExistCheck('contract_obligation'), 
                    new ContractObligationCompleteOrAcceptCheck('complete'),
                    new StatusCheck('contract_obligation', [config('constants.contract_obligation.status.active')])

                ],
                'entity_signature_id' => ['required', new ContractObligationEntitySignatureCheck($data['id'] ?? '')]
            ];
        }

        if ($method == 'ACCEPT') {
            $data['id'] = $id;
            $rule = [
                'id' => [
                    new UnderCheck('contract_obligation'), 
                    new ExistCheck('contract_obligation'), 
                    new ContractObligationCompleteOrAcceptCheck('accept'),
                    new StatusCheck('contract_obligation', [config('constants.contract_obligation.status.active')])

                ],
                'entity_signature_id' => ['required', new ContractObligationEntitySignatureCheck($data['id'] ?? '')]
            ];
        }

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

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

        $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];
        }
    }

    public static function makeLog($id = '', $remark = '') 
    {
        $contract_obligation = ContractObligation::find($id);
        $contract_obligation_log = new ContractObligationLog();
        $contract_obligation_log->contract_obligation_id = $contract_obligation->id;
        $contract_obligation_log->history = json_encode($contract_obligation);
        $contract_obligation_log->remark = $remark;
        $contract_obligation_log->save();
    }
}
