<?php

namespace App\Http\Modules\User;

use Auth;
use App\Models\Contract;
use App\Models\ContractLog;
use App\Models\ContractTemplate;
use App\Models\ContractObligation;

use App\Http\Modules\User\ContractObligationModule;
use App\Http\Modules\User\ContractObligationDependencyModule;

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

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

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

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

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

        return $pagination;
    }

    public static function show(Request $request, $hash_id)
    {
        $id = Hasher::decode('contracts', $hash_id);
        $user_id = Auth::guard('user-api')->user()->id;
        $contract = Contract::
            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 generate(Request $request)
    {
        $validation = ContractModule::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);

        $contract = new Contract();
        $contract->user_id = Auth::guard('user-api')->user()->id;
        $contract->contract_template_id = $contarct_template->id;
        $contract->name = $contarct_template->name;
        $contract->in_time_contract_template = json_encode($contarct_template);
        $contract->status = config('constants.contact.status.pending');
        $contract->save();

        // generate contract obligation
        $contract_template_obligation_list = $contarct_template->contract_template_obligation()
            ->orderBy('sequence', 'asc')
            ->where('status', config('constants.contract_template_obligation.status.active'))
            ->get();

        foreach ($contract_template_obligation_list as $key => $row) {
            $request->request->add([
                'contract_template_obligation_id' => [$row->hash_id],
                'contract_id' => [$contract->hash_id]
            ]);

            $contract_obligation = ContractObligationModule::generate($request);
        }

        // generate contract dependency
        foreach ($contract_template_obligation_list as $key => $row) {
            $contract_template_obligation_dependency = $row->contract_template_obligation_dependency()
            ->where('status', config('constants.contract_template_obligation_dependency.status.active'))
            ->get();

            if (!empty($contract_template_obligation_dependency[0])) {
                $contract_obligation = ContractObligation::
                    where('contract_id', $contract->id)
                    ->where('contract_template_obligation_id', $contract_template_obligation_dependency[0]->contract_template_obligation_id)
                    ->first();

                $depend_contract_obligation = ContractObligation::
                    where('contract_id', $contract->id)
                    ->where('contract_template_obligation_id', $contract_template_obligation_dependency[0]->depend_contract_template_obligation_id)
                    ->first();

                $request->request->add([
                    'contract_obligation_id' => [$contract_obligation->hash_id],
                    'depend_contract_obligation_id' => [$depend_contract_obligation->hash_id]
                ]);
                $contract_obligation_dependency = ContractObligationDependencyModule::generate($request);
            }
        }

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

        // DB::commit();

        $query_string = General::getCachePerviousQuery('contract_query');
        $data = General::returnData($contract, $query_string);

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

    public static function update(Request $request, $hash_id)
    {
        $id = Hasher::decode('contracts', $hash_id);
        $validation = ContractModule::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 = Contract::find($id);
        $contract->name = $name ?? $contract->name;
        $contract->complete_day_range = $complete_day_range ?? $contract->complete_day_range;
        $contract->update();




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

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_query');
        $data = General::returnData($contract, $query_string);

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

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

        DB::beginTransaction();

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

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

        DB::commit();

        $query_string = General::getCachePerviousQuery('contract_query');
        $data = General::returnData($contract, $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')]
            ];
        }

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

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

        $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 = Contract::find($id);
        $contract_log = new ContractLog();
        $contract_log->contract_id = $contract->id;
        $contract_log->history = json_encode($contract);
        $contract_log->remark = $remark;
        $contract_log->save();
    }
}
