<?php 
if(!defined('ABSPATH')){
    exit;
}

class PropertiesController{
    public static function renderPropertiesPage($route) {
        $lang = apply_filters('wpml_current_language', null);

        if (!$lang) {
            $lang = get_query_var('zoddak_lang') ?? 'en';
        }
        $sandbox = get_option('zoddak_activate_sandbox', 0);
        $options = [
            'apiUrl'        => get_option('zoddak_api_url'),
            'token'         => get_option('zoddak_api_token'),
            'perPage'       => get_option('zoddak_items_per_page', 10),
            'layout'        => get_option('zoddak_property_layout', 'horizontal'),
            'cardSize'      => get_option('zoddak_card_size', 'small'),
            'cardBg'        => get_option('zoddak_card_bg_color', '#ffffff'),
            'textSize'      => get_option('zoddak_text_size', '14px'),
            'pageWidth'     => get_option('zoddak_page_width', '1200px'),
            'btnDetails'    => get_option('zoddak_color_button_details', '#020202'),
            'btnTypeColor'  => get_option('zoddak_type_property_btn_color', '#dddd0f'),
            'btnTypeTxt'    => get_option('zoddak_type_property_txt_color', '#ffffff'),
            'hoverColor'    => get_option('zoddak_hover_color', '#110400'),
            'currentColor'  => get_option('zoddak_current_page_color', '#110400'),
            'filterBg'      => get_option('zoddak-bg-color-search-menu', '#f5f5f5'),
            'filterBtn'     => get_option('zoddak-btn-color-search-menu', '#070100'),
            'filterReset'   => get_option('zoddak-reset-btn-color', '#ffffff'),
            'borderRadius'  => get_option('zoddak_border_rounded', true),
            'horizontalLine' => get_option('zoddak_color_horizontal_line', '#c61c1c'),
            'currentPageColor' => get_option('zoddak_current_page_color', 'black'),
            'pageHoverColor' => get_option('zoddak_hover_color', 'green')
        ];
        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $itemsPerPage = self::checkItemsPerPage($options);
        $start = ($page - 1) * $itemsPerPage;
        $end   = $start + $itemsPerPage; 
        $adminOptions = [
            'stagesToHide' => get_option('zoddak_newdevs_stages', []),
            'typesToHide'  => get_option('zoddak_newdevs_types', []),
            'priceRange'   => get_option('zoddak_newdevs_price_range', ['min' => 0, 'max' => 35000000]),
            'areasToHide'  => get_option('zoddak_newdevs_location', [])
        ];
        $filters = [
            'towns'      => isset($_GET['towns']) ? (array) $_GET['towns'] : [],
            'places'     => isset($_GET['places']) ? (array) $_GET['places'] : [],
            'prop_types' => isset($_GET['type']) ? sanitize_text_field($_GET['type']) : '',
            'stages'     => isset($_GET['stages']) ? sanitize_text_field($_GET['stages']) : '',
            'min_price'  => isset($_GET['min_price']) ? intval($_GET['min_price']) : '',
            'max_price'  => isset($_GET['max_price']) ? intval($_GET['max_price']) : '',
            'min_baths'  => isset($_GET['min_baths']) ? intval($_GET['min_baths']) : '',
            'min_beds'   => isset($_GET['min_beds']) ? intval($_GET['min_beds']) : '',
            'orderBy'    => isset($_GET['order_by']) ? $_GET['order_by'] : '',
            'lang'       => $lang
        ];

        $minPrice = $adminOptions['priceRange']['min'] ?? 0;
        $maxPrice = $adminOptions['priceRange']['max'] ?? 35000000;
        if($_GET['reference']){
            $ref = strtoupper(sanitize_text_field($_GET['reference']));
            $baseRoute = trim(get_option('zoddak_custom_route', 'new-devs'), '/');
            $lang = get_query_var('zoddak_lang');

            $url = $lang
                ? home_url("/{$lang}/{$baseRoute}/{$ref}")
                : home_url("/{$baseRoute}/{$ref}");

            wp_redirect($url);
            exit;
        }
        if (!empty($filters['min_price'])) {
            $filters['min_price'] = max($filters['min_price'], $minPrice);
        } else {
            $filters['min_price'] = $minPrice;
        }
        
        if (!empty($filters['max_price'])) {
            $filters['max_price'] = min($filters['max_price'], $maxPrice);
        } else {
            $filters['max_price'] = $maxPrice;
        }

        $towns_param = '';
        if (!empty($filters['towns'])) {
            $towns_param = implode(',', array_map('sanitize_text_field', $filters['towns']));
        } elseif (!empty($adminOptions['areasToHide'])) {
            $allAreas = ApiController::get_areas();
            if(empty($allAreas)){
                return;
            }
            $allowedAreas = array_diff(array_column($allAreas, 'town'), $adminOptions['areasToHide']);
            $towns_param = implode(',', array_map('sanitize_text_field', $allowedAreas));
        }
        $places_param = '';
        if ($towns_param === '' && !empty($filters['places'])) {
            $places_param = implode(',', array_map('sanitize_text_field', $filters['places']));
        }else if($towns_param !== ''){
            $places_param = '';
        }
        $stages_param = '';

        if (!empty($adminOptions['stagesToHide'])) {

            $stagesToHide = array_map('strtolower', $adminOptions['stagesToHide']);

            $stagesData = ApiController::get_property_stage(); 

            $allowedStages = [];

            if (!empty($stagesData)) {
                foreach ($stagesData as $stage) {

                    $label = isset($stage['en']) ? $stage['en'] : '';

                    if ($label && !in_array(strtolower($label), $stagesToHide)) {
                        $allowedStages[] = $label;
                    }
                }
            }
            $allowedStages = array_map('strtolower', $allowedStages);
            $stages_param = implode(',', array_map('sanitize_text_field', $allowedStages));
        }
        $types_param = '';
        if (!empty($adminOptions['typesToHide'])) {
            $allTypes = ['Apartments', 'Villas', 'Townhouses'];
            $allTypes = array_map('strtolower',$allTypes);
            $typesToHide = array_map('strtolower', $adminOptions['typesToHide']);
            $allowedTypes = array_diff($allTypes,$typesToHide);
            $types_param = implode(',', $allowedTypes);
        }   
        
        $query_args = array_filter([
            'limit'      => $options['perPage'],
            'towns'      => $towns_param,
            'places'     => $places_param,
            'prop_types' => $filters['prop_types'] ?: $types_param,
            'stages'     => $filters['stages'] ?: $stages_param,
            'min_baths'  => $filters['min_baths'],
            'min_beds'   => $filters['min_beds'],
            'min_price'  => $filters['min_price'],
            'max_price'  => $filters['max_price'],
            'orderby'    => $filters['orderBy'],
            'start'      => $start,
            'end'        => $end,
            'lan'        => $lang
        ], function($value) {
            return $value !== '' && $value !== null;
        });
        if($sandbox){
            $url = add_query_arg($query_args, rtrim($options['apiUrl']. '/sandbox'));
        }else{
            $url = add_query_arg($query_args, $options['apiUrl']);
        }
        
        $response = wp_remote_get($url, [
            'headers' => [
                'Api-Token' => trim($options['token']),
                'Accept' => 'application/json'
            ],
            'timeout' => 10,
            'sslverify' => false
        ]);

        $bodyRaw = wp_remote_retrieve_body($response);

        $body = json_decode($bodyRaw, true);        
        $total_items = $body['total_items'] ?? 0;
        $body = $body['developments'] ?? [];
        $body = self::langSwitcher($body, $lang);
        $range_prices = include plugin_dir_path(__FILE__) . '../includes/config.php';
        $stages = ApiController::get_property_stage();
        $formattedStages = format_lang_stage($stages);
        $hidden = (array) ($adminOptions['stagesToHide'] ?? []);
        $visibleStages = array_filter($formattedStages, fn($stage) =>
            !in_array($stage['label'], $hidden, true)
        );
        $propertyTypes = [
            'Apartments',
            'Villas',
            'Townhouses'
        ];
        $typesToShow = $propertyTypes;
        if(!empty($adminOptions['typesToHide'])){
            $typesToShow = array_diff(
                array_map('strtolower', $propertyTypes),
                array_map('strtolower', $adminOptions['typesToHide'])
            );
        }
        $locations = ApiController::get_areas();
        $areasToHide = (array) ($adminOptions['areasToHide'] ?? []);
        $areasToShow = array_filter($locations, fn($loc) =>
            !in_array($loc['town'], $areasToHide, true)
        );
        $filtered_prices = array_filter($range_prices, function($price) use ($minPrice, $maxPrice) {
            return $price >= $minPrice && $price <= $maxPrice;
        });
        $filtered_prices = array_values($filtered_prices);
        $typesToShow = array_map('ucfirst', $typesToShow);
        do_not_cache();
        get_header();
        include plugin_dir_path(__FILE__) . '../views/page-properties.php';
        get_footer();
        exit;
    }



