<?php

namespace App\Core\Service;

use App\Core\Repository\OfferFactMapping\OfferFactMappingRepository;
use App\Core\Validator\OfferFactMapping\OfferFactMappingCreateValidator;
use App\Core\Validator\OfferFactMapping\OfferFactMappingAddValidator;
use App\Core\Service\PropertyFactService;

use App;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Exceptions\ApiErrorException;

class OfferFactMappingService
{

    private $offerFactMappingRepository;
    private $offerFactMappingCreateValidator;
    private $offerFactMappingAddValidator;
    private $propertyFactService;


    public function __construct(

        OfferFactMappingRepository $offerFactMappingRepository,
        OfferFactMappingCreateValidator $offerFactMappingCreateValidator,
        OfferFactMappingAddValidator $offerFactMappingAddValidator,
        PropertyFactService $propertyFactService
    )
    {
        $this->offerFactMappingRepository = $offerFactMappingRepository;
        $this->offerFactMappingCreateValidator = $offerFactMappingCreateValidator;
        $this->offerFactMappingAddValidator = $offerFactMappingAddValidator;
        $this->propertyFactService = $propertyFactService;
    }

    public function create($param = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $validationResult = $this->offerFactMappingCreateValidator->validate($param);

            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }

            $insertData =
                [
                    "offer_id" => fillOnUndefined($param, "offer_id"),
                    "category_id" => fillOnUndefined($param, "category_id"),
                    "property_fact_parent_id" => fillOnUndefined($param, "property_fact_parent_id"),
                    "property_fact_id" => fillOnUndefined($param, "property_fact_id"),

                    "status" => fillOnUndefined($param, "status", 0),
                    "created_by" => fillOnUndefined($param, "created_by"),
                    "updated_by" => fillOnUndefined($param, "updated_by"),
                    "created_at" => time(),
                    "updated_at" => time(),
                ];

            $userCreateResult = $this->offerFactMappingRepository->create($insertData);
            if ($userCreateResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $userData = $userCreateResult["data"];
            $response = [
                'status' => true,
                'data' => $userData,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function select($param = [], $column = ['*'])
    {

        $response = ['status' => -1, 'message' => '', 'data' => null];

        try {

            $data = $this->offerFactMappingRepository->findByCriteria($param, $column);

            $response = [
                'status' => true,
                'data' => $data,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = $e->getMessage();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function update($id, $param = [])
    {

        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $updateResult = $this->offerFactMappingRepository->update($id, $param);
            if ($updateResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $updateData = $updateResult["data"];
            $response = [
                'status' => true,
                'data' => $updateData,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function updateOrCreate($criteria = [], $saveData = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];

        try {

            $data = $this->offerFactMappingRepository->updateOrCreate($criteria, $saveData);
            $response = [
                'status' => true,
                'data' => $data,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = $e->getMessage();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);


    }

    public function insertNewOfferFacts($param = [])
    {

        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $validationResult = $this->offerFactMappingAddValidator->validate($param);

            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }

            $propertyFactsCheckParam = [
                'fact_ids' => $param['fact_mapping'],
                'property_id' => $param['property_id']
            ];
            $propertyFactsCheck  = $this->propertyFactService->checkPropertyFactMapping($propertyFactsCheckParam);
            if($propertyFactsCheck['status'] != 'success'){
                throw new ApiErrorException($propertyFactsCheck['message']);
            }

            $requestData = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ]
            ];
            $factData = $this->propertyFactService->select($requestData);

            if ($factData['status'] != 'success') {
                throw new ApiErrorException(lang('Fact data not loaded'));
            }

            $facts = collect($factData['data'])->keyBy('id');
            $insertDataArray = [] ;

            if(!empty($param['hotel_features_mapping'])){
                $param['fact_mapping'] = array_merge($param['fact_mapping'], $param['hotel_features_mapping']);
            }

            foreach ($param['fact_mapping'] as $fact) {
                $theFact = $facts[$fact];
                $parentFact = $facts[$theFact['parent_id']];
                $insertDataArray[] =
                    [
                        "offer_id" => fillOnUndefined($param, "offer_id"),
                        "category_id" => $parentFact['parent_id'],
                        "property_fact_parent_id" => $theFact['parent_id'],
                        "property_fact_id" =>$fact,
                        "status" => fillOnUndefined($param, "status", 1),
                        "created_by" => fillOnUndefined($param, "user_id"),
                        "updated_by" => fillOnUndefined($param, "user_id"),
                        "created_at" => time(),
                        "updated_at" => time(),
                    ];
            }

            $offerFactInsertResult = $this->offerFactMappingRepository->createAll($insertDataArray);
            if ($offerFactInsertResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $userData = $offerFactInsertResult["data"];
            $response = [
                'status' => true,
                'data' => $userData,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);

    }

    public function updateOfferFacts($param = [], $offerAllFactIds = [])
    {

        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $validationResult = $this->offerFactMappingAddValidator->validate($param);

            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }
            if(!empty($param['hotel_features_mapping'])){
                $param['fact_mapping'] = array_merge($param['fact_mapping'], $param['hotel_features_mapping']);
            }

            $insertThisIds = array_diff($param['fact_mapping'], $offerAllFactIds);
            $deleteThisIds = array_diff($offerAllFactIds, $param['fact_mapping']);


            $requestData = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ]
            ];
            $factData = $this->propertyFactService->select($requestData);

            if ($factData['status'] != 'success') {
                throw new ApiErrorException(lang('Fact data not loaded'));
            }

            $facts = collect($factData['data'])->keyBy('id');
            $insertDataArray = [] ;


            foreach ($insertThisIds as $fact) {
                $theFact = $facts[$fact];
                $parentFact = $facts[$theFact['parent_id']];
                $insertDataArray[] =
                    [
                        "offer_id" => fillOnUndefined($param, "offer_id"),
                        "category_id" => $parentFact['parent_id'],
                        "property_fact_parent_id" => $theFact['parent_id'],
                        "property_fact_id" =>$fact,
                        "status" => fillOnUndefined($param, "status", 1),
                        "created_by" => fillOnUndefined($param, "user_id"),
                        "updated_by" => fillOnUndefined($param, "user_id"),
                        "created_at" => time(),
                        "updated_at" => time(),
                    ];
            }

            $offerFactInsertResult = $this->offerFactMappingRepository->createAll($insertDataArray);
            if ($offerFactInsertResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }


            $requestData = [
                'criteria' => [
                    ['field' => 'offer_id', 'condition' => '=', 'value' => fillOnUndefined($param, "offer_id")],
                ],
                "whereIn" =>
                    [
                        ["field" => "property_fact_id", "value" => $deleteThisIds]
                    ]
            ];
            $factEraseMappingData = $this->offerFactMappingRepository->findByCriteria($requestData, ['id']);
            $factEraseMappingData = $factEraseMappingData ? $factEraseMappingData : [] ;
            $deleteThisIds = collect($factEraseMappingData)->keyBy('id')->keys()->all();

            if($deleteThisIds){
                $deleteThisArray = $this->offerFactMappingRepository->destroy($deleteThisIds);
                if ($deleteThisArray['status'] != 'success') {
                    throw new Exception('api-unknown_error');
                }
            }

            $userData = $offerFactInsertResult["data"];
            $response = [
                'status' => true,
                'data' => $userData,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);

    }


}
