<?php

namespace App\Http\Modules\User;

use Auth;
use App\Models\ContractEntity;
use App\Models\Contract;
use App\Models\Entity;

use App\Http\Modules\User\ContractModule;

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

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

    public static function list(Request $request)
    {
    	General::storeCachePerviousQuery($request->query(), 'contract_entity_query');
     
        $contract_hash_id = $contract_id = $request->get('contract_id', []);

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

        $query = ContractEntity::query();

        if (!empty($contract_id)) {
            $contract_id = Hasher::decodeArray('contracts', $contract_id);
            $query->whereIn('contract_id', $contract_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_id' => $contract_hash_id,
            'status' => $status,
            'page' => $page
        ];

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

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

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

        return $pagination;
    }

    public static function show(Request $request, $hash_id)
    {
        $id = Hasher::decode('contract_entities', $hash_id);
        $user_id = Auth::guard('user-api')->user()->id;
        $contract = ContractEntity::
            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 store(Request $request)
    {
        $validation = ContractEntityModule::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]);
        $contarct = Contract::find($contract_id);

        $entity_id = $request->input('entity_id');
        $entity_id = Hasher::decode('entities', $entity_id);
        $entity = Entity::find($entity_id);

        $contract_entity = new ContractEntity();
        $contract_entity->user_id = Auth::guard('user-api')->user()->id;
        $contract_entity->contract_id = $contarct->id;
        $contract_entity->entity_id = $entity->id;
        $contract_entity->entity_signature_id = $entity->entity_signature()->first()->id;
        $contract_entity->status = config('constants.contact_entity.status.active');
        $contract_entity->save();

        // log
        ContractModule::makeLog($contract_entity->contract_id, 'user (' . Auth::guard('user-api')->user()->id . ') contact entity created');

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_entity_query');
        $data = General::returnData($contract_entity, $query_string);

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

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

        DB::beginTransaction();

        $contract_entity = ContractEntity::find($id);
        $contract_entity->status = config('constants.contact_entity.status.delete');
        $contract_entity->update();

        // log
        ContractModule::makeLog($contract_entity->contract_id, 'user (' . Auth::guard('user-api')->user()->id . ') contact entity  deleted');

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_entity_query');
        $data = General::returnData($contract_entity, $query_string);

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

    public static function validCheck(Request $request, $hash_id = '', $method = 'POST')
    {
        $id = $hash_id ? Hasher::decode('contracts', $hash_id) : '';
        $validation = ContractEntityModule::validation($request, $id, $method);
        if (!$validation->status) {
            return response()->json($validation, 422);
        }
    }

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

        if ($method == 'POST') {
            $rule = [
                'contract_id' => ['required', new UnderCheck('contract'), new ExistCheck('contract')],
                'entity_id' => ['required', new UnderCheck('entity'), new ExistCheck('entity')]
            ];
        }

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

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