<?php

namespace App\Http\Modules\User;

use Auth;
use App\Models\ContractTemplate;
use App\Models\ContractTemplateLog;

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

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

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

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

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

        return $pagination;
    }

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

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

        DB::beginTransaction();

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

        $contract_template = new ContractTemplate();
        $contract_template->user_id = Auth::guard('user-api')->user()->id;
        $contract_template->name = $name;
        $contract_template->complete_day_range = $complete_day_range;
        $contract_template->status = config('constants.contact_template.status.pending');
        $contract_template->save();

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

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_template_query');
        $data = General::returnData($contract_template, $query_string);

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

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

        DB::beginTransaction();

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

        $contract_template = ContractTemplate::find($id);
        $contract_template->name = $name ?? $contract_template->name;
        $contract_template->complete_day_range = $complete_day_range ?? $contract_template->complete_day_range;
        $contract_template->update();

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

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_template_query');
        $data = General::returnData($contract_template, $query_string);

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

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

        DB::beginTransaction();

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

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

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_template_query');
        $data = General::returnData($contract_template, $query_string);

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

    public static function validCheck(Request $request, $hash_id = '', $method = 'POST')
    {
        $id = $hash_id ? Hasher::decode('contract_templates', $hash_id) : '';
        $validation = ContractTemplateModule::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 = [
                'name' => 'required',
                'complete_day_range' => 'required|numeric|gt:-1'
            ];
        }

        if ($method == 'PUT') {
            $data['id'] = $id;
            $rule = [
                'id' => [new UnderCheck('contract_template'), new ExistCheck('contract_template')],
                'name' => 'required',
                'complete_day_range' => 'required|numeric|gt:-1'
            ];
        }

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

        $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_template = ContractTemplate::find($id);
        $contract_template_log = new ContractTemplateLog();
        $contract_template_log->contract_template_id = $contract_template->id;
        $contract_template_log->history = json_encode($contract_template);
        $contract_template_log->remark = $remark;
        $contract_template_log->save();
    }
}
