<?php
namespace App\Controllers;
use App\Models\ListingModel;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;
use Slim\Views\Twig;

class ListingsController extends BaseController{
    public $listingModel;
    public string $layoutPath = "listings";
    public function __construct(Request $request, Response $response, $args,App $app)
    {
        parent::__construct($request, $response, $args,$app);
        $this->listingModel = new ListingModel();
    }

    /**
     * @throws \Twig\Error\SyntaxError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\LoaderError
     */
    public function baap() : Response{
        $file = fopen("log_read_adv_id.txt","a+");
        fwrite($file,"\n"."Called From ".$_SERVER['REMOTE_ADDR']." - ". $_SERVER['REMOTE_HOST'] . "on ".date('m/d/y H:i:s') );
        fclose($file);
        return $this->renderLayout('advertisersIndex.xml');
    }
    public function index() : Response{
        $data = $this->listingModel->getList();
        return $this->renderLayout('listingIndex.xml',['data'=>$data]);
    }
    public function listing() : Response{
        $reqData = $this->request->getQueryParams();
        if (!isset($reqData['id'])) {
            return $this->renderLayout('error.xml');
        }
        $idGot = $this->getUnitIdByListId($reqData['id']);
        if($idGot){ $reqData['id'] = $idGot; }
        $data = $this->listingModel->getListing($reqData['id']);
        if (count($data) == 0) {
            return $this->renderLayout('error.xml');
        }

        $data[0]['vrbo_bathroom_info'] = json_decode($data[0]['vrbo_bathroom_info'],true);
        $data[0]['vrbo_bedroom_info'] = json_decode($data[0]['vrbo_bedroom_info'],true);
        $amsUNF = $this->listingModel->getAmenities($reqData['id']);

        $ams = [];
        $skipAM = [];
        $fullSKIP = ['AMENITY_OUTDOOR_SHOWER'];
        $skipAM = ['SPORTS_GOLF_OPTIONAL','LOCAL_LAUNDROMAT','KITCHEN_DINING_DISHWASHER','KITCHEN_DINING_DISHES_UTENSILS','AMENITY_OUTDOOR_SHOWER','KITCHEN_DINING_KITCHEN','KITCHEN_DINING_MICROWAVE','SPORTS_CYCLING','SPORTS_FISHING','SPORTS_FISHING_BAY','SPORTS_FISHING_SURF','SPORTS_GOLF',
                    'SPORTS_JET_SKIING','SPORTS_SAILING','SPORTS_SCUBA_OR_SNORKELING','SPORTS_SNORKELING','SPORTS_SURFING','SPORTS_SWIMMING','SPORTS_WIND_SURFING','ATTRACTIONS_MARINA','LEISURE_ANTIQUING',
                    'LEISURE_BIRD_WATCHING','LEISURE_HORSEBACK_RIDING','LEISURE_SHOPPING','LOCAL_FITNESS_CENTER','LOCAL_HOSPITAL','COMMON_SURFACE_DISINFECTANT_CLEANED','ENHANCED_CLEANING_PRACTICES','SELF_CHECKIN_CHECKOUT',
                    'ATTRACTIONS_WATER_PARKS','SPORTS_FISHING_FLY','SPORTS_PIER_FISHING','ATTRACTIONS_BAY','ATTRACTIONS_ZOO',
                    'LEISURE_ECO_TOURISM','LEISURE_PADDLE_BOATING','DEADBOLT_LOCK','SMOKE_DETECTOR','FIRE_EXTINGUISHER','SPORTS_FISHING_FRESHWATER','AMENITIES_LINENS','','','','','','','','',
                    "LOCATION_TYPE_BEACH","LOCATION_TYPE_BEACH_FRONT","LOCATION_TYPE_BEACH_VIEW","LOCATION_TYPE_DOWNTOWN","LOCATION_TYPE_GOLF_COURSE_FRONT","LOCATION_TYPE_GOLF_COURSE_VIEW","LOCATION_TYPE_LAKE","LOCATION_TYPE_LAKE_FRONT","LOCATION_TYPE_LAKE_VIEW","LOCATION_TYPE_MOUNTAIN","LOCATION_TYPE_MOUNTAIN_VIEW",
                    "LOCATION_TYPE_NEAR_OCEAN","LOCATION_TYPE_OCEAN_FRONT","LOCATION_TYPE_OCEAN_VIEW","LOCATION_TYPE_RESORT","LOCATION_TYPE_RIVER","LOCATION_TYPE_RURAL","LOCATION_TYPE_SKI_IN","LOCATION_TYPE_SKI_IN_OUT","LOCATION_TYPE_SKI_OUT","LOCATION_TYPE_TOWN","LOCATION_TYPE_VILLAGE","LOCATION_TYPE_WATER_VIEW","LOCATION_TYPE_WATERFRONT"
                    ];
        // $skipAM = ['LOCATION_TYPE_VILLAGE','SPORTS_GOLF_OPTIONAL','LOCAL_LAUNDROMAT','KITCHEN_DINING_DISHWASHER','KITCHEN_DINING_DISHES_UTENSILS','AMENITY_OUTDOOR_SHOWER','KITCHEN_DINING_KITCHEN','KITCHEN_DINING_MICROWAVE','SPORTS_CYCLING','SPORTS_FISHING','SPORTS_FISHING_BAY','SPORTS_FISHING_SURF','SPORTS_GOLF',
        //             'SPORTS_JET_SKIING','SPORTS_SAILING','SPORTS_SCUBA_OR_SNORKELING','SPORTS_SNORKELING','SPORTS_SURFING','SPORTS_SWIMMING','SPORTS_WIND_SURFING','LOCATION_TYPE_NEAR_OCEAN','LOCATION_TYPE_RESORT','ATTRACTIONS_MARINA','LEISURE_ANTIQUING',
        //             'LEISURE_BIRD_WATCHING','LEISURE_HORSEBACK_RIDING','LEISURE_SHOPPING','LOCAL_FITNESS_CENTER','LOCAL_HOSPITAL','COMMON_SURFACE_DISINFECTANT_CLEANED','ENHANCED_CLEANING_PRACTICES','SELF_CHECKIN_CHECKOUT','LOCATION_TYPE_BEACH','LOCATION_TYPE_BEACH_FRONT',
        //             'LOCATION_TYPE_BEACH_VIEW','LOCATION_TYPE_OCEAN_FRONT','LOCATION_TYPE_OCEAN_VIEW','LOCATION_TYPE_WATER_VIEW','LOCATION_TYPE_WATERFRONT','ATTRACTIONS_WATER_PARKS','SPORTS_FISHING_FLY','SPORTS_PIER_FISHING','ATTRACTIONS_BAY','ATTRACTIONS_ZOO',
        //             'LEISURE_ECO_TOURISM','LEISURE_PADDLE_BOATING','DEADBOLT_LOCK','SMOKE_DETECTOR','FIRE_EXTINGUISHER','SPORTS_FISHING_FRESHWATER','AMENITIES_LINENS','','','','','','','','',
        //             ];
        $listAMs = [];
        $allowd = ['SUITABILITY_ACCESSIBILITY_WHEELCHAIR_ACCESSIBLE','SUITABILITY_ACCESSIBILITY_WHEELCHAIR_INACCESSIBLE','KITCHEN_DINING_KITCHEN','KITCHEN_DINING_AREA',
        'KITCHEN_DINING_REFRIGERATOR','KITCHEN_DINING_MICROWAVE','KITCHEN_DINING_COFFEEMAKER','KITCHEN_DINING_DISHWASHER','KITCHEN_DINING_DISHES_UTENSILS',
        'KITCHEN_DINING_SPICES','KITCHEN_DINING_STOVE','KITCHEN_DINING_OVEN','KITCHEN_DINING_ICE_MAKER','KITCHEN_DINING_HIGHCHAIR','KITCHEN_DINING_TOASTER','KITCHEN_DINING_ROOM',
        'ENTERTAINMENT_TELEVISION','ENTERTAINMENT_STEREO','ENTERTAINMENT_VIDEO_LIBRARY','ENTERTAINMENT_MUSIC_LIBRARY','ENTERTAINMENT_VIDEO_GAMES','ENTERTAINMENT_GAMES',
        'ENTERTAINMENT_BOOKS','ENTERTAINMENT_TOYS','ENTERTAINMENT_POOL_TABLE','ENTERTAINMENT_PING_PONG_TABLE','ENTERTAINMENT_FOOSBALL','ENTERTAINMENT_DVD',
        'ENTERTAINMENT_SATELLITE_OR_CABLE','OUTDOOR_GRILL','OUTDOOR_DECK_PATIO_UNCOVERED','OUTDOOR_LANAI_GAZEBO_COVERED','OUTDOOR_BALCONY','OUTDOOR_GARDEN','OUTDOOR_BIKE',
        'OUTDOOR_TENNIS','OUTDOOR_GOLF','OUTDOOR_BOAT','OUTDOOR_KAYAK_CANOE','OUTDOOR_WATER_SPORTS_GEAR','OUTDOOR_SNOW_SPORTS_GEAR','OUTDOOR_VERANDA','POOL','POOL_SPA_COMMUNAL_POOL',
        'POOL_SPA_PRIVATE_POOL','POOL_SPA_HOT_TUB','POOL_SPA_SAUNA','POOL_SPA_INDOOR_POOL','POOL_SPA_HEATED_POOL','ACCOMMODATIONS_BREAKFAST_BOOKING_POSSIBLE',
        'ACCOMMODATIONS_BREAKFAST_INCLUDED_IN_PRICE','ACCOMMODATIONS_HOUSE_CLEANING_INCLUDED','ACCOMMODATIONS_HOUSE_CLEANING_OPTIONAL','ACCOMMODATIONS_OTHER_SERVICES_CHAUFFEUR',
        'ACCOMMODATIONS_OTHER_SERVICES_CONCIERGE','ACCOMMODATIONS_OTHER_SERVICES_PRIVATE_CHEF','ACCOMMODATIONS_OTHER_SERVICES_MASSAGE','ACCOMMODATIONS_OTHER_SERVICES_CAR_AVAILABLE',
        'THEMES_FAMILY','THEMES_ROMANTIC','THEMES_HISTORIC','AMENITIES_INTERNET','AMENITIES_FIREPLACE','AMENITIES_WOOD_STOVE','AMENITIES_AIR_CONDITIONING','AMENITIES_HEATING',
        'AMENITIES_LINENS','AMENITIES_TOWELS','AMENITIES_WASHER','AMENITIES_DRYER','AMENITIES_PARKING','AMENITIES_GARAGE','AMENITIES_TELEPHONE','AMENITIES_LIVING_ROOM','AMENITIES_FITNESS_ROOM',
        'AMENITIES_GAME_ROOM','AMENITIES_IRON_BOARD','AMENITIES_HAIR_DRYER','AMENITIES_ELEVATOR','AMENITIES_DESK','OUTDOOR_FENCED_POOL','OUTDOOR_FENCED_YARD','AMENITIES_CABINET_LOCKS',
        'KITCHEN_DINING_DISHES_AND_UTENSILS_FOR_KIDS','ENTERTAINMENT_BOOKS_FOR_KIDS','ACCOMMODATIONS_MEAL_DELIVERY','ACCOMMODATIONS_CHILDCARE','AMENITIES_FREE_WIFI','AMENITIES_PAID_WIFI',
        'AMENITIES_WIFI_SPEED_25','AMENITIES_WIFI_SPEED_50','AMENITIES_WIFI_SPEED_100','AMENITIES_WIFI_SPEED_250','AMENITIES_WIFI_SPEED_500','AMENITIES_WIRELESS_BROADBAND',
        'ENTERTAINMENT_SMART_TV','AMENITIES_OFFICE','AMENITIES_COMPUTER_MONITOR','AMENITIES_PRINTER','AMENITIES_DESK_CHAIR','KITCHEN_DINING_KITCHEN_ISLAND','GENERAL_BABY_MONITOR',
        'GENERAL_TRAVEL_CRIB','OUTDOOR_PLAY_AREA','KITCHEN_DINING_DINING_TABLE'];
        
        $allowsLIST = ["EV_CAR_CHARGER","FIRE_PIT","SPORTS_BASKETBALL_COURT","SPORTS_CYCLING","SPORTS_DEEPSEA_FISHING","SPORTS_FISHING","SPORTS_FISHING_FLY","SPORTS_FISHING_FRESHWATER","SPORTS_GOLF","SPORTS_GOLF_OPTIONAL","SPORTS_HIKING","SPORTS_HUNTING","SPORTS_ICE_SKATING","SPORTS_JET_SKIING","SPORTS_MOUNTAIN_BIKING","SPORTS_MOUNTAIN_CLIMBING","SPORTS_MOUNTAINEERING","SPORTS_PIER_FISHING","SPORTS_RAFTING","SPORTS_SAILING","SPORTS_SCUBA_OR_SNORKELING","SPORTS_SKI_LIFT_PRIVILEGES","SPORTS_SKI_LIFT_PRIVILEGES_OPTIONAL","SPORTS_SKIING","SPORTS_SNORKELING","SPORTS_SNORKELING_DIVING","SPORTS_FISHING_BAY","SPORTS_SPELUNKING","SPORTS_FISHING_SURF","SPORTS_SURFING","SPORTS_SWIMMING","SPORTS_SKIING_WATER","SPORTS_TUBING_WATER","SPORTS_WHITEWATER_RAFTING","SPORTS_WIND_SURFING","SPORTS_CROSS_COUNTRY_SKIING","SPORTS_KAYAKING","SPORTS_PARASAILING","SPORTS_ROCK_CLIMBING","SPORTS_SNOWBOARDING","SPORTS_SNOWMOBILING","CAR_NECESSARY","CAR_NOT_NECESSARY","CAR_RECOMMENDED","LOCATION_TYPE_BEACH","LOCATION_TYPE_BEACH_VIEW","LOCATION_TYPE_BEACH_FRONT","LOCATION_TYPE_LAKE","LOCATION_TYPE_LAKE_VIEW","LOCATION_TYPE_LAKE_FRONT","LOCATION_TYPE_NEAR_OCEAN","LOCATION_TYPE_OCEAN_VIEW","LOCATION_TYPE_OCEAN_FRONT","LOCATION_TYPE_RIVER","LOCATION_TYPE_WATERFRONT","LOCATION_TYPE_WATER_VIEW","LOCATION_TYPE_MOUNTAIN","LOCATION_TYPE_MOUNTAIN_VIEW","LOCATION_TYPE_SKI_IN_OUT","LOCATION_TYPE_SKI_IN","LOCATION_TYPE_SKI_OUT","LOCATION_TYPE_GOLF_COURSE_FRONT","LOCATION_TYPE_GOLF_COURSE_VIEW","LOCATION_TYPE_DOWNTOWN","LOCATION_TYPE_RESORT","LOCATION_TYPE_RURAL","LOCATION_TYPE_TOWN","LOCATION_TYPE_VILLAGE","ATTRACTIONS_BAY","ATTRACTIONS_COIN_LAUNDRY","ATTRACTIONS_DUTY_FREE","ATTRACTIONS_HEALTH_BEAUTY_SPA","ATTRACTIONS_MARINA","ATTRACTIONS_MUSEUMS","ATTRACTIONS_THEME_PARKS","ATTRACTIONS_WATER_PARKS","ATTRACTIONS_WINERY_TOURS","ATTRACTIONS_ZOO","LEISURE_ANTIQUING","LEISURE_BIRD_WATCHING","LEISURE_ECO_TOURISM","LEISURE_GAMBLING","LEISURE_HORSEBACK_RIDING","LEISURE_OUTLET_SHOPPING","LEISURE_PADDLE_BOATING","LEISURE_SLEDDING","LEISURE_WHALE_WATCHING","LEISURE_BOATING","LEISURE_SHOPPING","LEISURE_WILDLIFE_VIEWING","LEISURE_WATER_SPORTS","LOCAL_FITNESS_CENTER","LOCAL_HOSPITAL","LOCAL_LAUNDROMAT","ENHANCED_CLEANING_PRACTICES","CLEANING_DISINFECTION","SELF_CHECKIN_CHECKOUT","GUEST_GAP_PERIOD_24_HOURS","GUEST_GAP_PERIOD_48_HOURS","GUEST_GAP_PERIOD_72_HOURS","COMMON_SURFACE_DISINFECTANT_CLEANED","LINENS_HIGH_TEMP_WASH","SG_CLEAN","SAFE_AND_CLEAN","CESCO","SAFETY_AND_HEALTH_ADMINISTRATION","CLEAN_AND_SAFE","MINISTRY_INDUSTRY_TRADE_TOURISM","SAFE_HOSPITALITY","PROTECTED_TOURIST","REGIONAL_GUIDELINES_NOT_SURE","ASSOCIATION_SANITARY_UNPLV","ASSOCIATION_SANITARY_SAFESTAY","ASSOCIATION_SANITARY_DTV_DFV","ASSOCIATION_SANITARY_EHHA","ASSOCIATION_SANITARY_CRISTAL","ASSOCIATION_SANITARY_SAFETRAVELS","ASSOCIATION_SANITARY_HUT","ASSOCIATION_SANITARY_SAFEHOME_VRMA_VRHP","INDUSTRY_ASSOCIATIONS_NOT_SURE"];
        
        foreach($amsUNF as $a){
            
            if(in_array($a['code'],$allowd)){
                if($a['code'] == "AMENITIES_INTERNET"){
                    $ams['AMENITIES_WIRELESS_BROADBAND'] = ['code'=>'AMENITIES_WIRELESS_BROADBAND'];
                    $ams['AMENITIES_FREE_WIFI'] = ['code'=>'AMENITIES_FREE_WIFI'];
                } else {
                    $ams[$a['code']] = $a;
                }
            }
            if(in_array($a['code'],$allowsLIST)){
                $listAMs[$a['code']] = $a;
                
            }
            
            // if(in_array($a['code'],$skipAM)){
            //     $listAMs[$a['code']] = $a;
            // }
            // else{
            //     if($a['code'] == "AMENITIES_INTERNET"){
            //         $ams['AMENITIES_WIRELESS_BROADBAND'] = ['code'=>'AMENITIES_WIRELESS_BROADBAND'];
            //         $ams['AMENITIES_FREE_WIFI'] = ['code'=>'AMENITIES_FREE_WIFI'];
            //     } else {
            //         if(in_array($a['code'],$allowd)){
            //             $ams[$a['code']] = $a;                    
            //         }
            //     }
            // }
        }
        $distinctimages = [];     

        foreach($data[0]['images'] as $image){
            $distinctimages[$image['original']] = $image;    
        }
        $data[0]['images'] = array_values($distinctimages); 
        return $this->renderLayout('listing.xml', ['unit' => $data[0],'ams'=>$ams,'listAMs'=>$listAMs]);
    }

