<?php

namespace App\Http\Modules\User;

use Auth;
use App\Models\EntitySignature;
use App\Models\EntitySignatureLog;
use App\Models\Entity;

use App\Http\Modules\User\EntityModule;

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

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

        $query = EntitySignature::query();

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

        $user_id = Auth::guard('user-api')->user()->id;
        $query->whereHas('entity', function($q) use ($user_id){
            $q->where('user_id', $user_id);
        });

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

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

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

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

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

        return $pagination;
    }

    public static function show(Request $request, $hash_id)
    {
        $id = Hasher::decode('entity_signatures', $hash_id);
        $user_id = Auth::guard('user-api')->user()->id;
        $entity_signature = EntitySignature::
            where('id', $id)
            ->whereHas('entity', function($q) use ($user_id){
                $q->where('user_id', $user_id);
            })
            ->first();
        if ($entity_signature) {
            $data = General::returnData($entity_signature, '');
            return response()->json($data);
        }
        $data = General::returnNotFoundData();
        return response()->json($data);
    }

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

        DB::beginTransaction();

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

        $name = $request->input('name');
        $type = $request->input('type');

        $entity_signature = new EntitySignature();
        $entity_signature->entity_id = $entity->id;
        $entity_signature->type = $type;
        $entity_signature->status = config('constants.entity.status.active');
        $entity_signature->save();

        // log
        EntityModule::makeLog($entity_signature->entity_id, 'user (' . Auth::guard('user-api')->user()->id . ') sugnature created');

        DB::commit();

        $query_string = General::getCachePerviousQuery('entity_signature_query');
        $data = General::returnData($entity_signature, $query_string);

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

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

        DB::beginTransaction();

        $entity_signature = EntitySignature::find($id);
        $entity_signature->status = config('constants.entity.status.delete');
        $entity_signature->update();

        // log
        EntityModule::makeLog($entity_signature->entity_id, 'user (' . Auth::guard('user-api')->user()->id . ') sugnature delete');

        DB::commit();

        $query_string = General::getCachePerviousQuery('entity_signature_query');
        $data = General::returnData($entity_signature, $query_string);

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


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

        if ($method == 'POST') {
            $rule = [
                'entity_id' => ['required', new UnderCheck('entity'), new ExistCheck('entity')],
                'type' => 'required|numeric|gt:-1'
            ];
        }

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

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