<?php

namespace App\Http\Modules\User;

use Auth;
use App\Models\ContractTemplateObligation;
use App\Models\ContractTemplateObligationLog;
use App\Models\ContractTemplate;

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

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

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

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

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

        return $pagination;
    }

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

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

        DB::beginTransaction();

        $contract_template_id = $request->input('contract_template_id');
        $contract_template_id = Hasher::decode('contract_templates', $contract_template_id[0]);
        $contarct_template = ContractTemplate::find($contract_template_id);

        $name = $request->input('name');
        $sequence = $request->input('sequence');
        $reference = $request->input('reference');
        $content = $request->input('content');
        $must_complete = $request->input('must_complete');
        $must_accept = $request->input('must_accept');
        $complete_day_range = $request->input('complete_day_range');
        $type = $request->input('type');

        $contract_template_obligation = new ContractTemplateObligation();
        $contract_template_obligation->contract_template_id = $contarct_template->id;
        $contract_template_obligation->user_id = Auth::guard('user-api')->user()->id;
        $contract_template_obligation->sequence = $sequence;
        $contract_template_obligation->reference = $reference;
        $contract_template_obligation->content = json_encode($content);
        $contract_template_obligation->must_complete = $must_complete;
        $contract_template_obligation->must_accept = $must_accept;
        $contract_template_obligation->complete_day_range = $complete_day_range;
        $contract_template_obligation->type = $type;
        $contract_template_obligation->status = config('constants.contract_template_obligation.status.pending');
        $contract_template_obligation->save();

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

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_template_obligation_query');
        $data = General::returnData($contract_template_obligation, $query_string);

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

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

        DB::beginTransaction();

        $name = $request->input('name');
        $sequence = $request->input('sequence');
        $reference = $request->input('reference');
        $content = $request->input('content');
        $must_complete = $request->input('must_complete');
        $must_accept = $request->input('must_accept');
        $complete_day_range = $request->input('complete_day_range');
        $type = $request->input('type');

        $contract_template_obligation = ContractTemplateObligation::find($id);
        $contract_template_obligation->name = $name ?? $contract_template_obligation->name;
        $contract_template_obligation->sequence = $sequence ?? $contract_template_obligation->sequence;
        $contract_template_obligation->reference = $reference ?? $contract_template_obligation->reference;
        $contract_template_obligation->content = json_encode($content) ?? json_encode($contract_template_obligation->content);
        $contract_template_obligation->must_complete = $must_complete ?? $contract_template_obligation->must_complete;
        $contract_template_obligation->must_accept = $must_accept ?? $contract_template_obligation->must_accept;
        $contract_template_obligation->complete_day_range = $complete_day_range ?? $contract_template_obligation->complete_day_range;
        $contract_template_obligation->type = $type ?? $contract_template_obligation->type;
        $contract_template_obligation->update();

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

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_template_obligation_query');
        $data = General::returnData($contract_template_obligation, $query_string);

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

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

        DB::beginTransaction();

        $contract_template_obligation = ContractTemplateObligation::find($id);
        $contract_template_obligation->status = config('constants.contract_template_obligation.status.delete');
        $contract_template_obligation->update();

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

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_template_obligation_query');
        $data = General::returnData($contract_template_obligation, $query_string);

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


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

        if ($method == 'POST') {
            $rule = [
                'contract_template_id' => ['required', new UnderCheck('contract_template'), new ExistCheck('contract_template')],
                'name' => 'required',
                'sequence' => 'required|numeric|gt:-1',
                'reference' => '',
                'content' => '',
                'must_complete' => '',
                'must_accept' => '',
                'complete_day_range' => 'required|numeric|gt:-1',
                'type' => 'required',
            ];
        }

        if ($method == 'PUT') {
            $data['id'] = $id;
            $rule = [
                'id' => [new UnderCheck('contract_template_obligation'), new ExistCheck('contract_template_obligation')],
                'name' => '',
                'sequence' => 'nullable|numeric|gt:-1',
                'reference' => '',
                'content' => '',
                'must_complete' => '',
                'must_accept' => '',
                'complete_day_range' => 'nullable|numeric|gt:-1',
                'type' => '',
            ];
        }

        if ($method == 'DEL') {
            $data['id'] = $id;
            $rule = [
                'id' => [new UnderCheck('contract_template_obligation'), new ExistCheck('contract_template_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_template_obligation = ContractTemplateObligation::find($id);
        $contract_template_obligation_log = new ContractTemplateObligationLog();
        $contract_template_obligation_log->contract_template_obligation_id = $contract_template_obligation->id;
        $contract_template_obligation_log->history = json_encode($contract_template_obligation);
        $contract_template_obligation_log->remark = $remark;
        $contract_template_obligation_log->save();
    }
}