    public function unitAvailabilityIndex() : Response{
        $data = $this->listingModel->getList();
        return $this->renderLayout('unitAvailabilityIndex.xml',['data'=>$data]);
    }

    public function unitAvailability():Response{
        $reqData = $this->request->getQueryParams();
        if (!isset($reqData['id'])) {
            return $this->renderLayout('error.xml');
        }
        $idGot = $this->getUnitIdByListId($reqData['id']);
        if($idGot){ $reqData['id'] = $idGot; }
        $data = $this->listingModel->getListing($reqData['id']);
        if (count($data) == 0) {
            return $this->renderLayout('error.xml');
        }
        $unit = $data[0];
        $start_date = date('Y-m-d',strtotime("-2 days"));
        $end_date = date('Y-m-d',strtotime("+1 year ".$start_date));
        $data = $this->listingModel->getAvailibilityByUnitId($reqData['id'],$start_date,$end_date);
        if (count($data) == 0) {
            return $this->renderLayout('error.xml');
        }

        $availability = join('',array_column($data,'isAvailable'));
        $availableUnitCount = join(',',array_column($data,'availableUnitCount'));
        $changeOver = join('',array_column($data,'dateAllowedFor'));
        $minStay = join(',',array_column($data,'minStay'));
        $maxStay = join(',',array_column($data,'maxStay'));

        return $this->renderLayout('unitAvailabilityContent.xml',
            [
                'unit'=>$unit,
                'unit_id'=>$reqData['id'],'start_date'=>$start_date,'end_date'=>$end_date,
                'availability'=>$availability,'availableUnitCount'=>$availableUnitCount,
                'changeOver'=>$changeOver,'minStay'=>$minStay,'maxStay'=>$maxStay
            ]
        );
    }

