<?php

function ovis_plugin_ajax_handler() {
    require_once __DIR__ . '/../classes/class.ajax.php';
    $oAjax = new Ajax();
    
    if(!defined('MAX_REQUEST_SIZE_BYTES')) define('MAX_REQUEST_SIZE_BYTES', 5 * 1024 * 1024); // 5 MB total request size
    if(!defined('OVIS_API_ENABLE_CACHE')) define('OVIS_API_ENABLE_CACHE', true);
    if(!defined('OVIS_PLUGIN_DEV_MODE')) define('OVIS_PLUGIN_DEV_MODE', false);

    if( $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
        wp_send_json_error( ['message' => 'invalid-method'], 405 );
        wp_die();
    }
    
    if( isset($_SERVER['CONTENT_LENGTH']) && is_numeric($_SERVER['CONTENT_LENGTH']) ) {
        if( (int)$_SERVER['CONTENT_LENGTH'] > MAX_REQUEST_SIZE_BYTES ) {
            wp_send_json_error(['message' => 'request-too-large'], 413);
            wp_die();
        }
    }
    
    if( empty( $_POST ) ) {
        wp_send_json_error( ['message' => 'empty-req-body'], 400 );
        wp_die();
    }

    if(defined('OVIS_PLUGIN_DEV_MODE') && OVIS_PLUGIN_DEV_MODE === true) {
        $startTimeTop = microtime(true);
        $startTop = hrtime(true);
    }

    global $wpdb;
    $sQuery = "
    SELECT OVIS_authentication FROM 
        ". $wpdb->prefix ."ovis
    WHERE 
        OVIS_ID = 1
    ";
    
    $sResult = $wpdb->get_results($sQuery, ARRAY_A);
    
    if( empty( $sResult ) ) {
        wp_send_json_error( ['message' => 'no-api-key'], 403 );
        wp_die();
    }
    
    $authenticationKey = $sResult[0]['OVIS_authentication'];
    
    if(empty($authenticationKey)) {
        wp_send_json_error( ['message' => 'no-api-key'], 403 );
        wp_die();
    }
    
    require_once __DIR__ . '/../classes/class.ovis_compat.php';
    $oOvisApi = new Ovis();
    $oOvisApi->useProductionApi();
    $oOvisApi->setAuthKey($authenticationKey);
    
    $oResponse = new \stdClass();
    $oResponse->message = '';
    $oResponse->success = false;
    
    $sAction        = $oAjax->getPostField('ovisAction');
    $iPage          = $oAjax->getPostField('page', FILTER_DEFAULT, 1);
    $sRealm         = $oAjax->getPostField('realm', FILTER_DEFAULT, 'ovis');
    
    $noFiltersMode = !empty($oAjax->getPostField('no_filter_mode')) ? true : false;
    
    $oSettingsOptions                           = new \stdClass();
    $oSettingsOptions->itemsPerPage             = $oAjax->getPostField('settings_items_per_page', FILTER_DEFAULT, 12);
    $oSettingsOptions->itemsPerPageNoFilters    = $oAjax->getPostField('settings_items_per_page_no_filter', FILTER_DEFAULT, 12);
    
    /**
     * Retrieve & store form values
     */
    $oFormOptions                        = new \stdClass();
    $oFormOptions->sort                  = $oAjax->getPostField('form_ovis-sort-field');
    $oFormOptions->category              = $oAjax->getPostField('form_category', FILTER_DEFAULT, 'all');
    $oFormOptions->subCategory           = $oAjax->getPostField('form_subcategory', FILTER_DEFAULT, 'all', true);
    $oFormOptions->condition             = $oAjax->getPostField('form_condition', FILTER_DEFAULT, 'all');
    $oFormOptions->brand                 = $oAjax->getPostField('form_brand', FILTER_DEFAULT, array(), true);
    $oFormOptions->modelTypeVersion      = $oAjax->getPostField('form_model_type_version');
    $oFormOptions->keyword               = $oAjax->getPostField('form_keyword');
    $oFormOptions->priceFrom             = $oAjax->getPostField('form_price_from');
    $oFormOptions->priceTo               = $oAjax->getPostField('form_price_to');
    $oFormOptions->constructionYearFrom  = $oAjax->getPostField('form_construction_from');
    $oFormOptions->constructionYearTo    = $oAjax->getPostField('form_construction_to');
    $oFormOptions->weightFrom            = $oAjax->getPostField('form_maxweight_from');
    $oFormOptions->weightTo              = $oAjax->getPostField('form_maxweight_to');
    $oFormOptions->sleepingPlacesFrom    = $oAjax->getPostField('form_sleepingplaces_from');
    $oFormOptions->sleepingPlacesTo      = $oAjax->getPostField('form_sleepingplaces_to');
    $oFormOptions->seatbeltPlacesFrom    = $oAjax->getPostField('form_seatbelts_from');
    $oFormOptions->seatbeltPlacesTo      = $oAjax->getPostField('form_seatbelts_to');
    $oFormOptions->lengthFrom            = $oAjax->getPostField('form_length_from');
    $oFormOptions->lengthTo              = $oAjax->getPostField('form_length_to');
    $oFormOptions->widthFrom             = $oAjax->getPostField('form_width_from');
    $oFormOptions->widthTo               = $oAjax->getPostField('form_width_to');
    $oFormOptions->mileageFrom           = $oAjax->getPostField('form_mileage_from');
    $oFormOptions->mileageTo             = $oAjax->getPostField('form_mileage_to');
    $oFormOptions->powerFrom             = $oAjax->getPostField('form_power_from');
    $oFormOptions->powerTo               = $oAjax->getPostField('form_power_to');
    $oFormOptions->rentalDateFrom        = $oAjax->getPostField('form_rental_date_from');
    $oFormOptions->rentalDateTo          = $oAjax->getPostField('form_rental_date_to');
    $oFormOptions->fuel                  = $oAjax->getPostField('form_fuel', FILTER_DEFAULT, array(), true);
    $oFormOptions->euroclass             = $oAjax->getPostField('form_euroclass', FILTER_DEFAULT, array(), true);
    $oFormOptions->transmission          = $oAjax->getPostField('form_transmission');
    $oFormOptions->division              = $oAjax->getPostField('form_division', FILTER_DEFAULT, array(), true);
    $oFormOptions->user                  = $oAjax->getPostField('form_ovis-user');
    $oFormOptions->dealer                = $oAjax->getPostField('form_provider');
    $oFormOptions->fastsailing           = $oAjax->getPostField('form_fastsailing');
    $oFormOptions->sort_changed          = $oAjax->getPostField('form_sort_changed');
    
    /**
     * Retrieve & store shortcode settings
     */
    $oShortcodeOptions                          = new \stdClass();
    $oShortcodeOptions->realm                   = $oAjax->getPostField('shortcode_ovis_realm', FILTER_DEFAULT, 'ovis');
    $oShortcodeOptions->brand                   = $oAjax->getPostField('shortcode_ovis_brand');
    $oShortcodeOptions->category                = $oAjax->getPostField('shortcode_ovis_categories');
    $oShortcodeOptions->condition               = $oAjax->getPostField('shortcode_ovis_condition', FILTER_DEFAULT, 'all');
    $oShortcodeOptions->constructionYear        = $oAjax->getPostField('shortcode_ovis_construction_year');
    $oShortcodeOptions->hideSold                = $oAjax->getPostField('shortcode_ovis_hide_sold');
    $oShortcodeOptions->fuel                    = $oAjax->getPostField('shortcode_ovis_fuel');
    $oShortcodeOptions->immediatelyAvailable    = $oAjax->getPostField('shortcode_ovis_immediately_available');
    $oShortcodeOptions->keyword                 = $oAjax->getPostField('shortcode_ovis_keyword');
    $oShortcodeOptions->modelYear               = $oAjax->getPostField('shortcode_ovis_model_year');
    $oShortcodeOptions->rental                  = $oAjax->getPostField('shortcode_ovis_rental');
    $oShortcodeOptions->sort                    = $oAjax->getPostField('shortcode_ovis_sort');
    $oShortcodeOptions->soldAtEnd               = $oAjax->getPostField('shortcode_ovis_sold_at_end');
    $oShortcodeOptions->specificDealer          = $oAjax->getPostField('shortcode_ovis_specific_dealer');
    $oShortcodeOptions->status                  = $oAjax->getPostField('shortcode_ovis_status');
    $oShortcodeOptions->subcategories           = $oAjax->getPostField('shortcode_ovis_subcategories');
    
    $aUserIds = array();
    
    if(!empty($oShortcodeOptions->specificDealer)) {
        array_push($aUserIds, (string)$oShortcodeOptions->specificDealer);
    } else {
        if(!empty($oFormOptions->user)) {
            array_push($aUserIds, (string)$oFormOptions->user);
        }
        if(!empty($oFormOptions->dealer)) {
            array_push($aUserIds, (string)$oFormOptions->dealer);
        }
    }
    
    
    $iPresentationId = $oAjax->getPostField('ovis-presentation-id', FILTER_SANITIZE_NUMBER_INT);
    
    
    /**
     * CTA form
     */
    if($sAction === 'contactDealer' || $sAction === 'rentalRequest' || $sAction === 'tradeInRequest') {
        $oCtaFormBody = new \stdClass();
    
        $oCtaFormBody->userId               = $oAjax->getPostField('ovis-contact-user', FILTER_SANITIZE_NUMBER_INT);
    
        $oCtaFormBody->presentationId       = $oAjax->getPostField('ovis-contact-object', FILTER_SANITIZE_NUMBER_INT);
    
        $oCtaFormBody->url                  = $oAjax->getPostField('ovis-contact-objecturl', FILTER_SANITIZE_URL);
    
        $oCtaFormBody->category             = $oAjax->getPostField('ovis-contact-soort');
    
        $oCtaFormBody->condition            = $oAjax->getPostField('ovis-contact-conditie');
    
        $oCtaFormBody->brand                = $oAjax->getPostField('ovis-contact-merk');
    
        $oCtaFormBody->modelType            = $oAjax->getPostField('ovis-contact-model');
    
        $oCtaFormBody->licensePlate         = $oAjax->getPostField('ovis-contact-kenteken');
    
        $oCtaFormBody->condition            = $oAjax->getPostField('ovis-contact-conditie');
        
        $oCtaFormBody->damage               = $oAjax->getPostField('ovis-contact-schade');
    
        $oCtaFormBody->constructionYear     = $oAjax->getPostField('ovis-contact-bouwjaar');
        
        $oCtaFormBody->mileage              = $oAjax->getPostField('ovis-contact-kilometerstand');
    
        $oCtaFormBody->upholstery           = $oAjax->getPostField('ovis-contact-staatbekleding');
    
        $oCtaFormBody->tires                = $oAjax->getPostField('ovis-contact-staatbanden');
    
        $oCtaFormBody->date                 = $oAjax->getPostField('ovis-contact-periode');
    
        $oCtaFormBody->numberOfPersons      = $oAjax->getPostField('ovis-contact-persons');
    
        $oCtaFormBody->address              = $oAjax->getPostField('ovis-contact-adres');
    
        $oCtaFormBody->houseNumber          = $oAjax->getPostField('ovis-contact-housenumber');
    
        $oCtaFormBody->zipcode              = $oAjax->getPostField('ovis-contact-zipcode');
    
        $oCtaFormBody->city                 = $oAjax->getPostField('ovis-contact-city');
    
        $oCtaFormBody->name                 = $oAjax->getPostField('ovis-contact-name');
        $oCtaFormBody->name                 = $oCtaFormBody->name ? htmlspecialchars(strip_tags($oCtaFormBody->name), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') : null;
    
        $oCtaFormBody->phone                = $oAjax->getPostField('ovis-contact-phone', FILTER_SANITIZE_NUMBER_INT);
    
        $oCtaFormBody->email                = $oAjax->getPostField('ovis-contact-email', FILTER_SANITIZE_EMAIL);
        
        $oCtaFormBody->message              = $oAjax->getPostField('ovis-contact-message');
        $oCtaFormBody->message              = $oCtaFormBody->message ? htmlspecialchars(strip_tags($oCtaFormBody->message), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') : null;
        
        $oCtaFormBody->requiredImage        = $oAjax->getPostField('ovis-required-image');
        
        $oCtaFormBody->images               = $oAjax->getPostField('file_base64', FILTER_DEFAULT, null, true);
    
        $oCtaFormBody->utmSource            = $oAjax->getPostField('ovis-contact-utm-source');
        $oCtaFormBody->utmSource            = $oCtaFormBody->utmSource ? htmlspecialchars(strip_tags($oCtaFormBody->utmSource), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') : null;
    
        $oCtaFormBody->utmCampaign          = $oAjax->getPostField('ovis-contact-utm-campaign');
        $oCtaFormBody->utmCampaign          = $oCtaFormBody->utmCampaign ? htmlspecialchars(strip_tags($oCtaFormBody->utmCampaign), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') : null;
    
        $oCtaFormBody->utmContent           = $oAjax->getPostField('ovis-contact-utm-content');
        $oCtaFormBody->utmContent           = $oCtaFormBody->utmContent ? htmlspecialchars(strip_tags($oCtaFormBody->utmContent), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') : null;
    }
    
    
    /**
     * Stop the development environment timers
     */
    if(OVIS_PLUGIN_DEV_MODE) {
        $endTimeTop = (microtime(true) - $startTimeTop);
        $endTop = (hrtime(true) - $startTop)/1e+9;
    }
    
    require_once __DIR__ . '/../classes/class.ovis_minmax.php';
    $oMinMaxHelper = new OvisMinMax();

    switch($sAction) {
    
        case 'getAllPresentations':
    
            $bCacheEnabled = false;
            $bCacheLifetime = 3600;
    
            if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) {
                $cacheFileKey = md5(json_encode($oShortcodeOptions) . json_encode($oFormOptions) . json_encode($oSettingsOptions) . $noFiltersMode . $iPage . $authenticationKey);
                $oCacheData = $oAjax->getCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, $bCacheLifetime);
                if(!empty($oCacheData)) {
                    $oAjax->setCacheHeaders();
                    wp_send_json( $oCacheData );
                    wp_die();
                }
            }
    
            /**
             * Start timers in development environment
             */
            if(OVIS_PLUGIN_DEV_MODE) {
                $startTime = microtime(true);
                $start = hrtime(true);
            }

            $oOvisApi->setCompactOutput(true);
    
            /**
             * Items per page
             */
            if($noFiltersMode && $oSettingsOptions->itemsPerPageNoFilters) {
                $oOvisApi->setItemsPerPage((int)$oSettingsOptions->itemsPerPageNoFilters);
            }
            else if($oSettingsOptions->itemsPerPage) {
                $oOvisApi->setItemsPerPage((int)$oSettingsOptions->itemsPerPage);
            } else {
                $oOvisApi->setItemsPerPage(12);
            }
			
    
            /**
             * Sorting
             */
            $sorting = array();

            if(isset($oShortcodeOptions->soldAtEnd) && $oShortcodeOptions->soldAtEnd === 'yes') {
                array_push($sorting, explode('_', 'sold_up'));
            }

            // Check if shortcode sort is set and has different value then the form sorting and that the form sorting changed
            if($oShortcodeOptions->sort && $oShortcodeOptions->sort !== $oFormOptions->sort && $oFormOptions->sort_changed === 'yes') {
                // Set sorting according to form
                array_push($sorting, explode('_', $oFormOptions->sort));
            } else {
                if(!empty($oFormOptions->sort) && $oFormOptions->sort_changed === 'yes') {
                    // Set according to form
                    array_push($sorting, explode('_', $oFormOptions->sort));
				} elseif(!empty($oShortcodeOptions->sort)) {
                    // Set according to shortcode
                    array_push($sorting, explode('_', $oShortcodeOptions->sort));
				} else {
                    // Set according to form
                    array_push($sorting, explode('_', $oFormOptions->sort));
                }
            }
            $oOvisApi->setSorting($sorting);


            /**
             * Realm
             * !Force selected shortcode option
             */
            if($oShortcodeOptions->realm) {
                $oOvisApi->setRealm($oShortcodeOptions->realm);
            }
    
            /**
             * Rental
             * !Force selected shortcode option
             */
            if($oShortcodeOptions->rental) {
                $oOvisApi->setRental(boolval($oShortcodeOptions->rental));
            }
    
            /**
             * Status
             */
            if($oShortcodeOptions->status) {
                $oOvisApi->setStatus($oShortcodeOptions->status);
            }
    
            /**
             * Available
             */
            if($oShortcodeOptions->immediatelyAvailable) {
                $oOvisApi->setAvailable($oShortcodeOptions->immediatelyAvailable);
            }
    
            /**
             * Category
             */
            if($oShortcodeOptions->category) {
    
                $categoryMapping = [
                    'caravan' => 'caravan',
                    'caravans' => 'caravan',
                    'camper' => 'camper',
                    'kampeerauto' => 'camper',
                    'campers' => 'camper',
                    'mobilehome' => 'mobilehome',
                    'stacaravan' => 'mobilehome',
                    'stacaravans' => 'mobilehome',
                    'mobilehomes' => 'mobilehome',
                    'tenttrailer' => 'tenttrailer',
                    'tenttrailers' => 'tenttrailer',
                    'trailer' => 'trailer',
                    'trailers' => 'trailer',
                    'aanhangwagen' => 'trailer',
                    'boot' => 'boat',
                    'boat' => 'boat',
                    'boats' => 'boat',
                    'boten' => 'boat',
                    'motor' => 'engine',
                    'engine' => 'engine',
                    'boattrailer' => 'boattrailer',
                    'boottrailer' => 'boattrailer'
                ];
    
                $formCategory = $oFormOptions->category ? strtolower($oFormOptions->category) : '';
    
                if(isset($categoryMapping[$formCategory])) {
                    $formCategory = $categoryMapping[$formCategory];
                }
    
                $shortcodeCategoriesRaw = explode(',', $oShortcodeOptions->category);
                $shortcodeCategories = [];
    
                foreach($shortcodeCategoriesRaw as $cat) {
                    
                    $cat = strtolower(trim($cat));
                    
                    if(isset($categoryMapping[$cat])) {
                        $cat = $categoryMapping[$cat];
                    }
                    
                    $shortcodeCategories[] = $cat;
                }
    
                /**
                 * Check if the form category is set and the selected category is part of the shortcode categories
                 */
                if($formCategory && in_array($formCategory, $shortcodeCategories)) {
                    $oOvisApi->setCategory($formCategory);
                } else {
    
                    /**
                     * !Force selected shortcode option
                     */
                    $oOvisApi->setCategory($shortcodeCategories);
                }
            }
    
            /**
             * Subcategory
             */
            if($oShortcodeOptions->subcategories) {
                $oOvisApi->setSubCategory($oShortcodeOptions->subcategories);
            } else {
                $oOvisApi->setSubCategory($oFormOptions->subCategory);
            }
    
            /**
             * Page
             */
            $oOvisApi->setPage((int)$iPage);
    
            /**
             * Hide sold
             * !Force selected shortcode option
             */
            if($oShortcodeOptions->hideSold) {
                $oOvisApi->setHideSold($oShortcodeOptions->hideSold);
            }
    
            /**
             * Set dealer
             * !Force selected shortcode option
             */
            $oOvisApi->setDealers($aUserIds);

            /**
             * Set division
             */
            if( !empty( $oFormOptions->division ) ) {
                $oOvisApi->setDivision( $oFormOptions->division );
            }
    
            /**
             * Condition
             */
            if($oShortcodeOptions->condition) {
    
                /**
                 * Check if all conditions are allowed by shortcode
                 */
                if($oShortcodeOptions->condition === 'all') {
                    if($oFormOptions->condition) {
                        $oOvisApi->setCondition($oFormOptions->condition);
                    }
                } else {
    
                    /**
                     * !Force selected shortcode option
                     */
                    $oOvisApi->setCondition($oShortcodeOptions->condition);
                }
            }
    
            /**
             * Brand
             */
            if($oShortcodeOptions->brand) {
                $oOvisApi->setBrand($oShortcodeOptions->brand);
            } else {
                $oOvisApi->setBrand($oFormOptions->brand);
            }
    
            /**
             * Model type version
             */
            $oOvisApi->setModelTypeVersion($oFormOptions->modelTypeVersion);
    
            /**
             * Keyword
             */
            if($oShortcodeOptions->keyword) {
                $oOvisApi->setKeyword($oShortcodeOptions->keyword);
            } else {
                $oOvisApi->setKeyword($oFormOptions->keyword);
            }
            
            /**
             * Price
             */
            $oOvisApi->setPriceFrom(floatval($oFormOptions->priceFrom));
            $oOvisApi->setPriceTo(floatval($oFormOptions->priceTo));
            
            /**
             * Model year
             * 
             * The shortcode option returns the model year as 'yearFrom-yearTo'
             * So we need to explode on '-' and assign the array index to the correct setter
             */
            if($oShortcodeOptions->modelYear) {
                $aModelYear = explode('-', $oShortcodeOptions->modelYear);
                $oOvisApi->setModelYearFrom((int)$aModelYear[0]);
                $oOvisApi->setModelYearTo((int)$aModelYear[1]);
            }
    
            /**
             * Construction year
             * 
             * The shortcode option returns the construction year as 'yearFrom-yearTo'
             * So we need to explode on '-' and assign the array index to the correct setter
             */
            if($oShortcodeOptions->constructionYear) {
                
                $aConstructionYear = explode('-', $oShortcodeOptions->constructionYear);
    
                if(is_array($aConstructionYear) && (count($aConstructionYear) > 1)) {
                    $oOvisApi->setConstructionYearFrom((int)$aConstructionYear[0]);
                    $oOvisApi->setConstructionYearTo((int)$aConstructionYear[1]);
                }
            } else {
                $oOvisApi->setConstructionYearFrom((int)$oFormOptions->constructionYearFrom);
                $oOvisApi->setConstructionYearTo((int)$oFormOptions->constructionYearTo);
            }
    
            /**
             * Weight
             */
            $oOvisApi->setWeightFrom((int)$oFormOptions->weightFrom);
            $oOvisApi->setWeightTo((int)$oFormOptions->weightTo);
    
            /**
             * Sleeping places
             */
            $oOvisApi->setSleepingPlacesFrom((int)$oFormOptions->sleepingPlacesFrom);
            $oOvisApi->setSleepingPlacesTo((int)$oFormOptions->sleepingPlacesTo);
    
            /**
             * Seatbelt places
             */
            $oOvisApi->setSeatbeltPlacesFrom((int)$oFormOptions->seatbeltPlacesFrom);
            $oOvisApi->setSeatbeltPlacesTo((int)$oFormOptions->seatbeltPlacesTo);
        
            /**
             * Mileage
             */
            $oOvisApi->setMileageFrom((int)$oFormOptions->mileageFrom);
            $oOvisApi->setMileageTo((int)$oFormOptions->mileageTo);

            /**
             * Length
             */
            $oOvisApi->setLengthFrom((int)$oFormOptions->lengthFrom);
            $oOvisApi->setLengthTo((int)$oFormOptions->lengthTo);
    
            /**
             * Width
             */
            $oOvisApi->setWidthFrom((int)$oFormOptions->widthFrom);
            $oOvisApi->setWidthTo((int)$oFormOptions->widthTo);
    
            /**
             * Power
             */
            $oOvisApi->setPowerFrom((int)$oFormOptions->powerFrom);
            $oOvisApi->setPowerTo((int)$oFormOptions->powerTo);
    
            /**
             * Rental date
             */
            $oOvisApi->setRentalDateFrom($oFormOptions->rentalDateFrom);
            $oOvisApi->setRentalDateTo($oFormOptions->rentalDateTo);
    
            /**
             * Fuel
             */
            if($oShortcodeOptions->fuel) {
                $oOvisApi->setSelecteFuelTypes($oShortcodeOptions->fuel);
            } else {
                $oOvisApi->setSelecteFuelTypes($oFormOptions->fuel);
            }
    
            /**
             * Transmission
             */
            $oOvisApi->setSelectedTransmissionTypes($oFormOptions->transmission);
            
            /**
             * Euroclass
             */
            $oOvisApi->setEuroclass($oFormOptions->euroclass);

            /**
             * Fast sailing
             */
            if(isset($oFormOptions->fastsailing) && (strtolower($oFormOptions->fastsailing) == 'ja' || strtolower($oFormOptions->fastsailing) == 'nee')) {
                $oOvisApi->setFastSailing($oFormOptions->fastsailing);
            }

            $oAllPresentations = $oOvisApi->fetchPresentations();
            
            $oSimplifiedPresentations = null;
    
            if(!empty($oAllPresentations) 
                && !empty($oAllPresentations->data) 
                && $oAllPresentations->result === true 
                && isset($oAllPresentations->data->totalInSet) 
                && (int)$oAllPresentations->data->totalInSet > 0) {
    
                $oSimplifiedPresentations = $oOvisApi->simplifyPresentations($oAllPresentations);
    
                if(!empty($oSimplifiedPresentations)) {
                    if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) $oAjax->addCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, $oSimplifiedPresentations, $bCacheLifetime);
                }
            }
    
            /**
             * Add additional fields to presentations object in development environment
             */
            if(OVIS_PLUGIN_DEV_MODE) {
                
                $oDebugObject = new \stdClass();
    
                $allTimers = new \stdClass();
                $allTimers->process_presentation_pre_exec_time_mr = $endTimeTop;
                $allTimers->process_presentation_pre_exec_time_hr = $endTop;
                $allTimers->process_presentation_action_exec_time_mr = (microtime(true) - $startTime);
                $allTimers->process_presentation_action_exec_time__hr = (hrtime(true) - $start)/1e+9;
                $oDebugObject->timers = $allTimers;
                $oDebugObject->shortcode_options = $oShortcodeOptions;
                $oDebugObject->form_options = $oFormOptions;
                $oDebugObject->curl_info = $oOvisApi->getCurlInfo();
                $oDebugObject->http_request_body = $oOvisApi->getHttpRequestBody();
                $oDebugObject->http_request_headers = $oOvisApi->getHttpRequestHeaders();
    
                if(!empty($oSimplifiedPresentations)) {
                    $oSimplifiedPresentations->debug = $oDebugObject;
                } else {
                    if(!empty($oAllPresentations)) {
                        $oAllPresentations->debug = $oDebugObject;
                    }
                }
            }
    
            $oAjax->setSuccessHeaders();
            wp_send_json( !empty( $oSimplifiedPresentations ) ? $oSimplifiedPresentations : $oAllPresentations );
            wp_die();
    
        case 'getAllMinMax':
    
            $bCacheEnabled = true;
            $bCacheLifetime = 3600;
    
            if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) {
                $cacheFileKey = md5($sAction . $authenticationKey . $sRealm);
                $oCacheData = $oAjax->getCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, $bCacheLifetime);
                if(!empty($oCacheData)) {
                    $oAjax->setCacheHeaders();
                    wp_send_json( $oCacheData );
                    wp_die();
                }
            }
    
            $oOvisApi->setRealm($sRealm);
            $oAllFilters = $oOvisApi->fetchMinMax();
            $oAllFiltersMerged = $oMinMaxHelper->merge($oAllFilters);
    
            if(!empty($oAllFilters) && isset($oAllFilters->data) && !empty($oAllFilters->data)) {
                if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) $oAjax->addCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, !empty($oAllFiltersMerged) ? $oAllFiltersMerged : $oAllFilters, $bCacheLifetime);
            }
    
            if(OVIS_PLUGIN_DEV_MODE) {
                $oDebugObject = new \stdClass();
                $oDebugObject->curl_info = $oOvisApi->getCurlInfo();
                $oDebugObject->http_request_body = $oOvisApi->getHttpRequestBody();
                $oDebugObject->http_request_headers = $oOvisApi->getHttpRequestHeaders();
    
                if(!empty($oAllFiltersMerged)) {
                    $oAllFiltersMerged->debug = $oDebugObject;
                } else {
                    $oAllFilters->debug = $oDebugObject;
                }
            }
    
            $oAjax->setSuccessHeaders();
            wp_send_json( !empty($oAllFiltersMerged) ? $oAllFiltersMerged : $oAllFilters );
            wp_die();
        
        case 'getClientMinMax':
    
            $bCacheEnabled = true;
            $bCacheLifetime = 3600;
    
            if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) {
                $cacheFileKey = md5($sAction . $authenticationKey . $sRealm . json_encode($aUserIds));
                $oCacheData = $oAjax->getCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, $bCacheLifetime);
                if(!empty($oCacheData)) {
                    $oAjax->setCacheHeaders();
                    wp_send_json( $oCacheData );
                    wp_die();
                }
            }
    
            $oOvisApi->setRealm($sRealm);
            $oOvisApi->setDealers($aUserIds);
            $oAllFilters = $oOvisApi->fetchMinMaxClient();
            $oAllFiltersMerged = $oMinMaxHelper->merge($oAllFilters);
    
            if(!empty($oAllFilters) && isset($oAllFilters->data) && !empty($oAllFilters->data)) {
                if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) $oAjax->addCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, !empty($oAllFiltersMerged) ? $oAllFiltersMerged : $oAllFilters, $bCacheLifetime);
            }
    
            $oAjax->setSuccessHeaders();
            wp_send_json( !empty($oAllFiltersMerged) ? $oAllFiltersMerged : $oAllFilters );
            wp_die();
    
        case 'getAllDivisions':
    
            $bCacheEnabled = true;
            $bCacheLifetime = 3600;
    
            if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) {
                $cacheFileKey = md5($sAction . $authenticationKey . $sRealm);
                $oCacheData = $oAjax->getCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, $bCacheLifetime);
                if(!empty($oCacheData)) {
                    $oAjax->setCacheHeaders();
                    wp_send_json( $oCacheData );
                    wp_die();
                }
            }
    
            $oOvisApi->setRealm($sRealm);
            $oAllDivisions = $oOvisApi->fetchDivisions();
    
            if(!empty($oAllDivisions)) {
                if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) $oAjax->addCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, $oAllDivisions, $bCacheLifetime);
            }
    
            $oAjax->setSuccessHeaders();
            wp_send_json( $oAllDivisions );
            wp_die();
    
        case 'getAllTranslations':
    
            $bCacheEnabled = true;
            $bCacheLifetime = 604800;
    
            if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) {
                $cacheFileKey = md5($sAction . $authenticationKey);
                $oCacheData = $oAjax->getCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, $bCacheLifetime);
                if(!empty($oCacheData)) {
                    $oAjax->setCacheHeaders();
                    wp_send_json( $oCacheData );
                    wp_die();
                }
            }
    
            $oAllTranslations = $oOvisApi->fetchTranslations();
    
            if(!empty($oAllTranslations)) {
                if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) $oAjax->addCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, $oAllTranslations, $bCacheLifetime);
            }
    
            $oAjax->setSuccessHeaders();
            wp_send_json( $oAllTranslations );
            wp_die();
    
        case 'getAllCategories':
    
            $bCacheEnabled = true;
            $bCacheLifetime = 604800;
    
            if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) {
                $cacheFileKey = md5($sAction . $authenticationKey . $sRealm);
                $oCacheData = $oAjax->getCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, $bCacheLifetime);
                if(!empty($oCacheData)) {
                    $oAjax->setCacheHeaders();
                    wp_send_json( $oCacheData );
                    wp_die();
                }
            }
            
            $oOvisApi->setRealm($sRealm);
            $oAllCategories = $oOvisApi->fetchCategories();
    
            if(!empty($oAllCategories)) {
                if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) $oAjax->addCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, $oAllCategories, $bCacheLifetime);
            }
    
            $oAjax->setSuccessHeaders();
            wp_send_json( $oAllCategories );
            wp_die();
        
        case 'getAllUsers':
    
            $bCacheEnabled = true;
            $bCacheLifetime = 3600;
    
            if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) {
                $cacheFileKey = md5($sAction . $authenticationKey . $sRealm);
                $oCacheData = $oAjax->getCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, $bCacheLifetime);
                if(!empty($oCacheData)) {
                    $oAjax->setCacheHeaders();
                    wp_send_json( $oCacheData );
                    wp_die();
                }
            }
            
            $oOvisApi->setRealm($sRealm);
            $oAllUsers = $oOvisApi->fetchUsers();
    
            if(!empty($oAllUsers)) {
                if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) $oAjax->addCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, $oAllUsers, $bCacheLifetime);
            }
    
            $oAjax->setSuccessHeaders();
            wp_send_json( $oAllUsers );
            wp_die();
        
        case 'getUnavailableDates':
    
            $bCacheEnabled = true;
            $bCacheLifetime = 3600;
    
            if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) {
                $cacheFileKey = md5($sAction . $authenticationKey);
                $oCacheData = $oAjax->getCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, $bCacheLifetime);
                if(!empty($oCacheData)) {
                    $oAjax->setCacheHeaders();
                    wp_send_json( $oCacheData );
                    wp_die();
                }
            }
    
            $oAllDates = $oOvisApi->fetchUnavailableRentalDates($iPresentationId);
    
            if(!empty($oAllDates)) {
                if(OVIS_API_ENABLE_CACHE && $bCacheEnabled) $oAjax->addCacheData($cacheFileKey, OVIS_PLUGIN_CACHE_DIR_PATH, $oAllDates, $bCacheLifetime);
            }
    
            $oAjax->setSuccessHeaders();
            wp_send_json( $oAllDates );
            wp_die();
        
        case 'contactDealer':
            $oRequestBody = new \stdClass();
            $oRequestBody->presentationId = (int) $oCtaFormBody->presentationId;
            $oRequestBody->url = $oCtaFormBody->url;
            $oRequestBody->name = $oCtaFormBody->name;
            $oRequestBody->phone = $oCtaFormBody->phone;
            $oRequestBody->email = $oCtaFormBody->email;
            $oRequestBody->message = $oCtaFormBody->message;
            
            $oUtm = new \stdClass();
            $oUtm->source = $oCtaFormBody->utmSource;
            $oUtm->campaign = $oCtaFormBody->utmCampaign;
            $oUtm->content = $oCtaFormBody->utmContent;
    
            $oRequestBody->utm = $oUtm;
    
            $oResponse = $oOvisApi->contactDealer($oRequestBody);
    
            $oAjax->setSuccessHeaders();
            wp_send_json( $oResponse );
            wp_die();
        
        case 'rentalRequest':
            $oRequestBody = new \stdClass();
            $oRequestBody->presentationId = (int) $oCtaFormBody->presentationId;
            $oRequestBody->numberOfPersons = (int) $oCtaFormBody->numberOfPersons;
            $dateRange = explode( ',', $oCtaFormBody->date );
            $oRequestBody->dateStart = !empty( $dateRange[0] ) ? date( 'Y-m-d',strtotime( $dateRange[0] ) ) : '';
            $oRequestBody->dateEnd = !empty( $dateRange[1] ) ? date( 'Y-m-d',strtotime( $dateRange[1] ) ) : '';
            $oRequestBody->address = $oCtaFormBody->address;
            if(!empty($oCtaFormBody->houseNumber)){
                $oRequestBody->address .= ' '.$oCtaFormBody->houseNumber;
            }
            $oRequestBody->city = $oCtaFormBody->city;
            $oRequestBody->zipcode = $oCtaFormBody->zipcode;
            $oRequestBody->name = $oCtaFormBody->name;
            $oRequestBody->phone = $oCtaFormBody->phone;
            $oRequestBody->email = $oCtaFormBody->email;
            $oRequestBody->message = $oCtaFormBody->message;
            
            $oUtm = new \stdClass();
            $oUtm->source = $oCtaFormBody->utmSource;
            $oUtm->campaign = $oCtaFormBody->utmCampaign;
            $oUtm->content = $oCtaFormBody->utmContent;
    
            $oRequestBody->utm = $oUtm;
    
            $oResponse = $oOvisApi->rentalRequest($oRequestBody);
    
            $oAjax->setSuccessHeaders();
            wp_send_json( $oResponse );
            wp_die();
        
        case 'tradeInRequest':
            $oRequestBody = new \stdClass();
            $oRequestBody->presentationId = (int) $oCtaFormBody->presentationId;
            
            $sCategory = 'nb';
            
            if($oCtaFormBody->category == 'caravan'){
                
                $sCategory = 'caravan';
                
            } elseif($oCtaFormBody->category == 'kampeerauto'){
                
                $sCategory = 'camper';	
                
            } elseif($oCtaFormBody->category == 'overig'){
                
                $sCategory = 'other';	
                
            }		
            $oRequestBody->category = $sCategory;
            $oRequestBody->condition = $oCtaFormBody->condition;
            $oRequestBody->damage = $oCtaFormBody->damage;
            $oRequestBody->brand = $oCtaFormBody->brand;
            $oRequestBody->modelType = $oCtaFormBody->modelType;
            $oRequestBody->constructionYear = (int) $oCtaFormBody->constructionYear;
            $oRequestBody->mileage = (int) $oCtaFormBody->mileage;
            $oRequestBody->tires = $oCtaFormBody->tires;
            $oRequestBody->upholstery = $oCtaFormBody->upholstery;
            $oRequestBody->licensePlate = $oCtaFormBody->licensePlate;
            $oRequestBody->name = $oCtaFormBody->name;
            $oRequestBody->phone = $oCtaFormBody->phone;
            $oRequestBody->email = $oCtaFormBody->email;
            $oRequestBody->message = $oCtaFormBody->message;
            if(isset($oCtaFormBody->requiredImage) && !empty($oCtaFormBody->requiredImage)) {
                $oRequestBody->requiredImage = $oCtaFormBody->requiredImage;
            }
            $oRequestBody->images = $oCtaFormBody->images;
    
            $oUtm = new \stdClass();
            $oUtm->source = $oCtaFormBody->utmSource;
            $oUtm->campaign = $oCtaFormBody->utmCampaign;
            $oUtm->content = $oCtaFormBody->utmContent;
    
            $oRequestBody->utm = $oUtm;
            $oResponse = $oOvisApi->tradeInRequest($oRequestBody);

            $oAjax->setSuccessHeaders();
            wp_send_json( $oResponse );
            wp_die();
        
        default:
            wp_send_json_error( ['message' => 'no-action'], 400 );
            wp_die();
    }
}