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

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

        if(!$lang){
            $lang = get_query_var('rs_zoddak_lang') ?? 'en';
        }
        if(!$lang){
            $lang = substr(get_locale(), 0, 2);
        }
        $options = [
            'apiUrl'            => get_option('rs_zoddak_api_url'),
            'token'             => get_option('rs_zoddak_api_token'),
            'perPage'           => get_option('rs_zoddak_items_per_page', 10),
            'layout'            => get_option('rs_zoddak_property_layout', 'horizontal'),
            'cardSize'          => get_option('rs_zoddak_card_size', 'small'),
            'cardBg'            => get_option('rs_zoddak_card_bg_color', '#ffffff'),
            'textSize'          => get_option('rs_zoddak_text_size', '14px'),
            'pageWidth'         => get_option('rs_zoddak_page_width', '1200px'),
            'btnDetails'        => get_option('rs_zoddak_color_button_details', '#020202'),
            'btnTypeColor'      => get_option('rs_zoddak_type_property_btn_color', '#dddd0f'),
            'btnTypeTxt'        => get_option('rs_zoddak_type_property_txt_color', '#ffffff'),
            'hoverColor'        => get_option('rs_rs_zoddak_hover_color', '#110400'),
            'currentColor'      => get_option('rs_zoddak_current_page_color', '#110400'),
            'filterBg'          => get_option('rs_zoddak-bg-color-search-menu', '#f5f5f5'),
            'filterBtn'         => get_option('rs_zoddak-btn-color-search-menu', '#070100'),
            'filterReset'       => get_option('rs_zoddak-reset-btn-color', '#ffffff'),
            'borderRadius'      => get_option('rs_zoddak_border_rounded', true),
            'horizontalLine'    => get_option('rs_zoddak_color_horizontal_line', '#c61c1c'),
            'currentPageColor'  => get_option('rs_zoddak_current_page_color', 'black'),
            'showMlsProperties' => get_option('rs_zoddak_show_mls_properties', false),
            'pageHoverColor'    => get_option('rs_rs_zoddak_hover_color', 'green'),
        ];
        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        if($_GET['reference']){
            $ref = strtoupper(sanitize_text_field($_GET['reference']));
            $baseRoute = trim(get_option('rs_zoddak_custom_route', 'resales'), '/');
            $lang = get_query_var('rs_zoddak_lang');

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

            wp_redirect($url);
            exit;
        }
        $itemsPerPage = self::checkItemsPerPage($options);
        $start = ($page - 1) * $itemsPerPage;
        $end   = $start + $itemsPerPage; 
        $adminOptions = [
            'stagesToHide' => get_option('rs_zoddak_resales_stages', []),
            'typesToHide'  => get_option('rs_zoddak_resales_types', []),
            'priceRange'   => get_option('rs_zoddak_newdevs_price_range', ['min' => 0, 'max' => 35000000]),
            'areasToHide'  => get_option('c', [])
        ];
        $filters = [
            'comarcas'      => isset($_GET['comarcas']) ? (array) $_GET['comarcas'] : [],
            'municipios'    => isset($_GET['municipios']) ? (array) $_GET['municipios'] : [],
            'distritos'     => isset($_GET['distritos']) ? (array) $_GET['distritos'] : [],
            'barrios'       => isset($_GET['barrios']) ? (array) $_GET['barrios'] : [],
            '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'          => strtolower(substr(get_locale(), 0, 2))
        ];

        $minPrice = $adminOptions['priceRange']['min'] ?? 0;
        $maxPrice = $adminOptions['priceRange']['max'] ?? 35000000;

        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;
        }
        $stages_param = ''; 
        $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'],
            'show_mls'      => $options['showMlsProperties'],
            'comarcas'      => implode(',', $filters['comarcas']),
            'municipios'    => $filters['municipios'],
            'distritos'     => $filters['distritos'],
            'barrios'       => $filters['barrios'],
            'types'         => $filters['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,
            'lang'          => $lang
        ], function($value) {
            return $value !== '' && $value !== null && !empty($value);
        });

        $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);
        $body =  $body['data'];
        $total_items = $body['total_items'];
        $body = $body['properties'];
        $range_prices = include plugin_dir_path(__FILE__) . '../includes/config.php';
        
        $formattedStages = format_lang_stage($stages);
        $hidden = (array) ($adminOptions['stagesToHide'] ?? []);
        $visibleStages = array_filter($formattedStages, fn($stage) =>
            !in_array($stage['label'], $hidden, true)
        );
        $types = RsApiController::get_types();
        usort($types, function($a, $b) use($lang){
            $descA = $a['description'][$lang] ?? '';
            $descB = $b['description'][$lang] ?? '';
            return strcmp($descA, $descB);
        });
        $locations = RsApiController::get_areas();
        $filtered_prices = array_filter($range_prices, function($price) use ($minPrice, $maxPrice) {
            return $price >= $minPrice && $price <= $maxPrice;
        });
        $filtered_prices = array_values($filtered_prices);
        $routes = rs_get_all_custom_routes_by_lang();
        get_header();

        include plugin_dir_path(__FILE__) . '../views/page-properties.php';
        exit;
    }


    public static function renderPropertyDetail($ref) {
        $lang = apply_filters('wpml_current_language', null);
        if(!$lang){
            $lang = get_query_var('rs_zoddak_lang') ?? 'en';
        }
        $options = [
            'apiUrl'        => get_option('rs_zoddak_api_url'),
            'token'         => get_option('rs_zoddak_api_token'),
            'contactForm'   => get_option('rs_zoddak_contact_shortcode', ''),
            'perPage'       => get_option('rs_zoddak_items_per_page', 10),
            'layout'        => get_option('rs_zoddak_property_layout', 'horizontal'),
            'cardSize'      => get_option('rs_zoddak_card_size', 'small'),
            'cardBg'        => get_option('rs_zoddak_card_bg_color', '#ffffff'),
            'textSize'      => get_option('rs_zoddak_text_size', '14px'),
            'pageWidth'     => get_option('rs_zoddak_page_width', '1200px'),
            'btnDetails'    => get_option('rs_zoddak_color_button_details', '#020202'),
            'btnTypeColor'  => get_option('rs_zoddak_type_property_btn_color', '#dddd0f'),
            'btnTypeTxt'    => get_option('rs_zoddak_type_property_txt_color', '#ffffff'),
            'hoverColor'    => get_option('rs_rs_zoddak_hover_color', '#110400'),
            'currentColor'  => get_option('rs_zoddak_current_page_color', '#110400'),
            'filterBg'      => get_option('rs_zoddak-bg-color-search-menu', '#f5f5f5'),
            'filterBtn'     => get_option('rs_zoddak-btn-color-search-menu', '#070100'),
            'filterReset'   => get_option('rs_zoddak-reset-btn-color', '#ffffff'),
        ];
        $url = RS_API_URL . '/properties/get_prop_details_for_wp/' . sanitize_text_field($ref);
        $response = wp_remote_get($url, [
            'headers' => [
                'Api-Token' => trim($options['token']),
                'Accept' => 'application/json'
            ],
            'timeout' => 10,
            'sslverify' => false
        ]);
        
        $property = json_decode(wp_remote_retrieve_body($response), true);
        $routes = rs_get_all_custom_routes_by_lang();
        $ref = get_query_var('rs_zoddak_property_ref');
        get_header();
        include plugin_dir_path(__FILE__) . '../views/page-property-details.php';
        get_footer();
        exit;
    }
    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('rs_zoddak_api_url'),
            'apiToken' => get_option('rs_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;
    }
}