<?php

namespace App\Http\Controllers\V1;


use App\Core\Mail\CancelBookingMail;
use App\Core\Service\OfferService;
use App\Core\Service\PropertyFactService;
use App\Core\Service\PropertyExecutiveService;
use App\Core\Service\PropertyRoomService;
use App\Core\Service\PropertyPhotoService\PropertyPhotoService;
use App\Core\Service\LanguageService;
use App\Core\Service\CurrencyService;
use App\Core\Service\PropertyBrandService;
use App\Core\Service\PropertyService;
use App\Core\Service\PropertyContactService;
use App\Core\Service\PropertyPaymentService;
use App\Core\Mail\OfferAcceptMail;
use App\Core\Mail\OfferPreConfirmCustomerMail;
use App\Core\Mail\OfferPreConfirmPropertyMail;
use App\Core\Mail\OfferSendMail;

//use App\Core\Service\QRCodeService;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;

//use Intervention\Image\Facades\Image;

class PropertyOfferController
{


    private $request;
    private $offerService;
    private $propertyFactService;
    private $propertyExecutiveService;
    private $propertyRoomService;
    private $propertyPhotoService;
    private $languageService;
    private $currencyService;
    private $propertyBrandService;
    private $propertyService;
    private $propertyContactService;
    private $propertyPaymentService;

//    private $qrCode;


    public function __construct(
        Request $request,
        Mailer $mailer,
        OfferService $offerService,
        PropertyFactService $propertyFactService,
        PropertyExecutiveService $propertyExecutiveService,
        PropertyRoomService $propertyRoomService,
        PropertyPhotoService $propertyPhotoService,
        LanguageService $languageService,
        CurrencyService $currencyService,
        PropertyBrandService $propertyBrandService,
        PropertyContactService $propertyContactService,
        PropertyService $propertyService,
        PropertyPaymentService $propertyPaymentService
//        QRCodeService $qrCode


    )
    {
        $this->request = $request;
        $this->mailer = $mailer;
        $this->offerService = $offerService;
        $this->propertyFactService = $propertyFactService;
        $this->propertyExecutiveService = $propertyExecutiveService;
        $this->propertyRoomService = $propertyRoomService;
        $this->propertyPhotoService = $propertyPhotoService;
        $this->languageService = $languageService;
        $this->currencyService = $currencyService;
        $this->propertyBrandService = $propertyBrandService;
        $this->propertyService = $propertyService;
        $this->propertyContactService = $propertyContactService;
        $this->propertyPaymentService = $propertyPaymentService;
        //     $this->qrCode = $qrCode;

    }


    public function listPropertyOffer(Request $request)
    {
        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            if (is_null($request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = $request->params;
            $propertyRequest = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => fillOnUndefined($params, 'property_id')],
                ],
                'with' => ['offerAcceptStatus','paymentTransaction'],
                "orderBy" => [
                    ["field" => "id", "value" => "DESC"]
                ]
            ];
            $ticketCode = fillOnUndefinedAndEmpty($params, 'ticket_code');
            if ($ticketCode) {
                $propertyRequest['criteria'][] = ['field' => 'ticket_code', 'condition' => 'like', 'value' => '%' . $ticketCode . '%'];
            }

            $propertyOffers = $this->offerService->select($propertyRequest);

            if ($propertyOffers['status'] != 'success') {
                throw new Exception($propertyOffers['message']);
            }