    public function lodgingConfigIndex(): Response{
        $data = $this->listingModel->getList();
        $config = $this->listingModel->getConfig();
        $config = (json_decode($config[0]['data'],true));
        return $this->renderLayout('lodgingConfigIndex.xml',['data'=>$data,'config'=>$config]);
    }

    public function lodgingConfigContent(): Response{
        $reqData = $this->request->getQueryParams();
        if (!isset($reqData['id'])) {
            return $this->renderLayout('error.xml');
        }
        $idGot = $this->getUnitIdByListId($reqData['id']);
        if($idGot){ $reqData['id'] = $idGot; }
        $unit = $this->listingModel->getListing($reqData['id']);
        if (count($unit) == 0) {
            return $this->renderLayout('error.xml');
        }
        $unit = $unit[0];
        $details = json_decode($unit['details'],true);
        $petallowd = ($details['dogs_allowed'] == "yes" || $details['cats_allowed'] == "yes") ? "true":"false"; 
        return $this->renderLayout('lodgingConfigContent.xml',['unit'=>$unit,'unit_id'=>$reqData['id'],'petallowd'=>$petallowd]   );
    }

    public function lodgingRateIndex():Response{
        $data = $this->listingModel->getList();
        return $this->renderLayout('lodgingRateIndex.xml',['data'=>$data]);
    }


