<?php


namespace App\Http\Controllers\v2019;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use App\RestApiResponseCodes;
use App\Rules\AssessmentType;
use App\Rules\ComparisionItemDataType;
use App\Rules\ComparisionSource;
use App\Rules\Resource;
use Illuminate\Http\Request;
use Validator;

class Comparison extends Controller
{
    public function savedlist(Request $request)
    {
        $bodyContent = $request->getContent();
        if (!\App\Helper::isJSON($bodyContent)) {
            return response()->json([
                'status' => [
                    "code" => RestApiResponseCodes::InvalidInputsCode,
                    'message' => RestApiResponseCodes::InvalidInputsMsg
                ]
            ]);
        }
        $data = json_decode($bodyContent, true);
        $validator = Validator::make($data, [
            'resourceType' => ['required', new Resource]
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }
        $user_id = null;
        if (!empty($data['accessToken'])) {
            $e = \App\Helper::validateAccessToken($data['accessToken']);
            if (!$e['user_id']) {
                return response()->json([
                    'status' => [
                        "code" => RestApiResponseCodes::accessTokenWasExpiredOrInvalidCode,
                        'message' => RestApiResponseCodes::accessTokenWasExpiredOrInvalidMsg
                    ]
                ], 401);
            }
            $user_id = $e['user_id'];
        }
        if (isset($data['accessToken'])) {
            $cData = \App\Comparision::select('*')->where('memid', $user_id)->get();
        } else if (isset($data['memid'])) {
            $cData = \App\Comparision::select('*')->where('memid', $data['memId'])->get();
        }
        print_r($cData);
        die;
    }

    public function save(Request $request)
    {
        $memId = \App\Helper::getMemId();
        $resourceType = \App\Helper::getResourceType();
        $data = json_decode($request->getContent(), true);

        if ($resourceType == 'app') {
            $validator = Validator::make($data, [
                'item1Id' => 'required',
                'item2Id' => 'required',
                'assessmentType' => ['required', new AssessmentType],
                'source' => ['required', new ComparisionSource],
//                'fromDate' => 'required|date|date_multi_format:"Y-m-d","M-Y","Y"',
//                'toDate' => 'required|date|date_multi_format:"Y-m-d","M-Y","Y"',
            ]);
        } else {
            $validator = Validator::make($data, [
                'item1' => 'required|array',
                "item1.dataType" => ['required', new ComparisionItemDataType()],
                'item2' => 'required|array',
                "item2.dataType" => ['required', new ComparisionItemDataType],
//                'fromDate' => 'required|date|date_multi_format:"Y-m-d","M-Y","Y"',
//                'toDate' => 'required|date|date_multi_format:"Y-m-d","M-Y","Y"',
                'assessmentType' => ['required', new AssessmentType],
                'source' => ['required', new ComparisionSource],
            ]);
        }
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }
        try {
            if ($data['comparisonId'] == "") {
                //save
                if ($resourceType == 'app') {
                    $f = \App\Comparision::select('*')
                        ->where('memid', $memId)
                        ->where('item_1_id', (isset($data['item1Id']) ? $data['item1Id'] : ''))
                        ->where('item_2_id', (isset($data['item2Id']) ? $data['item2Id'] : ''))
                        ->where('comparisonName', (isset($data['compareName']) ? $data['compareName'] : ''))
                        ->count();
                } else {
                    $f = \App\Comparision::select('*')->where('memid', $memId)
                        ->where('datatype_1', (isset($data['item1']['dataType']) ? $data['item1']['dataType'] : ''))
                        ->where('datatype_2', (isset($data['item2']['dataType']) ? $data['item2']['dataType'] : ''))
                        ->where('comodityId_1', (isset($data['item1']['comodityId']) ? $data['item1']['comodityId'] : ''))
                        ->where('comodityId_2', (isset($data['item2']['comodityId']) ? $data['item2']['comodityId'] : ''))
                        ->where('regionId_1', (isset($data['item1']['regionId']) ? $data['item1']['regionId'] : ''))
                        ->where('regionId_2', (isset($data['item2']['regionId']) ? $data['item2']['regionId'] : ''))
                        ->where('relation_id_1', (isset($data['item1']['relationId']) ? $data['item1']['relationId'] : ''))
                        ->where('relation_id_2', (isset($data['item2']['relationId']) ? $data['item2']['relationId'] : ''))
                        ->where('2ndlevel_1', isset($data['item1']['2ndlevel']) ? $data['item1']['2ndlevel'] : '')
                        ->where('2ndlevel_2', isset($data['item2']['2ndlevel']) ? $data['item1']['2ndlevel'] : '')
                        ->where('comparisonName', $data['compareName'])
                        ->count();

                }
                if ($data['source'] == "Remove Comparison") {
                    return response()->json([
                        'status' => [
                            "code" => \App\RestApiResponseCodes::userNotFoundCode,
                            'message' => "No record to delete",
                        ]
                    ]);
                }
                if ($f) {
                    return response()->json([
                        'status' => [
                            "code" => \App\RestApiResponseCodes::somethingDataAlreadyExistsCode,
                            'message' => \App\RestApiResponseCodes::somethingDataAlreadyExistsMsg,
                        ]
                    ]);
                }
                \App\Comparision::insert([
                    'saved_on_time' => date("Y-m-d h:i:s"),
                    'resource' => $resourceType,
                    'periodType' => $data['assessmentType'],
                    'fromPeriod' => $data['fromDate'],
                    'toPeriod' => $data['toDate'],
                    'memId' => $memId,
                    'item_1_id' => (isset($data['item1Id']) ? $data['item1Id'] : ''),
                    'item_2_id' => (isset($data['item2Id']) ? $data['item2Id'] : ''),
                    'item_1_type' => (isset($data['item1Type']) ? $data['item1Type'] : ''),
                    'item_2_type' => (isset($data['item2Type']) ? $data['item2Type'] : ''),
                    'comparisonName' => $data['compareName'],
                    'source' => $data['source'],
                    'datatype_1' => (isset($data['item1']['dataType']) ? $data['item1']['dataType'] : ''),
                    'datatype_2' => (isset($data['item2']['dataType']) ? $data['item2']['dataType'] : ''),
                    'comodityId_1' => (isset($data['item1']['comodityId']) ? $data['item1']['comodityId'] : ''),
                    'comodityId_2' => (isset($data['item2']['comodityId']) ? $data['item2']['comodityId'] : ''),
                    'regionId_1' => (isset($data['item1']['regionId']) ? $data['item1']['regionId'] : ''),
                    'regionId_2' => (isset($data['item2']['regionId']) ? $data['item2']['regionId'] : ''),
                    'relation_id_1' => (isset($data['item1']['relationId']) ? $data['item1']['relationId'] : ''),
                    'relation_id_2' => (isset($data['item2']['relationId']) ? $data['item2']['relationId'] : ''),
                    '2ndlevel_1' => (isset($data['item1']['2ndLevel']) ? $data['item1']['2ndLevel'] : ''),
                    '2ndlevel_2' => (isset($data['item2']['2ndLevel']) ? $data['item2']['2ndLevel'] : ''),
                ]);
                return response()->json([
                    'status' => [
                        "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                        'message' => \App\RestApiResponseCodes::RequestSentSuccessfullyMsg,
                    ]
                ]);
            } else {
                if ($data['source'] == 'Remove Comparison' && !empty($data['comparisonId'])) {
                    //delete
                    $hasRec = \App\Comparision::select('*')->where('id', $data['comparisonId'])->count();
                    if (!$hasRec) {
                        return response()->json([
                            'status' => [
                                "code" => \App\RestApiResponseCodes::userNotFoundCode,
                                'message' => \App\RestApiResponseCodes::recNotFoundMsg,
                            ]
                        ]);
                    }
                    \App\Comparision::where('id', $data['comparisonId'])->where('memid', $memId)->delete();
                } else if ($data['source'] == 'Save Comparison' && !empty($data['comparisonId'])) {
                    //update
                    $hasRec = \App\Comparision::select('*')->where('memid', $memId)->where('id', $data['comparisonId'])->count();
                    if (!$hasRec) {
                        return response()->json([
                            'status' => [
                                "code" => \App\RestApiResponseCodes::userNotFoundCode,
                                'message' => \App\RestApiResponseCodes::recNotFoundMsg,
                            ]
                        ]);
                    }
                    \App\Comparision::where('id', $data['comparisonId'])
                        ->where('memid', $memId)
                        ->update([
                            'periodType' => (isset($data['assessmentType']) ? $data['assessmentType'] : ''),
                            'fromPeriod' => (isset($data['fromDate']) ? $data['fromDate'] : ''),
                            'toPeriod' => (isset($data['toDate']) ? $data['toDate'] : ''),
                            'memId' => (isset($memId) ? $memId : ''),
                            'item_1_id' => (isset($data['item1Id']) ? $data['item1Id'] : ''),
                            'item_2_id' => (isset($data['item2Id']) ? $data['item2Id'] : ''),
                            'item_1_type' => (isset($data['item1Type']) ? $data['item1Type'] : ''),
                            'item_2_type' => (isset($data['item2Type']) ? $data['item2Type'] : ''),
                            'comparisonName' => (isset($data['compareName']) ? $data['compareName'] : ''),
                            'source' => (isset($data['source']) ? $data['source'] : ''),
                            'datatype_1' => (isset($data['item1']['dataType']) ? $data['item1']['dataType'] : ''),
                            'datatype_2' => (isset($data['item2']['dataType']) ? $data['item2']['dataType'] : ''),
                            'comodityId_1' => (isset($data['item1']['comodityId']) ? $data['item1']['comodityId'] : ''),
                            'comodityId_2' => (isset($data['item2']['comodityId']) ? $data['item2']['comodityId'] : ''),
                            'regionId_1' => (isset($data['item1']['regionId']) ? $data['item1']['regionId'] : ''),
                            'regionId_2' => (isset($data['item2']['regionId']) ? $data['item2']['regionId'] : ''),
                            'relation_id_1' => (isset($data['item1']['relationId']) ? $data['item1']['relationId'] : ''),
                            'relation_id_2' => (isset($data['item2']['relationId']) ? $data['item2']['relationId'] : ''),
                            '2ndlevel_1' => (isset($data['item1']['2ndLevel']) ? $data['item1']['2ndLevel'] : ''),
                            '2ndlevel_2' => (isset($data['item2']['2ndLevel']) ? $data['item2']['2ndLevel'] : ''),
                        ]);
                }
                return response()->json([
                    'status' => [
                        "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                        'message' => \App\RestApiResponseCodes::RequestSentSuccessfullyMsg,
                    ]
                ]);
            }
        } catch (\Exception $ex) {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::somethingWentWrongCode,
                    'message' => \App\RestApiResponseCodes::somethingWentWrongMsg,
                ]
            ]);
        }
    }
}