    public static function renderPropertyDetail($ref) {
        $lang = apply_filters('wpml_current_language', null);

        if (!$lang) {
            $lang = get_query_var('zoddak_lang') ?? 'en';
        }
        $sandbox = get_option('zoddak_activate_sandbox', 0);
        $options = [
            'apiUrl'        => get_option('zoddak_api_url'),
            'token'         => get_option('zoddak_api_token'),
            'contactForm'   => get_option('zoddak_contact_shortcode', ''),
            'perPage'       => get_option('zoddak_items_per_page', 10),
            'layout'        => get_option('zoddak_property_layout', 'horizontal'),
            'cardSize'      => get_option('zoddak_card_size', 'small'),
            'cardBg'        => get_option('zoddak_card_bg_color', '#ffffff'),
            'textSize'      => get_option('zoddak_text_size', '14px'),
            'pageWidth'     => get_option('zoddak_page_width', '1200px'),
            'btnDetails'    => get_option('zoddak_color_button_details', '#020202'),
            'btnTypeColor'  => get_option('zoddak_type_property_btn_color', '#dddd0f'),
            'btnTypeTxt'    => get_option('zoddak_type_property_txt_color', '#ffffff'),
            'hoverColor'    => get_option('zoddak_hover_color', '#110400'),
            'currentColor'  => get_option('zoddak_current_page_color', '#110400'),
            'filterBg'      => get_option('zoddak-bg-color-search-menu', '#f5f5f5'),
            'filterBtn'     => get_option('zoddak-btn-color-search-menu', '#070100'),
            'filterReset'   => get_option('zoddak-reset-btn-color', '#ffffff'),
        ];
        if($sandbox){
            $url = rtrim($options['apiUrl'], '/' ) . '/' . sanitize_text_field($ref) . '/sandbox/' . '?lan=' . $lang;
        }else{
            $url = rtrim($options['apiUrl'], '/' ) . '/' . sanitize_text_field($ref) . '?lan=' . $lang;
        }
        $response = wp_remote_get($url, [
            'headers' => [
                'Api-Token' => trim($options['token']),
                'Accept' => 'application/json'
            ],
            'timeout' => 10,
            'sslverify' => false
        ]);

        $body = json_decode(wp_remote_retrieve_body($response), true);
        if (empty($body['development'])) {
            $property = [];
        } else {
            $property = $body['development'];
        }
        set_transient($cache_key, $property, 6 * HOUR_IN_SECONDS);
        
        $property = self::langSwitcher($property, $lang);
        $unitsData = self::checkUnitsAvailable($property['units']);
        $routes = get_all_custom_routes_by_lang();
        $ref = get_query_var('zoddak_property_ref');
        get_header();
        include plugin_dir_path(__FILE__) . '../views/page-property-details.php';
        get_footer();
        return;
    }
    private static function checkUnitsAvailable($units) {
    if (empty($units)) return [];

    $collectionUnit = [];

    foreach ($units as $unit) {       
        $beds = (int)$unit['beds'];

        if (!isset($collectionUnit[$beds])) {
            $collectionUnit[$beds] = [
                'count' => 0,
                'units' => []
            ];
        }

        $collectionUnit[$beds]['units'][] = [
            'baths' => $unit['baths'],
            'name' => $unit['unit'],
            'builtArea' => $unit['built_area'],
            'plotArea' => $unit['plot'],
            'price' => $unit['price']
        ];

        $collectionUnit[$beds]['count']++;
    }

    ksort($collectionUnit); 

    return $collectionUnit;
}