    public function getRateContentData($reqData): array{
        $seasonsNOmap = $this->listingModel->getSeasonsByUnitId($reqData['id']);
        $seasons = [];
        $markupAmount = $this->listingModel->getMarkup();
        $cameDates = [];
        foreach($seasonsNOmap as $season){
            if(!in_array($season['date_from'],$cameDates)){
                $cameDates[] = $season['date_from'];
                $markedup = ceil($season['daily_price'] + (($season['daily_price'] * $markupAmount['rate']) / 100 ));
                $seasons[$markedup][] = ['date_from'=>$season['date_from'],'date_to'=>$season['date_to']];
            }
        }

        $charges = $this->listingModel->getChargesByUnit($reqData['id']);
        $chargesTYPEVRBOMAP = [
            "Cleaningfee"=>"CLEANING",
            "AirConditioningFee"=>"AIR_CONDITIONING",
            "AirportShuttleFee"=>"TRANSPORTATION",
            "BedLinenFee"=>"LINENS",
            "BookingFee"=>"ADMINISTRATIVE",
            "ChildrenExtraFee"=>"BABY_BED",
            "ClubCardFee"=>"CLUB",
            "ConservationFee"=>"GARDENING",
            "CreditCardFee"=>"CLASS",
            "DestinationFee"=>"DEPARTURE_EARLY",
            "ElectricityFee"=>"ELECTRICITY",
            "EnvironmentFee"=>"ENERGY",
            "ExtraBedFee"=>"ADDITIONAL_BED",
            "GasFee"=>"GAS",
            "HeatingFee"=>"POOL_HEATING",
            "HousekeepingFee"=>"CLEANING",
            "Insurance"=>"ADMINISTRATIVE",
            "InternetFee"=>"INTERNET",
            "KitchenLinenFee"=>"FOOD",
            "LinenPackageFee"=>"LINENS",
            "OilFee"=>"OIL",
            "ParkingFee"=>"PARKING",
            "PetFee"=>"PET",
            "ResortFee"=>"RESORT",
            "SeaPlaneFee"=>"WATER_CRAFT",
            "ServiceFee"=>"ADMINISTRATIVE",//SERVICE throws ERROR
            "ShuttleBoatFee"=>"TOUR",
            "SkiPass"=>"ADMINISTRATIVE",
            "TourismFee"=>"TOUR",
            "TowelsFee"=>"LINENS_BATH",
            "TransferFee"=>"PROPERTY_FEE",
            "VisaSupportFee"=>"ADMINISTRATIVE",
            "WaterParkFee"=>"WATER_CRAFT_MOORING",
            "WaterUsageFee"=>"WATER",
            "WoodFee"=>"WOOD",
            "WristbandFee"=>"POOL"
        ];
        $listingModelInner =  $this->listingModel;
        $charges = array_map(function ($charge) use($chargesTYPEVRBOMAP,$markupAmount,$listingModelInner){
            if($charge['ct_id'] != ""){
                $chargeTemplate = $listingModelInner->getChargeTemplate($charge['ct_id']);
                if(count($chargeTemplate) > 0){
                    //whenBookingDateIn
                    if($chargeTemplate[0]['effective_start_date'] != NULL && $chargeTemplate[0]['effective_start_date'] != ""){
                        $charge['effective_start_date'] = date('Y-m-d',strtotime($chargeTemplate[0]['effective_start_date']));
                    }
                    if($chargeTemplate[0]['effective_end_date'] != NULL && $chargeTemplate[0]['effective_end_date'] != ""){
                        $charge['effective_end_date'] = date('Y-m-d',strtotime($chargeTemplate[0]['effective_end_date']));
                    }
                    // whenStayDateIn
                    if($chargeTemplate[0]['quote_start_date'] != NULL && $chargeTemplate[0]['quote_start_date'] != ""){
                        $charge['quote_start_date'] = date('Y-m-d',strtotime($chargeTemplate[0]['quote_start_date']));
                    }
                    if($chargeTemplate[0]['quote_end_date'] != NULL && $chargeTemplate[0]['quote_end_date'] != ""){
                        $charge['quote_end_date'] = date('Y-m-d',strtotime($chargeTemplate[0]['quote_end_date']));
                    }
                }
            }
            $charge['value'] = round($charge['value'] + (($charge['value'] * $markupAmount['charges']) / 100 ),2);
            $charge['productCode'] = $chargesTYPEVRBOMAP[$charge['charge']];
            return $charge;
        },$charges);
        $cleaningCharge = array_filter($charges, function ($charge) {
            return $charge['charge'] == "Cleaningfee";
        });
        
        $petCharge = array_filter($charges, function ($charge) {
            return $charge['charge'] == "PetFee";
        }); 

        
        $charges = array_filter($charges, function ($charge) {
            return ($charge['charge'] != "Cleaningfee" && $charge['charge'] != "PetFee");
        });

        
//        percentOfSubtotalFees = cumulativePercentage
        $q = "SELECT * FROM rentalsunited_data where id=1";
        $ru_data_default = $this->listingModel->select($q);
        $ru_data_default = json_decode($ru_data_default[0]['data'],true);
        $deduction_percentage = $ru_data_default['deduction_percentage'];
        
        $percentOfSubtotalFees = array_filter($charges, function ($charge) {
            return $charge['calculation_by'] == "CumulativePercentage";
        });
        
        // $percentOfSubtotalFees = array_map(function ($charge)use($deduction_percentage) {
        //     $charge['value'] = $charge['value'] + $deduction_percentage;
        //     return $charge;
        // },$percentOfSubtotalFees);
        

//        percentOfRentFees = IndependentPercentage
        $percentOfRentFees = array_filter($charges, function ($charge) {
            return $charge['calculation_by'] == "IndependentPercentage";
        });


//        otherFees = otherthen above all
        $otherFees = array_filter($charges, function ($charge) {
            return ($charge['calculation_by'] != "IndependentPercentage" && $charge['calculation_by'] != "CumulativePercentage");
        });

        $taxes = $this->listingModel->getTaxesByUnit($reqData['id']);
        $taxes = array_map(function($tax) use($markupAmount){
            $tax['value'] = round($tax['value'] + (($tax['value'] * $markupAmount['tax']) / 100 ),2);
            return $tax;
        },$taxes);
        $percentOfRentAndFeesTaxRules = array_filter($taxes,function($tax){ return $tax['calculation_by'] == "IndependentPercentage"; });
        $flatTaxRules = array_filter($taxes,function($tax){ return $tax['calculation_by'] != "IndependentPercentage"; });
        
//        return ['seasons'=>$seasons,'charges'=>$charges,
//            'cleaningCharge'=>$cleaningCharge,
//            'percentOfSubtotalFees'=>$percentOfSubtotalFees,'percentOfRentFees'=>$percentOfRentFees,
//            'otherFees'=>$otherFees,'percentOfRentAndFeesTaxRules'=>$percentOfRentAndFeesTaxRules,
//            'flatTaxRules'=>$flatTaxRules];
        return compact('petCharge','seasons','charges','cleaningCharge','percentOfSubtotalFees','percentOfRentFees','otherFees',
            'percentOfRentAndFeesTaxRules','flatTaxRules','deduction_percentage');
    }

