<?php

namespace App\Http\Modules\User;

use Auth;
use App\Models\Entity;
use App\Models\EntityLog;

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

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

        $query = Entity::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
        ];

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

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

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

        return $pagination;
    }

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

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

        DB::beginTransaction();

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

        $entity = new Entity();
        $entity->user_id = Auth::guard('user-api')->user()->id;
        $entity->name = $name;
        $entity->status = config('constants.entity.status.active');
        $entity->save();

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

        DB::commit();

        $query_string = General::getCachePerviousQuery('entity_query');
        $data = General::returnData($entity, $query_string);

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

    public static function update(Request $request, $hash_id)
    {
        $id = Hasher::decode('entities', $hash_id);
        $validation = EntityModule::validation($request, $hash_id, 'PUT');
        if (!$validation->status) {
            return response()->json($validation, 422);
        }

        DB::beginTransaction();

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

        $entity = Entity::find($id);
        $entity->name = $name ?? $entity->name;
        $entity->update();

        // log
        EntityModule::makeLog($entity->id, 'user (' . Auth::guard('user-api')->user()->id . ') updated');

        DB::commit();

        $query_string = General::getCachePerviousQuery('entity_query');
        $data = General::returnData($entity, $query_string);

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

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

        DB::beginTransaction();

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

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

        DB::commit();

        $query_string = General::getCachePerviousQuery('entity_query');
        $data = General::returnData($entity, $query_string);

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


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

        if ($method == 'POST') {
            $rule = [
                'name' => 'required',
            ];
        }

        if ($method == 'PUT') {
            $data['id'] = $id;
            $rule = [
                'id' => [new UnderCheck('entity'), new ExistCheck('entity')],
                'name' => 'required',
            ];
        }

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

    public static function makeLog($id = '', $remark = '') 
    {
        $entity = Entity::find($id);
        $entity_log = new EntityLog();
        $entity_log->entity_id = $entity->id;
        $entity_log->history = json_encode($entity);
        $entity_log->remark = $remark;
        $entity_log->save();
    }
}