    private static function getPropertiesStage($properties)
    {
        if(!$properties) return;
        $options = [
            'apiUrl'   => get_option('zoddak_api_url'),
            'apiToken' => get_option('zoddak_api_token'),
        ];
        $data = [];
        
        foreach($properties as &$prop){
            if (empty($prop['reference'])) continue;

            $url = rtrim($options['apiUrl'], '/') . '/' . sanitize_text_field($prop['reference']);
            $response = wp_remote_get($url, [
                'headers' => [
                    'Api-Token' => trim($options['apiToken']),
                    'Accept' => 'application/json'
                ],
                'timeout' => 10,
                'sslverify' => false
            ]);

            $detail = json_decode(wp_remote_retrieve_body($response), true);
            if (!empty($detail['development']['stage'])) {
                $prop['stage'] = $detail['development']['stage'];
            } else {
                $prop['stage'] = null;
            }       
        }
        return $properties;
    }
   private static function langSwitcher(array $devs, string $lan)
    {
        if (empty($devs)) return $devs;

        $lan = strtolower(strtok($lan, '_-'));

        $propertyType = [
            'es' => ['Apartments'=>'Apartamento','Villas'=>'Villa','Townhouses'=>'Adosado'],
            'fr' => ['Apartments'=>'Appartement','Villas'=>'Villa','Townhouses'=>'Maison de ville'],
            'da' => ['Apartments'=>'Lejlighed','Villas'=>'Villa','Townhouses'=>'Rækkehus'],
            'de' => ['Apartments'=>'Wohnung','Villas'=>'Villa','Townhouses'=>'Reihenhaus'],
            'no' => ['Apartments'=>'Leilighet','Villas'=>'Villa','Townhouses'=>'Rekkehus'],
            'fi' => ['Apartments'=>'Huoneisto','Villas'=>'Huvila','Townhouses'=>'Rivitalo'],
            'ru' => ['Apartments'=>'Квартира','Villas'=>'Вилла','Townhouses'=>'Таунхаус'],
            'sv' => ['Apartments'=>'Lägenhet','Villas'=>'Villa','Townhouses'=>'Radhus'],
        ];
        if (!isset($propertyType[$lan])) return $devs;

        $map = $propertyType[$lan];

        foreach ($devs as &$dev) {
            if (!isset($dev['prop_type'])) continue; // nada que traducir
            $key = $dev['prop_type'];                // valor original (suele venir en inglés)
            if (isset($map[$key])) {
                $dev['prop_type'] = $map[$key];
            }
            
        }
        unset($dev); 
        return $devs;
    }
    public static function checkItemsPerPage($options)
    {
        $itemsPerPage = 20;
        if($options['cardSize'] === 'small'){
            if($options['pageWidth'] === '960px'){
                $itemsPerPage = 18;
                return $itemsPerPage;
            }else if($options['pageWidth'] === '100%'){
                $itemsPerPage = 18;
                return $itemsPerPage;
            }
        }else if($options['cardSize'] === 'medium'){
            if($options['pageWidth'] === '1200px'){
                $itemsPerPage = 18;
                return $itemsPerPage;
            }
        }else if($options['cardSize'] === 'large'){
            if($options['pageWidth'] === '1400px'){
                $itemsPerPage = 18;
                return $itemsPerPage;
            }
        }
        return $itemsPerPage;
    }
}