    public function lodgingRateContent(): Response
    {
        $reqData = $this->request->getQueryParams();
        if (!isset($reqData['id']) || $reqData['id'] == "") {
            return $this->renderLayout('error.xml');
        }
        $idGot = $this->getUnitIdByListId($reqData['id']);
        if($idGot){ $reqData['id'] = $idGot; }
        $unit = $this->listingModel->getListing($reqData['id']);
        if (count($unit) == 0) {
            return $this->renderLayout('error.xml');
        }
        $unit = $unit[0];
        list('seasons' => $seasons, 'charges' => $charges,
            'cleaningCharge' => $cleaningCharge,
            'percentOfSubtotalFees' => $percentOfSubtotalFees, 'percentOfRentFees' => $percentOfRentFees,
            'otherFees' => $otherFees, 'percentOfRentAndFeesTaxRules' => $percentOfRentAndFeesTaxRules,
            'flatTaxRules' => $flatTaxRules,'petCharge'=>$petCharge
            )
            = $this->getRateContentData($reqData);
        return $this->renderLayout('lodgingRateContent.xml', [
            'unit'=>$unit,
            'unit_id' => $reqData['id'],
            'petCharge'=>$petCharge,
            'seasons' => $seasons,
            'cleaningCharge' => $cleaningCharge,
            'percentOfSubtotalFees' => $percentOfSubtotalFees,
            'percentOfRentFees' => $percentOfRentFees,
            'otherFees' => $otherFees,
            'percentOfRentAndFeesTaxRules' => $percentOfRentAndFeesTaxRules,
            'flatTaxRules' => $flatTaxRules
        ]);
    }

