<?php

namespace App\Core\Service;

use App\Core\Repository\OfferAccommodationMapping\OfferAccommodationMappingRepository;
use App\Core\Validator\OfferAccommodationMapping\OfferAccommodationMappingCreateValidator;
use App\Core\Validator\OfferAccommodationMapping\OfferAccommodationMappingAddValidator;


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

class OfferAccommodationMappingService
{

    private $offerAccommodationMappingRepository;
    private $offerAccommodationMappingCreateValidator;
    private $offerAccommodationMappingAddValidator;


    public function __construct(

        OfferAccommodationMappingRepository $offerAccommodationMappingRepository,
        OfferAccommodationMappingCreateValidator $offerAccommodationMappingCreateValidator,
        OfferAccommodationMappingAddValidator $offerAccommodationMappingAddValidator
    )
    {
        $this->offerAccommodationMappingRepository = $offerAccommodationMappingRepository;
        $this->offerAccommodationMappingCreateValidator = $offerAccommodationMappingCreateValidator;
        $this->offerAccommodationMappingAddValidator = $offerAccommodationMappingAddValidator;
    }

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

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

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

            $insertData =
                [
                    "offer_id" => fillOnUndefined($param, "offer_id"),
                    "property_accommodation_id" => fillOnUndefined($param, "property_accommodation_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->offerAccommodationMappingRepository->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->offerAccommodationMappingRepository->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->offerAccommodationMappingRepository->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->offerAccommodationMappingRepository->updateOrCreate($criteria, $saveData);
            if ($data['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $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 insertAccommodationMapping($param = [])
    {

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

            $validationResult = $this->offerAccommodationMappingAddValidator->validate($param);
            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }
            $insertDataArray = [] ;
            foreach ($param['accommodation_mapping'] as $item) {
                $insertDataArray[] =
                    [
                        "offer_id" => fillOnUndefined($param, "offer_id"),
                        "property_accommodation_id" => $item,
                        "status" => fillOnUndefined($param, "status", 1),
                        "created_by" => fillOnUndefined($param, "user_id"),
                        "updated_by" => fillOnUndefined($param, "user_id"),
                        "created_at" => time(),
                        "updated_at" => time(),
                    ];
            }

            $offerContactInsertResult = $this->offerAccommodationMappingRepository->createAll($insertDataArray);
            if ($offerContactInsertResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $userData = $offerContactInsertResult["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 updateAccommodationMapping($param = [], $offerAccommodationMapping)
    {

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

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

            $insertThisIds = array_diff($param['accommodation_mapping'], $offerAccommodationMapping);
            $deleteThisIds = array_diff($offerAccommodationMapping, $param['accommodation_mapping']);
            $responseDeleteIds = $deleteThisIds;



            $insertDataArray = [] ;
            foreach ($insertThisIds as $item) {
                $insertDataArray[] =
                    [
                        "offer_id" => fillOnUndefined($param, "offer_id"),
                        "property_accommodation_id" => $item,
                        "status" => fillOnUndefined($param, "status", 1),
                        "created_by" => fillOnUndefined($param, "user_id"),
                        "updated_by" => fillOnUndefined($param, "user_id"),
                        "created_at" => time(),
                        "updated_at" => time(),
                    ];
            }

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

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

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


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

        } 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);

    }

}