            $offerList = [];
            foreach ($propertyOffers['data'] as $offerKey => $value) {
                $offerList[$offerKey] = $value;
                $offerList[$offerKey]['total'] = moneyDoubleFormat($value['total']);
                if(!empty($value['payment_type_mapping_id'])) {
                    $offerList[$offerKey]['is_payment_received'] = false;
                    $paymentTransactionList = collect($value['payment_transaction']);
                    if($paymentTransactionList->where('status',1)->count() > 0) {
                        $offerList[$offerKey]['is_payment_received'] = true;
                    }
                }

                unset($offerList[$offerKey]['payment_transaction']);
            }

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $offerList];

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

    public function createPropertyOffer(Request $request)
    {

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            if (is_null($this->request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = $this->request->params;


            $requestParams = [
                'locale' => fillOnUndefined($params, 'locale'),
                'property_id' => fillOnUndefined($params, 'property_id'),
            ];
            $getPropertyFact = $this->propertyFactService->getPropertyFact($requestParams);
            if ($getPropertyFact['status'] != 'success') {
                throw new ApiErrorException($getPropertyFact['message']);
            }

            $getPropertyFact = $this->propertyFactService->getPropertyOfferFilter($getPropertyFact['data'], []);
            if ($getPropertyFact['status'] != 'success') {
                throw new ApiErrorException($getPropertyFact['message']);
            }

            $accommodationTypes = $getPropertyFact['data']['accommodation_types'];
            $propertyFacts = $getPropertyFact['data']['get_facts'];

            $propertyExecutive = $this->propertyExecutiveService->listPropertyExecutive($requestParams);
            if ($propertyExecutive['status'] != 'success') {
                throw new Exception($propertyExecutive['message']);
            }


            $propertyRooms = $this->propertyRoomService->getPropertyRooms($requestParams);
            if ($propertyRooms['status'] != 'success') {
                throw new ApiErrorException($propertyRooms['message']);
            }

            $propertyPhotos = $this->propertyPhotoService->getPropertyPhotos($params);
            if ($propertyPhotos['status'] != 'success') {
                throw new ApiErrorException($propertyPhotos['message']);
            }
            $languageCriteria = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                    ['field' => 'is_application', 'condition' => '=', 'value' => 1],
                    ['field' => 'is_published', 'condition' => '=', 'value' => 1]
                ],
                "orderBy" => [
                    ["field" => "name", "value" => "ASC"]
                ]
            ];

            $languages = $this->languageService->getAllLanguages($languageCriteria, ['id', 'code', 'name', 'status', 'language_key']);
            if ($languages['status'] != 'success') {
                throw new ApiErrorException($languages['message']);
            }


            $currencies = $this->currencyService->getCurrencyList(['justBasicCurrencies' => true]);
            if ($currencies['status'] != 'success') {
                throw new ApiErrorException($currencies['message']);
            }

            $offerConfirmType = $this->offerService->selectOfferConfirmType([], ['code', 'name', 'language_key']);
            if ($offerConfirmType['status'] != 'success') {
                throw new ApiErrorException($offerConfirmType['message']);
            }

            $offerConfirmType = $offerConfirmType['data'];

            $paymentList = $this->propertyPaymentService->getPaymentMappingList($params);
            if ($paymentList['status'] != 'success') {
                throw new ApiErrorException($paymentList['message']);
            }

            $paymentListType = collect($paymentList['data'])->map(function ($payment) {
                return [
                    'id' => $payment['id'],
                    'name' => $payment['name'],
                    'currency_code' => $payment['currency_code'],
                    'title' => $payment['name'] . ' - ' . $payment['currency_code'],
                    'status' => $payment['status']
                ];
            })->sortBy('title')->toArray();
            $paymentListType = array_values($paymentListType);

            $responseData = [
                'get_facts' => $propertyFacts,
                'accommodation_types' => $accommodationTypes,
                'executives' => $propertyExecutive['data']['executives'],
                'property_rooms' => $propertyRooms['data'],
                'photos' => $propertyPhotos['data'],
                'languages' => $languages['data'],
                'currencies' => $currencies['data'],
                'offer_confirm_type' => $offerConfirmType,
                'payment_list_type' => $paymentListType,
            ];

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];

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


    }

    public function storePropertyOffer(Request $request)
    {

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            if (is_null($this->request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = $this->request->params;

            $requestParams = $params;
            $requestParams['user_id'] = $this->request->auth->id;

            $storeOffer = $this->offerService->addNewOffer($requestParams);
            if ($storeOffer['status'] != 'success') {
                throw new ApiErrorException($storeOffer['message']);
            }


            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $storeOffer['data']];

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

    }

    public function getPricePropertyOffer(Request $request)
    {

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            if (is_null($this->request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = $this->request->params;

            $requestParams = $params;
            $requestParams['user_id'] = $this->request->auth->id;

            $checkPropertyOfferPermissionAccess = $this->offerService->checkPropertyOfferPermissionAccess(['property_id' => $params['property_id'], 'offer_id' => $params['offer_id']]);
            if ($checkPropertyOfferPermissionAccess['status'] != 'success') {
                throw new ApiErrorException($checkPropertyOfferPermissionAccess['message']);
            }

            $storeOffer = $this->offerService->getPriceList($requestParams);
            if ($storeOffer['status'] != 'success') {
                throw new ApiErrorException($storeOffer['message']);
            }


            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $storeOffer['data']];

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


    }

    public function storePricePropertyOffer(Request $request)
    {

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            if (is_null($this->request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = $this->request->params;

            $requestParams = $params;
            $requestParams['user_id'] = $this->request->auth->id;

            $checkPropertyOfferPermissionAccess = $this->offerService->checkPropertyOfferPermissionAccess(['property_id' => $params['property_id'], 'offer_id' => $params['offer_id']]);
            if ($checkPropertyOfferPermissionAccess['status'] != 'success') {
                throw new ApiErrorException($checkPropertyOfferPermissionAccess['message']);
            }

            $storeOffer = $this->offerService->storePriceList($requestParams);
            if ($storeOffer['status'] != 'success') {
                throw new ApiErrorException($storeOffer['message']);
            }
            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $storeOffer['data']];

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


    }

    public function editPropertyOffer(Request $request)
    {

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            if (is_null($this->request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = $this->request->params;

            $checkPropertyOfferPermissionAccess = $this->offerService->checkPropertyOfferPermissionAccess(['property_id' => $params['property_id'], 'offer_id' => $params['offer_id']]);
            if ($checkPropertyOfferPermissionAccess['status'] != 'success') {
                throw new ApiErrorException($checkPropertyOfferPermissionAccess['message']);
            }

            $requestParams = [
                'locale' => fillOnUndefined($params, 'locale'),
                'property_id' => fillOnUndefined($params, 'property_id'),
                'offer_id' => fillOnUndefined($params, 'offer_id'),
            ];

            $getOffer = $this->offerService->findOffer($requestParams);
            if ($getOffer['status'] != 'success') {
                throw new ApiErrorException($getOffer['message']);
            }

            $offerPrice = $getOffer['data']['offer_price'];
            $startDate = collect($offerPrice)->keyBy('date')->keys()->min();
            $endDate = collect($offerPrice)->keyBy('date')->keys()->max();

            $getPropertyFact = $this->propertyFactService->getPropertyFact($requestParams);
            if ($getPropertyFact['status'] != 'success') {
                throw new ApiErrorException($getPropertyFact['message']);
            }


            $offerAccommodationMapping = collect($getOffer['data']['offer_accommodation_mapping'])->keyBy('id')->keys()->all();
            $offerFactMapping = collect($getOffer['data']['offer_fact_mapping'])->keyBy('id')->keys()->all();
            $offerAllFactIds = array_merge($offerAccommodationMapping, $offerFactMapping);

            $getPropertyFact = $this->propertyFactService->getPropertyOfferFilter($getPropertyFact['data'], $offerAllFactIds);
            if ($getPropertyFact['status'] != 'success') {
                throw new ApiErrorException($getPropertyFact['message']);
            }

            $accommodationTypes = $getPropertyFact['data']['accommodation_types'];
            $propertyFacts = $getPropertyFact['data']['get_facts'];


            $propertyExecutive = $this->propertyExecutiveService->listPropertyExecutive($requestParams);
            if ($propertyExecutive['status'] != 'success') {
                throw new Exception($propertyExecutive['message']);
            }

            $propertyRooms = $this->propertyRoomService->getPropertyRooms($requestParams);
            if ($propertyRooms['status'] != 'success') {
                throw new ApiErrorException($propertyRooms['message']);
            }

            $propertyPhotos = $this->propertyPhotoService->getPropertyPhotos($params);
            if ($propertyPhotos['status'] != 'success') {
                throw new ApiErrorException($propertyPhotos['message']);
            }

            $languageCriteria = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                    ['field' => 'is_application', 'condition' => '=', 'value' => 1],
                    ['field' => 'is_published', 'condition' => '=', 'value' => 1]
                ],
                "orderBy" => [
                    ["field" => "name", "value" => "ASC"]
                ]
            ];

            $languages = $this->languageService->getAllLanguages($languageCriteria, ['id', 'code', 'name', 'status', 'language_key']);
            if ($languages['status'] != 'success') {
                throw new ApiErrorException($languages['message']);
            }


            $currencies = $this->currencyService->getCurrencyList();
            if ($currencies['status'] != 'success') {
                throw new ApiErrorException($currencies['message']);
            }

            $offerConfirmTypes = $this->offerService->selectOfferConfirmType([], ['code', 'name', 'language_key']);
            if ($offerConfirmTypes['status'] != 'success') {
                throw new ApiErrorException($offerConfirmTypes['message']);
            }

            $offerConfirmType = [];
            foreach ($offerConfirmTypes['data'] as $offerConfirmTypeData) {

                $isSelectedOfferConfirmType = false;
                if ($offerConfirmTypeData['code'] == $getOffer['data']['confirm_type']) {
                    $isSelectedOfferConfirmType = true;
                }

                $offerConfirmType[] = [
                    'code' => $offerConfirmTypeData['code'],
                    'name' => $offerConfirmTypeData['name'],
                    'language_key' => $offerConfirmTypeData['language_key'],
                    'is_selected' => $isSelectedOfferConfirmType
                ];
            }

            $paymentList = $this->propertyPaymentService->getPaymentMappingList($params);
            if ($paymentList['status'] != 'success') {
                throw new ApiErrorException($paymentList['message']);
            }

            $paymentListType = collect($paymentList['data'])->map(function ($payment) use ($getOffer) {


                $isSelectedPaymentType = false;
                if ($payment['id'] == $getOffer['data']['payment_type_mapping_id']) {
                    $isSelectedPaymentType = true;
                }

                return [
                    'id' => $payment['id'],
                    'name' => $payment['name'],
                    'currency_code' => $payment['currency_code'],
                    'title' => $payment['name'] . ' - ' . $payment['currency_code'],
                    'status' => $payment['status'],
                    'is_selected' => $isSelectedPaymentType
                ];
            })->sortBy('title')->toArray();

            $paymentListType = array_values($paymentListType);

            $responseData = [
                'get_offer' => $getOffer['data'],
                'get_facts' => $propertyFacts,
                'accommodation_types' => $accommodationTypes,
                'executives' => $propertyExecutive['data']['executives'],
                'property_rooms' => $propertyRooms['data'],
                'photos' => $propertyPhotos['data'],
                'languages' => $languages['data'],
                'currencies' => $currencies['data'],
                'start_date' => fillOnUndefined($getOffer['data'], "check_in"),
                'end_date' => fillOnUndefined($getOffer['data'], "check_out"),
                'offer_confirm_type' => $offerConfirmType,
                'payment_list_type' => $paymentListType,
            ];

            $responseData = $this->offerService->editFormCheckValues($responseData);


            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];

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


    }

    public function updatePropertyOffer(Request $request)
    {

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            if (is_null($this->request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = $this->request->params;

            $requestParams = $params;
            $requestParams['user_id'] = $this->request->auth->id;

            $checkPropertyOfferPermissionAccess = $this->offerService->checkPropertyOfferPermissionAccess(['property_id' => $params['property_id'], 'offer_id' => $params['offer_id']]);
            if ($checkPropertyOfferPermissionAccess['status'] != 'success') {
                throw new ApiErrorException($checkPropertyOfferPermissionAccess['message']);
            }

            $storeOffer = $this->offerService->updateOffer($requestParams);
            if ($storeOffer['status'] != 'success') {
                throw new ApiErrorException($storeOffer['message']);
            }


            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $storeOffer['data']];

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


    }

    public function listPropertyOfferPublish(Request $request)
    {

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            if (is_null($this->request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = $this->request->params;

            $checkOffer = [
                'criteria' => [
                    ['field' => 'offer_code', 'condition' => '=', 'value' => fillOnUndefined($params, 'offer_code')],
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ],
                'with' => ['paymentTransaction'],
                'whereIn' => [
                    ['field' => 'accept_status', 'value' => [1, 2, 3]],
                ],
                'firstRow' => 1
            ];
            $checkOfferData = $this->offerService->select($checkOffer);
            if ($checkOfferData['status'] != "success" || !$checkOfferData['data']) {
                throw new ApiErrorException('offer not found');
            }
            $params['offer_id'] = $checkOfferData['data']['id'];
            $params['property_id'] = $checkOfferData['data']['property_id'];
            $params['offer_code'] = $checkOfferData['data']['offer_code'];

            /* $offerUrl = config('app.client_server')."/offer/".$params['offer_code'];
             $generatedQRCode = $this->qrCode->generate($offerUrl, 250);

             if($generatedQRCode['status'] === false){
                 throw new ApiErrorException($generatedQRCode['message']);
             }

             $qrCode = (string) Image::make($generatedQRCode['data'])->encode('data-url');*/

            $requestParams = $params;

            $getOffer = $this->offerService->findOffer($requestParams);

            if ($getOffer['status'] != 'success') {
                throw new ApiErrorException($getOffer['message']);
            }

            $offerLanguage = $getOffer['data']['language'];
            $requestParams['locale'] = $offerLanguage;

            $requestBrand = [

                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => fillOnUndefined($params, 'property_id')],

                ],
                'firstRow' => 1
            ];
            $getPropertyBrand = $this->propertyBrandService->select($requestBrand);
            $getPropertyBrand['data']['color_codes'] = json_decode($getPropertyBrand['data']['color_codes'], true);
            if ($getPropertyBrand['status'] != "success") {
                throw new ApiErrorException($getPropertyBrand['message']);
            }

            $defaultLogo = "/assets/img/logo/logo.png";
            $getPropertyBrand['data']['logo_url'] = isset($getPropertyBrand['data']['logo_name']) ? Config::get('app.imageUrl') . '/property-photos/' . $params['property_id'] . '/logo/' . $getPropertyBrand['data']['logo_name'] . '_250x250.' . $getPropertyBrand['data']['logo_file_ext'] : $defaultLogo;

            $getOffer['data']['expire_date'] = humanReadableDate($getOffer['data']['expire_date']);
            $getPropertyFact = $this->propertyFactService->getPropertyFact($requestParams);
            if ($getPropertyFact['status'] != 'success') {
                throw new ApiErrorException($getPropertyFact['message']);
            }

            $offerAccommodationMapping = collect($getOffer['data']['offer_accommodation_mapping'])->keyBy('id')->keys()->all();
            $offerFactMapping = collect($getOffer['data']['offer_fact_mapping'])->keyBy('id')->keys()->all();
            $offerAllFactIds = array_merge($offerAccommodationMapping, $offerFactMapping);
            $getPropertyFact = $this->propertyFactService->getPropertyOfferFilterForHtml($getPropertyFact['data'], $offerAllFactIds);
            if ($getPropertyFact['status'] != 'success') {
                throw new ApiErrorException($getPropertyFact['message']);
            }


            $getProperty = $this->propertyService->getPropertyDetail($requestParams);

            if ($getProperty['status'] != 'success') {
                throw new ApiErrorException($getProperty['message']);
            }

            $propertyContact = $this->propertyContactService->propertyContact($requestParams);

            if ($propertyContact['status'] != 'success') {
                throw new Exception($propertyContact['message']);
            }

            $getProperty['data']['contact'] = $propertyContact['data']['property_contact'];
            $getRoomPriceParams = [

                'offer_id' => $getOffer['data']['id'],
                'property_id' => fillOnUndefined($params, 'property_id'),
                'locale' => $offerLanguage,

            ];

            $getRoomPrice = $this->offerService->getPrice($getRoomPriceParams);

            if ($getRoomPrice['status'] != 'success') {
                throw new ApiErrorException($getRoomPrice['message']);
            }


            $offerPayment = [];
            if(!empty($checkOfferData['data']['payment_type_mapping_id'])) {
                $paymentTransaction = collect($checkOfferData['data']['payment_transaction']);

                $paymentLink = $paymentTransaction->where('code',null)->first();

                if(isset($paymentLink['manuelPaymentLink'])) {
                    $offerPayment['payment_link'] = $paymentLink['manuelPaymentLink'];
                    $offerPayment['is_payment_received'] = false;
                }

                if($paymentTransaction->where('status',1)->count() > 0) {
                    $offerPayment['is_payment_received'] = true;
                }

            }

            unset($getOffer['data']['offer_accommodation_mapping']);
            unset($getOffer['data']['offer_fact_mapping']);
            unset($getOffer['data']['offer_price']);
            unset($getOffer['data']['offer_room_mapping']);

            $offerPublishData = [
                'property_brand' => fillOnUndefined($getPropertyBrand, "data", []),
                'offer' => fillOnUndefined($getOffer, 'data', []),
                'property' => fillOnUndefined($getProperty, 'data', []),
                'property_fact' => fillOnUndefined($getPropertyFact, 'data', []),
                'room_price' => fillOnUndefined($getRoomPrice, 'data', []),
                'offer_payment' => $offerPayment
                //  "qr_code" => $qrCode
            ];

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $offerPublishData];

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

    public function updatePropertyOfferStatus(Request $request)
    {

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            if (is_null($this->request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = $this->request->params;

            $requestParams = $params;

            $requestParams['user_id'] = $this->request->auth->id;

            $checkPropertyOfferPermissionAccess = $this->offerService->checkPropertyOfferPermissionAccess(['property_id' => $params['property_id'], 'offer_id' => $params['offer_id']]);
            if ($checkPropertyOfferPermissionAccess['status'] != 'success') {
                throw new ApiErrorException($checkPropertyOfferPermissionAccess['message']);
            }

            $statusOffer = $this->offerService->updateStatus($requestParams);
            if ($statusOffer['status'] != 'success') {
                throw new ApiErrorException($statusOffer['message']);
            }

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $statusOffer['data']];
        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
            $response['statusCode'] = 400;
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
            $response['statusCode'] = 500;
        }
        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);

    }

    public function updatePropertyOfferAceptStatus(Request $request)
    {

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            if (is_null($this->request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = $this->request->params;

            $requestParams['user_id'] = $this->request->auth->id;

            $checkPropertyOfferPermissionAccess = $this->offerService->checkPropertyOfferPermissionAccess(['property_id' => $params['property_id'], 'offer_id' => $params['offer_id']]);
            if ($checkPropertyOfferPermissionAccess['status'] != 'success') {
                throw new ApiErrorException($checkPropertyOfferPermissionAccess['message']);
            }

            $requestParams['offer_id'] = $checkPropertyOfferPermissionAccess['data']['id'];
            $requestParams['offer_code'] = $checkPropertyOfferPermissionAccess['data']['offer_code'];

            if ($checkPropertyOfferPermissionAccess['data']['confirm_type'] == 'HTL' && $checkPropertyOfferPermissionAccess['data']['accept_status'] == 2) {
                $requestParams['accept_status'] = 1;

                $statusOffer = $this->offerService->updateAcceptStatus($requestParams);
                if ($statusOffer['status'] != 'success') {
                    throw new ApiErrorException($statusOffer['message']);
                }

                $offerAcceptMailParam = [
                    'offer_id' => $checkPropertyOfferPermissionAccess['data']['id'],
                    'property_id' => $checkPropertyOfferPermissionAccess['data']['property_id'],
                    'paymentUrl' => null
                ];

                //Integrated Payment Link
                if (!is_null($checkPropertyOfferPermissionAccess['data']['payment_type_mapping_id'])) {

                    $paymentLinkParam = [
                        'property_id' => $checkPropertyOfferPermissionAccess['data']['property_id'],
                        'title' => $checkPropertyOfferPermissionAccess['data']['title'],
                        'description' => $checkPropertyOfferPermissionAccess['data']['ticket_code'] . '-' . $checkPropertyOfferPermissionAccess['data']['offer_code'],
                        'email' => $checkPropertyOfferPermissionAccess['data']['email'],
                        'currency' => $checkPropertyOfferPermissionAccess['data']['currency'],
                        'base_amount' => $checkPropertyOfferPermissionAccess['data']['total'],
                        'commission' => '0',
                        'payment_method' => 'online',
                        'payment_type_mapping_id' => $checkPropertyOfferPermissionAccess['data']['payment_type_mapping_id'],
                        'locale' => $checkPropertyOfferPermissionAccess['data']['language'],
                        'user_id' => $checkPropertyOfferPermissionAccess['data']['created_by'],
                    ];

                    $createPaymentLink = $this->propertyPaymentService->createManualPayment($paymentLinkParam);

                    if ($createPaymentLink['status'] == "success") {
                        $offerAcceptMailParam['paymentUrl'] = $createPaymentLink['data']['payment_link'];
                        $this->offerService->update($checkPropertyOfferPermissionAccess['data']['id'], ['payment_transaction_order_id' => $createPaymentLink['data']['order_id']]);
                    }

                }

                $this->mailer->onQueue('offerAcceptMail', new OfferAcceptMail($offerAcceptMailParam));

            } else {
                throw new ApiErrorException('Offer status not available');
            }

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

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

    }

    public function dashboardPropertyOffer(Request $request)
    {
        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            if (is_null($request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = $request->params;

            $propertyRequest = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ],
            ];
            $propertyOffers = $this->offerService->select($propertyRequest);
            $propertyOffers = collect($propertyOffers['data'])->groupBy('accept_status')->map->count()->toArray();

            $propertyPassiveRequest = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                    ['field' => 'status', 'condition' => '=', 'value' => 0],
                ],
            ];
            $propertyPassiveOffers = $this->offerService->select($propertyPassiveRequest);
            $passiveCounts = collect($propertyPassiveOffers['data'])->count();
            $acceptAndPendingCount = collect($propertyOffers)->sum();
            $offerDashboardData =
                [
                    "passive" => $passiveCounts,
                    "canceled" => fillOnUndefined($propertyOffers, 0, 0),
                    "accepted" => fillOnUndefined($propertyOffers, 1, 0),
                    "pending" => fillOnUndefined($propertyOffers, 2, 0),
                    "total" => $passiveCounts + $acceptAndPendingCount,

                ];

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $offerDashboardData];

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

    public function updatePropertyOfferAcceptStatus(Request $request)
    {

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            if (is_null($this->request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $requestParams = $this->request->params;

            $checkOfferApprovedParam = [
                'offer_id' => $requestParams['offer_id']
            ];
            $checkOfferApprovedStatus = $this->offerService->checkOfferApprovedStatus($checkOfferApprovedParam);

            if ($checkOfferApprovedStatus['status'] != 'success') {
                throw new ApiErrorException($checkOfferApprovedStatus['message']);
            }

            $requestParams['accept_status'] = 1;
            if ($checkOfferApprovedStatus['data']['confirm_type'] == 'HTL') {
                $requestParams['accept_status'] = 2;
            }


            $acceptStatusOffer = $this->offerService->updateAcceptStatus($requestParams);
            if ($acceptStatusOffer['status'] != 'success') {
                throw new ApiErrorException($acceptStatusOffer['message']);
            }

            if ($checkOfferApprovedStatus['data']['confirm_type'] == 'INS') {

                $offerAcceptMailParam = [
                    'offer_id' => $checkOfferApprovedStatus['data']['id'],
                    'property_id' => $checkOfferApprovedStatus['data']['property_id'],
                    'paymentUrl' => null
                ];


                //Integrated Payment Link
                if (!is_null($checkOfferApprovedStatus['data']['payment_type_mapping_id'])) {


                    $paymentLinkParam = [
                        'property_id' => $checkOfferApprovedStatus['data']['property_id'],
                        'title' => $checkOfferApprovedStatus['data']['title'],
                        'description' => $checkOfferApprovedStatus['data']['ticket_code'] . '-' . $checkOfferApprovedStatus['data']['offer_code'],
                        'email' => $checkOfferApprovedStatus['data']['email'],
                        'currency' => $checkOfferApprovedStatus['data']['currency'],
                        'base_amount' => $checkOfferApprovedStatus['data']['total'],
                        'commission' => '0',
                        'payment_method' => 'online',
                        'payment_type_mapping_id' => $checkOfferApprovedStatus['data']['payment_type_mapping_id'],
                        'locale' => $checkOfferApprovedStatus['data']['language'],
                        'user_id' => $checkOfferApprovedStatus['data']['created_by'],
                    ];

                    $createPaymentLink = $this->propertyPaymentService->createManualPayment($paymentLinkParam);

                    if ($createPaymentLink['status'] == "success") {
                        $offerAcceptMailParam['paymentUrl'] = $createPaymentLink['data']['payment_link'];
                        $this->offerService->update($checkOfferApprovedStatus['data']['id'], ['payment_transaction_order_id' => $createPaymentLink['data']['order_id']]);
                    }

                }

                $this->mailer->onQueue('offerAcceptMail', new OfferAcceptMail($offerAcceptMailParam));

            } elseif ($checkOfferApprovedStatus['data']['confirm_type'] == 'HTL') {

                $offerAcceptMailParam = [
                    'offer_id' => $checkOfferApprovedStatus['data']['id'],
                    'property_id' => $checkOfferApprovedStatus['data']['property_id'],
                ];

                $this->mailer->onQueue('offerPreConfirmCustomerMail', new OfferPreConfirmCustomerMail($offerAcceptMailParam));

                $this->mailer->onQueue('offerPreConfirmPropertyMail', new OfferPreConfirmPropertyMail($offerAcceptMailParam));

            }


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

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

    }

    public function sendOfferEmail(Request $request)
    {

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            if (is_null($this->request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = $this->request->params;


            $checkPropertyOfferPermissionAccess = $this->offerService->checkPropertyOfferPermissionAccess(['property_id' => $params['property_id'], 'offer_id' => $params['offer_id']]);
            if ($checkPropertyOfferPermissionAccess['status'] != 'success') {
                throw new ApiErrorException($checkPropertyOfferPermissionAccess['message']);
            }


            $offerSendMailParam = [
                'offer_id' => $params['offer_id'],
                'property_id' => $params['property_id']
            ];

            $this->mailer->onQueue('offerSendMail', new OfferSendMail($offerSendMailParam));

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

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

    }



}