    public function pushLodgingRateUpdate(): Response{
        $reqData = $this->request->getQueryParams();
        if (!isset($reqData['id'])) {
            return $this->renderLayout('error.xml');
        }
        $idGot = $this->getUnitIdByListId($reqData['id']);
        if($idGot){ $reqData['id'] = $idGot; }
        $unit = $this->listingModel->getListing($reqData['id']);
        if (count($unit) == 0) {
            return $this->renderLayout('error.xml');
        }
        $unit = $unit[0];
        list('seasons' => $seasons, 'charges' => $charges,
            'cleaningCharge' => $cleaningCharge,
            'percentOfSubtotalFees' => $percentOfSubtotalFees, 'percentOfRentFees' => $percentOfRentFees,
            'otherFees' => $otherFees, 'percentOfRentAndFeesTaxRules' => $percentOfRentAndFeesTaxRules,
            'flatTaxRules' => $flatTaxRules
            )
            = $this->getRateContentData($reqData);

        $requestContent = $this->renderLayoutRow('lodgingRateUpdate.xml', [
            'unit'=>$unit,
            'unit_id' => $reqData['id'],
            'seasons' => $seasons,
            'cleaningCharge' => $cleaningCharge,
            'percentOfSubtotalFees' => $percentOfSubtotalFees,
            'percentOfRentFees' => $percentOfRentFees,
            'otherFees'=>$otherFees,
            'percentOfRentAndFeesTaxRules'=>$percentOfRentAndFeesTaxRules,
            'flatTaxRules'=>$flatTaxRules
        ]);

        $reqClient = new Client([
            'base_uri'=>VRBO_lodgingRateUpdate_URL
        ]);
        $responseFromVRBO = $reqClient->post('',[
            'headers'=>[
                'Content-Type'=>'application/xml'
            ],
            'body'=>$requestContent
        ]);
        $this->response->getBody()->write($responseFromVRBO->getBody()->getContents());
        return $this->response->withAddedHeader('Content-type','application/xml');
    }

    public function pushUnitAvailabilityUpdate():Response{
        // $reqData = $this->request->getQueryParams();
        // if (!isset($reqData['id'])) {
        //     return $this->renderLayout('error.xml');
        // }
        // $idGot = $this->getUnitIdByListId($reqData['id']);
        // if($idGot){ $reqData['id'] = $idGot; }
        // $unit = $this->listingModel->getListing($reqData['id']);
        // if (count($unit) == 0) {
        //     return $this->renderLayout('error.xml');
        // }
        // $unit = $unit[0];
        // $data = $this->listingModel->getListing($reqData['id']);
        // if (count($data) == 0) {
        //     return $this->renderLayout('error.xml');
        // }
        // $start_date = date('Y-m-d');
        // $end_date = date('Y-m-d',strtotime("+1 year"));
        // $data = $this->listingModel->getAvailibilityByUnitId($reqData['id'],$start_date,$end_date);
        // if (count($data) == 0) {
        //     return $this->renderLayout('error.xml');
        // }

        // $availability = join('',array_column($data,'isAvailable'));
        // $availableUnitCount = join(',',array_column($data,'availableUnitCount'));
        // $changeOver = join('',array_column($data,'dateAllowedFor'));
        // $minStay = join(',',array_column($data,'minStay'));

        $reqData = $this->request->getQueryParams();
        if (!isset($reqData['id'])) {
            return $this->renderLayout('error.xml');
        }
        $idGot = $this->getUnitIdByListId($reqData['id']);
        if($idGot){ $reqData['id'] = $idGot; }
        $data = $this->listingModel->getListing($reqData['id']);
        if (count($data) == 0) {
            return $this->renderLayout('error.xml');
        }
        $unit = $data[0];
        $start_date = date('Y-m-d');
        $end_date = date('Y-m-d',strtotime("+1 year"));
        $data = $this->listingModel->getAvailibilityByUnitId($reqData['id'],$start_date,$end_date);
        if (count($data) == 0) {
            return $this->renderLayout('error.xml');
        }

        $availability = join('',array_column($data,'isAvailable'));
        $availableUnitCount = join(',',array_column($data,'availableUnitCount'));
        $changeOver = join('',array_column($data,'dateAllowedFor'));
        $minStay = join(',',array_column($data,'minStay'));
        $maxStay = join(',',array_column($data,'maxStay'));

        $requestContent = $this->renderLayoutRow('unitAvailabilityUpdate.xml', [
                'unit'=>$unit,
                'unit_id'=>$reqData['id'],'start_date'=>$start_date,'end_date'=>$end_date,
                'availability'=>$availability,'availableUnitCount'=>$availableUnitCount,
                'changeOver'=>$changeOver,'minStay'=>$minStay,'maxStay'=>$maxStay
            ]);

        $reqClient = new Client([
            'base_uri'=>VRBO_unitAvailabilityUpdate_URL
        ]);
        $responseFromVRBO = $reqClient->post('',[
            'headers'=>[
                'Content-Type'=>'application/xml'
            ],
            'body'=>$requestContent
        ]);
        $this->response->getBody()->write($responseFromVRBO->getBody()->getContents());
        return $this->response->withAddedHeader('Content-type','application/xml');
    }

}