<?php

namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;



error_reporting(E_ALL);
ini_set('display_errors', 1);

class Listings extends BaseController
{
    use ResponseTrait;


public function listings($return_data = false)
{
    $data = array();

    $listingModel = model('App\Models\ListingModel');
    $fieldModel = model('App\Models\FieldModel');
    $treeModel = model('App\Models\TreefieldModel');
    $userModel = model('App\Models\UserModel');
    $tokenModel = model('App\Models\TokenModel');
    $favoriteModel = model('App\Models\FavoriteModel');
    $hiddenModel = model('App\Models\HiddenModel');
    $db = \Config\Database::connect();
    
    // Test log
    $logFile = WRITEPATH . 'logs/api_test.log';
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - API çağrıldı: " . $this->request->getUri() . "\n", FILE_APPEND);


    // ========================================
    // TOKEN KONTROLÜ
    // ========================================
    $user_id = NULL;
    $include_analytics = false;

    if(!empty($_GET['token']))
    {
        $token = $_GET['token'];
        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if(count($user_token) > 0)
        {
            $user_id = $user_token[0]['user_id'];
            $include_analytics = true;

            $data['token'] = array(
                'token' => $user_token[0]['token'],
                'user_id' =>  $user_id,
                'expire_date' =>  date('Y-m-d H:i:s', strtotime($user_token[0]['date_last_access']." +2 months")),
                'user_email' =>  $user_token[0]['username'],
                'include_analytics' => true,
            );
        }
    }

    // ========================================
    // PAGINATION SETUP
    // ========================================
    $offset = 0;
    $where = array();
    $user_check = FALSE;
    $show_other_agents_litings = FALSE;
    $order_by = 'property.id DESC';

    $limit = 10;
    if(isset($_GET['per_page']))
        $limit = $_GET['per_page'];

    if(isset($_GET['paged']))
        $offset = $limit*($_GET['paged']-1);

    if(isset($_GET['search']))
        $_GET['field_search'] = $_GET['search'];

    if(isset($_GET['is_featured']))
        $order_by = 'is_featured DESC, counter_views DESC';

    // ========================================
    // SORTING SYSTEM
    // ========================================
    if(isset($_GET['sort'])) {
        switch($_GET['sort']) {
            case 'date_desc':
                $order_by = 'property.id DESC';
                break;
            case 'date_asc':
                $order_by = 'property.id ASC';
                break;
            case 'price_asc':
                $order_by = 'COALESCE(field_36_int, 0) ASC';
                break;
            case 'price_desc':
                $order_by = 'COALESCE(field_36_int, 0) DESC';
                break;
            case 'size_asc':
                $order_by = 'COALESCE(CAST(JSON_EXTRACT(json_object, "$.field_13") AS UNSIGNED), 0) ASC';
                break;
            case 'size_desc':
                $order_by = 'COALESCE(CAST(JSON_EXTRACT(json_object, "$.field_13") AS UNSIGNED), 0) DESC';
                break;
            case 'days_left_asc':
                $order_by = 'CASE WHEN STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_1015")), "%d/%m/%Y") IS NOT NULL 
                              THEN DATEDIFF(STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_1015")), "%d/%m/%Y"), CURDATE())
                              ELSE 999999 END ASC';
                break;
            case 'days_left_desc':
                $order_by = 'CASE WHEN STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_1015")), "%d/%m/%Y") IS NOT NULL 
                              THEN DATEDIFF(STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_1015")), "%d/%m/%Y"), CURDATE())
                              ELSE -1 END DESC';
                break;
            case 'views_desc':
                $order_by = 'COALESCE(ps.total_views, 0) DESC, property.id DESC';
                break;
            case 'views_asc':
                $order_by = 'COALESCE(ps.total_views, 0) ASC, property.id DESC';
                break;
            case 'favorites_desc':
                $order_by = 'COALESCE(ps.total_favorites, 0) DESC, property.id DESC';
                break;
            case 'favorites_asc':
                $order_by = 'COALESCE(ps.total_favorites, 0) ASC, property.id DESC';
                break;
            case 'enquiries_desc':
                $order_by = 'COALESCE(ps.total_enquiries, 0) DESC, property.id DESC';
                break;
            case 'enquiries_asc':
                $order_by = 'COALESCE(ps.total_enquiries, 0) ASC, property.id DESC';
                break;
            case 'unique_views_desc':
                $order_by = 'COALESCE(ps.unique_views, 0) DESC, property.id DESC';
                break;
            case 'unique_views_asc':
                $order_by = 'COALESCE(ps.unique_views, 0) ASC, property.id DESC';
                break;
            default:
                $order_by = 'property.id DESC';
                break;
        }
    }

    // ========================================
    // SEARCH FILTERS
    // ========================================
    
    // Text search
    if(isset($_GET['field_search']) && !empty($_GET['field_search']))
        $where['search_values LIKE \'%'.$_GET['field_search'].'%\''] = NULL;

    // Location search alias
    if(isset($_GET['search_location']))
        $_GET['location_id'] = $_GET['search_location'];

    // Category search alias
    if(isset($_GET['search_category']))
        $_GET['category_id'] = $_GET['search_category'];

    // Purpose filter (Satılık/Kiralık)
    if(isset($_GET['field_5']) && !empty($_GET['field_5']))
    {
        $where['field_4'] = $_GET['field_5'];
    }

    // By post id
    if(isset($_GET['field_post_id']) && !empty($_GET['field_post_id']))
    {
        $where['property.id'] = $_GET['field_post_id'];
    }

    // ========================================
    // LOCATION FILTER - AKILLI MANTIK
    // ========================================
    if(isset($_GET['search_location']) && !empty($_GET['search_location']))
    {
        $location_ids = explode(',', $_GET['search_location']);
        $search_conditions = array();
        
        if(getenv('CI_ENVIRONMENT') == 'development') {
            log_message('info', '🔍 Location Filter Başladı');
            log_message('info', '   Toplam lokasyon: ' . count($location_ids));
            log_message('info', '   Raw input: ' . $_GET['search_location']);
        }
        
        foreach($location_ids as $location_id) {
            $location_id = trim($location_id);
            if(empty($location_id)) continue;
            
            // Treefield'den location bilgisini al
            $tree_search = $treeModel->where('language_id', getenv('LANGUAGE_ID'))
                                     ->where('field_id', getenv('LOCATION_FIELD_ID'))
                                     ->where('treefield_id', $location_id)                          
                                     ->findAll();
    
            if(count($tree_search) > 0) {
                $search_location = $tree_search[0]['value'];
                $level = intval($tree_search[0]['level']);
                
                // AKILLI FİLTRELEME MANTIĞI
                if($level === 0) {
                    // İl seviyesi - bu ilin TÜM alt lokasyonlarını dahil et
                    // Örnek: "İstanbul" → "İstanbul - Kadıköy", "İstanbul - Beşiktaş" hepsi
                    $search_conditions[] = 'json_object LIKE \'%"field_64":"'.$db->escapeLikeString($search_location).'%\'';
                    
                    if(getenv('CI_ENVIRONMENT') == 'development') {
                        log_message('info', "  📍 İl (Tüm alt bölgeler): $search_location (ID: $location_id)");
                    }
                } 
                else if($level === 1) {
                    // İlçe seviyesi - bu ilçe ve TÜM alt mahalleleri
                    // Örnek: "Kadıköy" → "İstanbul - Kadıköy", "İstanbul - Kadıköy - Göztepe", "İstanbul - Kadıköy - Fenerbahçe" hepsi
                    $search_conditions[] = 'json_object LIKE \'%'.$db->escapeLikeString($search_location).'%\'';
                    
                    if(getenv('CI_ENVIRONMENT') == 'development') {
                        log_message('info', "  📍 İlçe (Tüm mahalleler): $search_location (ID: $location_id)");
                    }
                } 
                else if($level === 2) {
                    // Mahalle seviyesi - SADECE bu mahalle
                    // Örnek: "Göztepe" → SADECE "İstanbul - Kadıköy - Göztepe"
                    $search_conditions[] = 'json_object LIKE \'%'.$db->escapeLikeString($search_location).' -%\'';
                    
                    if(getenv('CI_ENVIRONMENT') == 'development') {
                        log_message('info', "  📍 Mahalle (Spesifik): $search_location (ID: $location_id)");
                    }
                }
            } else {
                if(getenv('CI_ENVIRONMENT') == 'development') {
                    log_message('warning', "  ❌ Lokasyon bulunamadı: ID $location_id");
                }
            }
        }
        
        if(!empty($search_conditions)) {
            // OR ile birleştir - seçilen lokasyonlardan HERHANGİ BİRİNDE bulunması yeterli
            $where['('.implode(' OR ', $search_conditions).')'] = NULL;
            
            if(getenv('CI_ENVIRONMENT') == 'development') {
                log_message('info', '✅ Location filtresi oluşturuldu: ' . count($search_conditions) . ' koşul');
            }
        } else {
            if(getenv('CI_ENVIRONMENT') == 'development') {
                log_message('warning', '⚠️ Hiçbir geçerli lokasyon bulunamadı - filtre uygulanmıyor');
            }
        }
    }

    // ========================================
    // CATEGORY FILTER
    // ========================================
    if(isset($_GET['category_id']) && !empty($_GET['category_id']))
    {
        $category_ids = explode(',', $_GET['category_id']);
        $category_conditions = array();
        
        foreach($category_ids as $category_id) {
            $category_id = trim($category_id);
            if(empty($category_id)) continue;
            
            $tree_search = $treeModel->where('language_id', getenv('LANGUAGE_ID'))
                                       ->where('field_id', getenv('CATEGORY_FIELD_ID'))
                                       ->where('treefield_id', $category_id)                          
                                       ->findAll();

            if(count($tree_search) > 0) {
                $search_category = $tree_search[0]['value'];
                $category_conditions[] = 'json_object LIKE \'%'.$search_category.' -%\'';
            }
        }
        
        if(!empty($category_conditions)) {
            $where['('.implode(' OR ', $category_conditions).')'] = NULL;
        }
    }

    // ========================================
    // PRICE FILTERS
    // ========================================
    
    // Sale price (field_6)
    if(isset($_GET['field_6_min']) && !empty($_GET['field_6_min']))
    {
        $min_price = intval($_GET['field_6_min']);
        if($min_price > 0) {
            $where['field_36_int >= '.$min_price] = NULL;
        }
    }

    if(isset($_GET['field_6_max']) && !empty($_GET['field_6_max']))
    {
        $max_price = intval($_GET['field_6_max']);
        if($max_price > 0) {
            $where['field_36_int <= '.$max_price] = NULL;
        }
    }

    // Rent price (field_7)
    if(isset($_GET['field_7_min']) && !empty($_GET['field_7_min']))
    {
        $min_rent = intval($_GET['field_7_min']);
        if($min_rent > 0) {
            $where['field_37_int >= '.$min_rent] = NULL;
        }
    }

    if(isset($_GET['field_7_max']) && !empty($_GET['field_7_max']))
    {
        $max_rent = intval($_GET['field_7_max']);
        if($max_rent > 0) {
            $where['field_37_int <= '.$max_rent] = NULL;
        }
    }

    // ========================================
    // PROPERTY FILTERS
    // ========================================
    
    // Size (m²)
    if(isset($_GET['size_min']) && !empty($_GET['size_min']))
    {
        $min_size = intval($_GET['size_min']);
        if($min_size > 0) {
            $where['CAST(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_13")) AS UNSIGNED) >= '.$min_size] = NULL;
        }
    }

    if(isset($_GET['size_max']) && !empty($_GET['size_max']))
    {
        $max_size = intval($_GET['size_max']);
        if($max_size > 0) {
            $where['CAST(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_13")) AS UNSIGNED) <= '.$max_size] = NULL;
        }
    }

    // Room count
    if(isset($_GET['rooms_min']) && !empty($_GET['rooms_min']))
    {
        $min_rooms = intval($_GET['rooms_min']);
        if($min_rooms > 0) {
            $where['CAST(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_11")) AS UNSIGNED) >= '.$min_rooms] = NULL;
        }
    }

    if(isset($_GET['rooms_max']) && !empty($_GET['rooms_max']))
    {
        $max_rooms = intval($_GET['rooms_max']);
        if($max_rooms > 0) {
            $where['CAST(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_11")) AS UNSIGNED) <= '.$max_rooms] = NULL;
        }
    }

    // Bathroom count
    if(isset($_GET['bathrooms_min']) && !empty($_GET['bathrooms_min']))
    {
        $min_bathrooms = intval($_GET['bathrooms_min']);
        if($min_bathrooms > 0) {
            $where['CAST(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_12")) AS UNSIGNED) >= '.$min_bathrooms] = NULL;
        }
    }

    if(isset($_GET['bathrooms_max']) && !empty($_GET['bathrooms_max']))
    {
        $max_bathrooms = intval($_GET['bathrooms_max']);
        if($max_bathrooms > 0) {
            $where['CAST(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_12")) AS UNSIGNED) <= '.$max_bathrooms] = NULL;
        }
    }

    // Building age
    if(isset($_GET['building_age_min']) && !empty($_GET['building_age_min']))
    {
        $min_age = intval($_GET['building_age_min']);
        $where['CAST(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_14")) AS UNSIGNED) >= '.$min_age] = NULL;
    }

    if(isset($_GET['building_age_max']) && !empty($_GET['building_age_max']))
    {
        $max_age = intval($_GET['building_age_max']);
        $where['CAST(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_14")) AS UNSIGNED) <= '.$max_age] = NULL;
    }

    // Floor
    if(isset($_GET['floor_min']) && !empty($_GET['floor_min']))
    {
        $min_floor = intval($_GET['floor_min']);
        $where['CAST(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_15")) AS SIGNED) >= '.$min_floor] = NULL;
    }

    if(isset($_GET['floor_max']) && !empty($_GET['floor_max']))
    {
        $max_floor = intval($_GET['floor_max']);
        $where['CAST(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_15")) AS SIGNED) <= '.$max_floor] = NULL;
    }

    // ========================================
    // AMENITY FILTERS (Boolean)
    // ========================================
    
    if(isset($_GET['field_29']) && $_GET['field_29']=='1')
        $where['json_object LIKE \'%"field_25":"true"%\''] = NULL;

    if(isset($_GET['field_33']) && $_GET['field_33']=='1')
        $where['json_object LIKE \'%"field_27":"true"%\''] = NULL;

    if(isset($_GET['field_37']) && $_GET['field_37']=='1')
        $where['json_object LIKE \'%"field_22":"true"%\''] = NULL;

    if(isset($_GET['air_conditioning']) && $_GET['air_conditioning']=='1')
        $where['json_object LIKE \'%"field_23":"true"%\''] = NULL;

    if(isset($_GET['parking']) && $_GET['parking']=='1')
        $where['json_object LIKE \'%"field_24":"true"%\''] = NULL;

    if(isset($_GET['swimming_pool']) && $_GET['swimming_pool']=='1')
        $where['json_object LIKE \'%"field_26":"true"%\''] = NULL;

    if(isset($_GET['garden']) && $_GET['garden']=='1')
        $where['json_object LIKE \'%"field_28":"true"%\''] = NULL;

    if(isset($_GET['balcony']) && $_GET['balcony']=='1')
        $where['json_object LIKE \'%"field_29":"true"%\''] = NULL;

    if(isset($_GET['elevator']) && $_GET['elevator']=='1')
        $where['json_object LIKE \'%"field_30":"true"%\''] = NULL;

    if(isset($_GET['security']) && $_GET['security']=='1')
        $where['json_object LIKE \'%"field_31":"true"%\''] = NULL;

    // ========================================
    // OTHER FILTERS
    // ========================================
    
    // Heating type
    if(isset($_GET['heating_type']) && !empty($_GET['heating_type']))
    {
        $heating_types = explode(',', $_GET['heating_type']);
        $heating_conditions = array();
        
        foreach($heating_types as $heating_type) {
            $heating_type = trim($heating_type);
            if(!empty($heating_type)) {
                $heating_conditions[] = 'json_object LIKE \'%"field_16":"'.$heating_type.'"%\'';
            }
        }
        
        if(!empty($heating_conditions)) {
            $where['('.implode(' OR ', $heating_conditions).')'] = NULL;
        }
    }

    // Agent filter
    if(isset($_GET['search_agents_ids']) && !empty($_GET['search_agents_ids']))
    {
        $agent_ids = explode(',', $_GET['search_agents_ids']);
        $agent_conditions = array();
        
        foreach($agent_ids as $agent_id) {
            $agent_id = trim($agent_id);
            if(!empty($agent_id) && is_numeric($agent_id)) {
                $agent_conditions[] = 'property_user.user_id = '.$agent_id;
            }
        }
        
        if(!empty($agent_conditions)) {
            $where['('.implode(' OR ', $agent_conditions).')'] = NULL;
        }
    }

    // Date range
    if(isset($_GET['date_from']) && !empty($_GET['date_from']))
    {
        $date_from = date('Y-m-d', strtotime($_GET['date_from']));
        $where['DATE(property.date) >= \''.$date_from.'\''] = NULL;
    }

    if(isset($_GET['date_to']) && !empty($_GET['date_to']))
    {
        $date_to = date('Y-m-d', strtotime($_GET['date_to']));
        $where['DATE(property.date) <= \''.$date_to.'\''] = NULL;
    }

    // Days left
    if(isset($_GET['days_left_min']) && !empty($_GET['days_left_min']))
    {
        $min_days = intval($_GET['days_left_min']);
        $where['DATEDIFF(STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_1015")), "%d/%m/%Y"), CURDATE()) >= '.$min_days] = NULL;
    }

    if(isset($_GET['days_left_max']) && !empty($_GET['days_left_max']))
    {
        $max_days = intval($_GET['days_left_max']);
        $where['DATEDIFF(STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(json_object, "$.field_1015")), "%d/%m/%Y"), CURDATE()) <= '.$max_days] = NULL;
    }

    // ========================================
    // USER SPECIFIC FILTERS
    // ========================================
    
    if(!empty($user_id) && isset($_GET['is_favorite']))
    {
        $where['favorites.user_id'] = $user_id;
        $where['favorites.id > 0'] = NULL;
    }
    
    if(!empty($user_id) && isset($_GET['is_hidden']))
    {
        $where['hiddens.user_id'] = $user_id;
        $where['hiddens.id > 0'] = NULL;
    }

    // ========================================
    // EXECUTE QUERY
    // ========================================
    
    $fields = $fieldModel->where('language_id', getenv('LANGUAGE_ID'))->findAll();

    $listings = $listingModel->where('language_id', getenv('LANGUAGE_ID'))
                                ->where('is_activated', '1')
                                ->where('approval_status', 'approved')
                                ->orderBy($order_by)
                                ->get_pagination_with_analytics($limit, $offset, $where, $user_check, $user_id, $show_other_agents_litings, $order_by);

    if(getenv('CI_ENVIRONMENT') == 'development')
        $data['sql'] = (string) $listingModel->getLastQuery();

    $data['listings_count'] = ''.count($listings);
    
    // Debug log
    if(getenv('CI_ENVIRONMENT') == 'development' && isset($_GET['search_location'])) {
        log_message('info', '📊 Filtreleme Sonucu:');
        log_message('info', "   Aranan lokasyonlar: " . $_GET['search_location']);
        log_message('info', "   Bulunan ilan sayısı: " . count($listings));
        if(count($listings) > 0) {
            $first_ids = array_slice(array_column($listings, 'property_id'), 0, 3);
            log_message('info', "   İlk ilanlar: " . implode(', ', $first_ids));
        }
    }

    $data['listings'] = array();

    // ========================================
    // GET ANALYTICS DATA (BATCH)
    // ========================================
    
    $property_ids = array_column($listings, 'property_id');
    $analytics_data = array();
    
    if($include_analytics && !empty($property_ids)) {
        $analytics_data = $this->getPropertyStatisticsBatch($property_ids);
    }

    // ========================================
    // PROCESS RESULTS
    // ========================================
    
    foreach($listings as $listing)
    {
        $n_listing = array();
        $n_listing['post_id'] = $listing['property_id'];
        $n_listing['idlisting'] = $listing['property_id'];
        $n_listing['category_id'] = "2";
        $n_listing['address'] = $listing['address'];
        $n_listing['lat'] = $listing['lat'];
        $n_listing['lng'] = $listing['lng'];

        $n_listing['is_favorite'] = 'null';
        $n_listing['is_hidden'] = 'null';

        if($user_id !== NULL)
        {
            $favorites = $favoriteModel->where('property_id', $listing['id'])
                          ->where('user_id', $user_id)
                          ->where('lang_code', getenv('LANG_CODE'))->findAll(1);

            if(count($favorites) > 0)
                $n_listing['is_favorite'] = '1';
                
            $hiddens = $hiddenModel->where('property_id', $listing['id'])
                          ->where('user_id', $user_id)
                          ->where('lang_code', getenv('LANG_CODE'))->findAll(1);

            if(count($hiddens) > 0)
                $n_listing['is_hidden'] = '1';
        }

        $n_listing['guid'] = getenv('WEBSITE_URL').'index.php/'.getenv('LISTING_URI').'/'.$listing['id'];

        // Images
        $n_listing['listing_images_path_medium'] = '';
        $n_listing['listing_images_path'] = '';
        if(isset($listing['image_repository']))
        {
            $images_paths = json_decode($listing['image_repository']);

            foreach($images_paths as $key=>$path)
            {
                if(file_exists(getenv('FILES_DIRECTORY').'files/strict_cache/851x678'.$path))
                {
                    $images_paths[$key] = 'strict_cache/851x678'.$path;
                }
            }

            $n_listing['listing_images_path_medium'] = join(',', $images_paths);
            $n_listing['listing_images_path'] = join(',', $images_paths);
        }

        // Agent
        $n_listing['agent_exists'] = '0';
        $users = $userModel->where('property_id', $listing['id'])->findAllListing(1);
        if(count($users) > 0)
        {
            $n_listing['agent_exists'] = '1';
        }

        $json_object = json_decode($listing['json_object']);

        $n_listing['post_title'] = '';
        if(isset($json_object->{"field_10"}))
            $n_listing['post_title'] = $json_object->{"field_10"};

        $n_listing['location_name'] = '';
        if(isset($json_object->{"field_7"}))
            $n_listing['location_name'] = $json_object->{"field_7"};
            
        // Deadline
        $n_listing['deadline'] = '';
        if(isset($json_object->{"field_1015"})){
            $expiry_date = \DateTime::createFromFormat('d/m/Y', $json_object->{"field_1015"});
            
            if($expiry_date) {
                $today = new \DateTime('now');
                $diff = $expiry_date->diff($today);
                $remaining_days = $diff->invert ? $diff->days : 0;
                $n_listing['deadline'] = "$remaining_days";
            }
        }

        // Process fields
        foreach($fields as $field)
        {
            if(in_array($field['id'], array(77,10,78,8,17,38,6,56,1017,1015)))continue;
            if($field['type'] == 'HTMLTABLE')continue;
            if($field['type'] == 'PEDIGREE')continue;
            if($field['type'] == 'UPLOAD')continue;

            $value = '';

            if(isset($json_object->{"field_".$field['id']}))
            {
                $value = $json_object->{"field_".$field['id']};

                if($field['type'] == 'TEXTAREA')
                {
                    $value = strip_tags($value);
                    $value = str_replace('&amp;', '&', $value);
                }

                if($field['type'] == 'TREE' && strlen($value) > 2)
                {
                    $value = substr($value,0, -2);
                }

                if($value == '-')
                    $value = '';
            }

            if($value === true || $value === 'true')
                $value = '1';

            if($value === false || $value === 'false')
                $value = '0';

            if(!empty($value))
                $n_listing['field_'.$field['id'].'_'.$field['type']] = $field['prefix'].$value.$field['suffix'];

            if($field['type'] == 'INPUTBOX' && !empty($value))
            {
                $n_listing['field_'.$field['id'].'_NUMBER'] = $field['prefix'].$value.$field['suffix'];
            }
        }

        $n_listing['field_5_DROPDOWN'] = '';
        if(!empty($listing['field_4']))
            $n_listing['field_5_DROPDOWN'] = $listing['field_4'];

        $n_listing['field_6_NUMBER'] = '';
        if(!empty($n_listing['field_36_NUMBER']))
            $n_listing['field_6_NUMBER'] = str_replace('TL', '', $n_listing['field_36_NUMBER']);
            
        if(!empty($n_listing['field_36_NUMBER']))
            $n_listing['field_36_NUMBER'] = str_replace('TL', '€', $n_listing['field_36_NUMBER']);
            
        if(!empty($n_listing['field_36_INPUTBOX']))
            $n_listing['field_36_INPUTBOX'] = str_replace('TL', '€', $n_listing['field_36_INPUTBOX']);
        
        $n_listing['field_7_NUMBER'] = '';
        if(!empty($n_listing['field_37_NUMBER']))
            $n_listing['field_7_NUMBER'] = $n_listing['field_37_NUMBER'];

        $n_listing['post_content_stripped'] = '';
        if(!empty($json_object->{"field_17"}))
            $n_listing['post_content_stripped'] = strip_tags($json_object->{"field_17"});

        // Analytics
        if($include_analytics && isset($analytics_data[$listing['property_id']])) {
            $n_listing['analytics'] = $analytics_data[$listing['property_id']];
        }

        $data['listings'][] = $n_listing;
    }

    if($return_data)
        return $data;

    return $this->respond($data);
}

/**
 * Get property statistics in batch for performance
 */
private function getPropertyStatisticsBatch($property_ids) {
    if(empty($property_ids)) {
        return array();
    }

    $db = \Config\Database::connect();
    $analytics_data = array();

    try {
        $builder = $db->table('property_statistics ps');
        $builder->select('ps.property_id, ps.total_views, ps.unique_views, ps.total_favorites, ps.total_hidden, ps.total_enquiries, ps.avg_view_duration');
        $builder->whereIn('ps.property_id', $property_ids);
        $stats_result = $builder->get()->getResultArray();

        foreach($stats_result as $stat) {
            $analytics_data[$stat['property_id']] = array(
                'total_views' => intval($stat['total_views']),
                'unique_views' => intval($stat['unique_views']),
                'total_favorites' => intval($stat['total_favorites']),
                'total_hidden' => intval($stat['total_hidden']),
                'total_enquiries' => intval($stat['total_enquiries']),
                'avg_view_duration' => intval($stat['avg_view_duration'])
            );
        }

        // Fill missing properties
        foreach($property_ids as $property_id) {
            if(!isset($analytics_data[$property_id])) {
                $analytics_data[$property_id] = array(
                    'total_views' => 0,
                    'unique_views' => 0,
                    'total_favorites' => 0,
                    'total_hidden' => 0,
                    'total_enquiries' => 0,
                    'avg_view_duration' => 0
                );
            }
        }

    } catch(\Exception $e) {
       log_message('error', 'Analytics batch query error: ' . $e->getMessage());
        
        foreach($property_ids as $property_id) {
            $analytics_data[$property_id] = array(
                'total_views' => 0,
                'unique_views' => 0,
                'total_favorites' => 0,
                'total_hidden' => 0,
                'total_enquiries' => 0,
                'avg_view_duration' => 0
            );
        }
    }

    return $analytics_data;
}

    public function locations($return_data = false)
    {
        $primaryModel = model('App\Models\TreefieldModel');
        $listingModel = model('App\Models\ListingModel');

        $limit = 0;
        $offset = 0;
        $where = array();
        $user_check = FALSE;
        $user_id=NULL;
        $show_other_agents_litings = FALSE;
        $data = array();
        
        $items = $primaryModel->where('language_id', getenv('LANGUAGE_ID'))->where('field_id', 64)->where('level', 2)->orderBy('value', 'ASC')->findAll();

        foreach($items as $item)
        {
            $n_item = $item;

            $n_item['idlocation'] = $n_item['treefield_id'];
            $n_item['location_title'] = $n_item['value'];
            $n_item['image_url'] = empty($n_item['image_filename'])?'':'https://satisahazir.com/files/'.$n_item['image_filename'];
            $n_item['icon_url'] = '';
            $n_item['count_listings'] = '0';

            $count_listings = $listingModel->where('language_id', getenv('LANGUAGE_ID'))->where('json_object LIKE \'%'.$n_item['value'].' -%\'', NULL)->countAllResults();

            if(!empty($count_listings)){
                $n_item['count_listings'] = $count_listings;
               $data[] = $n_item;
                } 
        }

        if($return_data)
            return $data;

        return $this->respond($data);
    }

    public function categories($return_data = false)
    {
        $primaryModel = model('App\Models\TreefieldModel');
        $listingModel = model('App\Models\ListingModel');

        $limit = 0;
        $offset = 0;
        $where = array();
        $user_check = FALSE;
        $user_id=NULL;
        $show_other_agents_litings = FALSE;
        $data = array();
        
        $items = $primaryModel->where('language_id', getenv('LANGUAGE_ID'))->where('field_id', 79)->findAll();

        foreach($items as $item)
        {
            $n_item = $item;

            $n_item['idcategory'] = $n_item['treefield_id'];
            $n_item['category_title'] = $n_item['value'];
            $n_item['image_url'] = empty($n_item['image_filename'])?'':'files/'.$n_item['image_filename'];
            
            $n_item['icon_url'] = '';
            $n_item['count_listings'] = '0';

            $count_listings = $listingModel->where('language_id', getenv('LANGUAGE_ID'))->where('json_object LIKE \'%'.$n_item['value'].' -%\'', NULL)->countAllResults();

            if(!empty($count_listings))
                $n_item['count_listings'] = $count_listings;

            $data[] = $n_item;
        }

        if($return_data)
            return $data;

        return $this->respond($data);
    }

    public function fields($return_data = false)
    {
        $primaryModel = model('App\Models\FieldModel');

        $limit = 0;
        $offset = 0;
        $where = array();
        $user_check = FALSE;
        $user_id=NULL;
        $show_other_agents_litings = FALSE;
        $data = array();
        
        $items = $primaryModel->where('language_id', getenv('LANGUAGE_ID'))
                            //  ->where('is_frontend', '1')
                              ->findAll();

        foreach($items as $item)
        {
            if($item['id'] == getenv('CONTENT_FIELD_ID') ||
                $item['id'] == getenv('TITLE_FIELD_ID') )
                continue;

            $n_item = $item;

            if($item['type'] == 'CATEGORY')
                $item['type'] = 'SECTION';

            $n_item['idfield'] = $item['id'];
            $n_item['field_type'] = $item['type'];
            $n_item['field_label'] = $item['option'];
            $n_item['values_list'] = $item['values'];

            if(empty($item['columns_number']))
                $n_item['columns_number'] = '12';

            $data[] = $n_item;
        }

        if($return_data)
            return $data;

        return $this->respond($data);
    }

 public function agents($return_data = false)
{
    $data = array();
    
    // Token kontrolü
    $tokenModel = model('App\Models\TokenModel');
    $user_id = NULL;
    $user_type = 'GUEST';
    
    if(!empty($_GET['token']))
    {
        $token = $_GET['token'];
        $user_token = $tokenModel->where('token', $token)->findAll(1);
        
        if(count($user_token) > 0)
        {
            $user_id = $user_token[0]['user_id'];
            
            // Kullanıcı tipini al
            $userModel = model('App\Models\UserModel');
            $user = $userModel->find($user_id);
            if($user) {
                $user_type = $user['type'];
            }
        }
    }
    
    // Yetki kontrolü
    if($user_type == 'USER' || $user_type == 'GUEST') {
        // Normal kullanıcılar ve misafirler agent listesini göremesin
        return $this->respond(array(
            'code' => 'unauthorized',
            'message' => 'Bu içeriği görüntüleme yetkiniz yok',
            'data' => []
        ));
    }
    
    $primaryModel = model('App\Models\UserModel');
    
    if($user_type == 'AGENT') {
        // Agent sadece kendi bilgilerini görebilir
        $items = $primaryModel->where('id', $user_id)
                              ->where('activated', 1)
                              ->findAllListing(1);
    } else if($user_type == 'ADMIN' || $user_type == 'SUPER_ADMIN') {
        // Admin tüm agentları görebilir
        $items = $primaryModel->where('activated', 1)
                              ->where('type', 'AGENT')
                              ->findAllListing(100);
    }
    
    // Mevcut AnalyticsModel'i kullan
    $analyticsModel = model('App\Models\AnalyticsModel');
    
    foreach($items as $user)
    {
        $n_item = array();
        $n_item['ID'] = $user['id'];
        $n_item['display_name'] = $user['name_surname'];
        $n_item['user_email'] = $user['mail'];
        $n_item['count_listings'] = $user['count_listings'];
        $n_item['profile_url'] = getenv('WEBSITE_URL').'index.php/profile/'.$user['id'];
        
        // Admin istatistikleri görebilir
        if($user_type == 'ADMIN' || $user_type == 'SUPER_ADMIN') {
            // Agent istatistiklerini getir
            $stats = $analyticsModel->getAgentStatistics($user['id']);
            
            $n_item['stats'] = $stats;
            
            // Admin için tam bilgiler
            $n_item['phone'] = $user['phone'];
           // $n_item['registration_date'] = $user['date'];
            $n_item['last_login'] = $user['last_login'] ?? 'N/A';
            
            // Avatar
            if(!empty($user['image_user_filename'])) {
                $n_item['avatar_url'] = getenv('WEBSITE_URL').'files/'.$user['image_user_filename'];
            } else {
                $n_item['avatar_url'] = '';
            }
        } else {
            // Agent kendi istatistiklerini görebilir
            if($user['id'] == $user_id) {
                $stats = $analyticsModel->getAgentStatistics($user['id']);
                $n_item['stats'] = $stats;
            }
            
            // Telefon ve diğer özel bilgiler gizli
            $n_item['phone'] = '';
            $n_item['avatar_url'] = '';
        }
        
        $data[] = $n_item;
    }
    
    if($return_data)
        return $data;
        
    return $this->respond(array(
        'code' => 'success',
        'user_type' => $user_type,
        'data' => $data
    ));
}

    public function news($return_data = false)
    {
        $data = array();

        $primaryModel = model('App\Models\PageModel');
       
        $items = $primaryModel->where('type', 'ARTICLE')
                              ->where('language_id', getenv('LANGUAGE_ID'))
                              ->findAll(10);

        foreach($items as $item)
        {
            $n_item = $item;
            $n_item['image_url'] = '';
            $n_item['post_title'] = $item['title'];
            $n_item['post_author_display_name'] = date("m-d", strtotime($item['date_publish']));
            $n_item['post_date'] = date("Y-m-d", strtotime($item['date_publish']));
            $n_item['post_content'] = $item['description'];

            if(!empty($item['image_filename']))
                $n_item['image_url'] = 'files/'.$item['image_filename'];

            $n_item['guid'] = 'https://satisahazir.com/index.php/'.getenv('LANG_CODE').'/'.$item['id'];

            $data[] = $n_item;
        }

        if($return_data)
            return $data;

        return $this->respond($data);
    }

    public function redirect_login()
    {
        return redirect()->to(getenv('WEBSITE_URL').'index.php/admin/user/forgetpassword');
    }

    public function listing_agent_message()
    {
        $data = array(
            'code'	    => 'empty_code',
            'message'   => 'Empty Message'
        );

        $postBody = file_get_contents('php://input');
        $data_json = json_decode($postBody);

        if(empty($data_json->listing_id))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Missing listing id in request'
            ));
        }

        $listingModel = model('App\Models\ListingModel');
        $userModel = model('App\Models\UserModel');
        $settingsModel = model('App\Models\SettingsModel');

        $items = $listingModel->where('property.id', $data_json->listing_id)
                              ->where('language_id', getenv('LANGUAGE_ID'))
                              ->findAll(1);

        if(count($items) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Listing id not found'
            ));
        }

        $listing = $items[0];
        $user = NULL;
        $email_to = NULL;
        
        if(isset($listing['user_id']))
        {
            $user_res = $userModel->where('id', $listing['user_id'])->findAll(1);

            if(count($user_res) > 0)
            {
                $user = $user_res[0];
                $email_to = $user['mail'];
            }
        }
        else
        {
            $user_res = $userModel->where('type', 'ADMIN')->findAll(1);

            if(count($user_res) > 0)
            {
                $user = $user_res[0];
            }

            $email_to = $settingsModel->get_setting('email');
        }

        $validation = \Config\Services::validation();

        $validation->setRules([
            'listing_id' => ['label' => 'listing_id', 'rules' => 'required'],
            'Name' => ['label' => 'Name', 'rules' => 'required'],
            'Email' => ['label' => 'Email', 'rules' => ['required', 'valid_email']],
            'Message' => ['label' => 'Message', 'rules' => ['required']],
        ]);

        if ($validation->withRequest($this->request)->run()) {
            $data_json = $this->request->getJSON();

            $listing_json = json_decode($listing['json_object']);
            $listing_url = getenv('WEBSITE_URL').'index.php/'.getenv('LISTING_URI').'/'.$listing['id'];
            
            $enquireModel = model('App\Models\EnquireModel');
                     
            $data = array();
            $data['property_id'] = $data_json->listing_id;
            $data['phone'] = $data_json->Phone;
            $data['mail'] = $data_json->Email;
            $data['name_surname'] = $data_json->Name;
            $data['message'] = $data_json->Message;
            $data['agent_id'] = 164;
            $data['readed'] = 0;
            $data['date'] = date('Y-m-d H:i:s');

            $insert_id = $enquireModel->insert($data);
            
            $analyticsModel = model('App\Models\AnalyticsModel');
            $analyticsModel->recordEnquiry($data_json->listing_id);

            $message  = '<p>'.'Contact message related to listing'.' <a href="'.$listing_url.'">'.
                            isset($listing_json->field_10)?$listing_json->field_10:$listing['address']
                            .'</a></p>';
            $message .= implode('<br />', (array) $data_json);

            $email = \Config\Services::email();
            $email->setFrom($settingsModel->get_setting('admin'));
            $email->setTo($email_to);
            $email->setReplyTo($data_json->Email);
            $email->setSubject('New Message waiting');
            $email->setMessage($message);
            
            $ret = $email->send(false);
            
            if( $ret) {
                return $this->respond(array(
                    'code'	    => 'success',
                    'message'   => 'Mesajınız başarı ile gönderildi. Temsilcilerimiz en kısa sürede size dönüş yapacaklar.'
                ));
            }
            else
            {
                return $this->respond(array(
                    'code'	    => 'failed',
                    'message'   => 'Server can\'t send emails, please use SMTP mail configuration.',
                    'debugger'  => getenv('CI_ENVIRONMENT') == 'development'?$email->printDebugger():'-',
                ));
            }
        }
        else
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => join("\n", $validation->getErrors())
            ));
        }       

        return $this->respond($data);
    }

    public function listing_favorite()
    {
        $data = array(
            'code'	    => 'empty_code',
            'message'   => 'Empty Message'
        );

        $data_json = $this->request->getJSON();

        if(empty($data_json->listing_id))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Missing listing id in request'
            ));
        }

        $listingModel = model('App\Models\ListingModel');
        $userModel = model('App\Models\UserModel');
        $favoriteModel = model('App\Models\FavoriteModel');
        $tokenModel = model('App\Models\TokenModel');

        if(empty($_GET['token']))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Token missing'
            ));
        }

        $token = $_GET['token'];
        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if(count($user_token) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Valid Token missing'
            ));
        }

        $user_id = $user_token[0]['user_id'];

        $validation = \Config\Services::validation();

        $validation->setRules([
            'listing_id' => ['label' => 'Listing ID', 'rules' => 'required|numeric'],
        ]);

        if ($validation->withRequest($this->request)->run()) {

            if(empty($data_json->is_favorite))
            {
                $favoriteModel->where('property_id', $data_json->listing_id)
                              ->where('user_id', $user_id)
                              ->where('lang_code', getenv('LANG_CODE'))
                              ->delete();
                              
                $analyticsModel = model('App\Models\AnalyticsModel');
                $analyticsModel->recordFavoriteAction($data_json->listing_id, $user_id, 'remove');

                return $this->respond(array(
                    'code'	    => 'success',
                    'message'   => 'Removed from favorites'
                ));
            }
            else
            {
                $favorite_added = $favoriteModel->where('property_id', $data_json->listing_id)
                                                ->where('user_id', $user_id)
                                                ->where('lang_code', getenv('LANG_CODE'))
                                                ->findAll(1);
            
                if(count($favorite_added) > 0)
                    return $this->respond(array(
                        'code'	    => 'success',
                        'message'   => 'Favorite already exists'
                    ));

                $data = [
                    'lang_code' => getenv('LANG_CODE'),
                    'property_id' => $data_json->listing_id,
                    'user_id' => $user_id,
                    'date_saved' => date("Y-m-d H:i:s"),
                    'date_last_informed' => date("Y-m-d H:i:s"),
                ];

                $insert_id = $favoriteModel->insert($data);
                $analyticsModel = model('App\Models\AnalyticsModel');
                $analyticsModel->recordFavoriteAction($data_json->listing_id, $user_id, 'add');
                
                return $this->respond(array(
                    'code'	    => 'success',
                    'message'   => 'Added to favorites'
                ));
            }

        }
        else
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => join("\n", $validation->getErrors())
            ));
        }       

        return $this->respond($data);
    }
    
    public function listing_hidden()
    {
        $data = array(
            'code'	    => 'empty_code',
            'message'   => 'Empty Message'
        );
        $data_json = $this->request->getJSON();
        
        if(empty($data_json->listing_id))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Missing listing id in request'
            ));
        }
        
        $listingModel = model('App\Models\ListingModel');
        $userModel = model('App\Models\UserModel');
        $hiddenModel = model('App\Models\HiddenModel');
        $tokenModel = model('App\Models\TokenModel');
        
        if(empty($_GET['token']))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Token missing'
            ));
        }
        
        $token = $_GET['token'];
        $user_token = $tokenModel->where('token', $token)->findAll(1);
        
        if(count($user_token) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Valid Token missing'
            ));
        }
        
        $user_id = $user_token[0]['user_id'];
        
        $validation = \Config\Services::validation();
        $validation->setRules([
            'listing_id' => ['label' => 'Listing ID', 'rules' => 'required|numeric'],
        ]);
        
        if ($validation->withRequest($this->request)->run()) {
            
            if(!isset($data_json->is_hidden) || $data_json->is_hidden == 0 || $data_json->is_hidden === false)
            {
                $deleted_count = $hiddenModel->where('property_id', $data_json->listing_id)
                              ->where('user_id', $user_id)
                              ->where('lang_code', getenv('LANG_CODE'))
                              ->delete();
                
                log_message('info', "Hidden removal attempt for listing {$data_json->listing_id}, user {$user_id}, deleted rows: {$deleted_count}");
                $analyticsModel = model('App\Models\AnalyticsModel');
                $analyticsModel->recordHiddenAction($data_json->listing_id, $user_id, 'unhide');
            
                return $this->respond(array(
                    'code'	    => 'success',
                    'message'   => 'Removed from hiddens',
                    'deleted_count' => $deleted_count
                ));
            }
            else
            {
                $hidden_added = $hiddenModel->where('property_id', $data_json->listing_id)
                                                ->where('user_id', $user_id)
                                                ->where('lang_code', getenv('LANG_CODE'))
                                                ->findAll(1);
            
                if(count($hidden_added) > 0)
                    return $this->respond(array(
                        'code'	    => 'success',
                        'message'   => 'Hidden already exists'
                    ));
                    
                $data = [
                    'lang_code' => getenv('LANG_CODE'),
                    'property_id' => $data_json->listing_id,
                    'user_id' => $user_id,
                    'date_saved' => date("Y-m-d H:i:s"),
                    'date_last_informed' => date("Y-m-d H:i:s"),
                ];
                
                $insert_id = $hiddenModel->insert($data);
                $analyticsModel = model('App\Models\AnalyticsModel');
                $analyticsModel->recordHiddenAction($data_json->listing_id, $user_id, 'hide');
                
                log_message('info', "Hidden added for listing {$data_json->listing_id}, user {$user_id}, insert_id: {$insert_id}");
                
                return $this->respond(array(
                    'code'	    => 'success',
                    'message'   => 'Added to hiddens',
                    'insert_id' => $insert_id
                ));
            }
        }
        else
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => join("\n", $validation->getErrors())
            ));
        }       
        
        return $this->respond($data);
    }
    
 public function home()
{
    $db = \Config\Database::connect();
    $listingModel = model('App\Models\ListingModel');
    $fieldModel = model('App\Models\FieldModel');
    $tokenModel = model('App\Models\TokenModel');
    $favoriteModel = model('App\Models\FavoriteModel');
    $hiddenModel = model('App\Models\HiddenModel');
    $userModel = model('App\Models\UserModel');
    
    // ========================================
    // TOKEN KONTROLÜ
    // ========================================
    $user_id = NULL;
    $include_analytics = false;
    $show_hidden = true; // Default: tüm ilanları göster
    
    if(!empty($_GET['token']))
    {
        $token = $_GET['token'];
        $user_token = $tokenModel->where('token', $token)->findAll(1);
        
        if(count($user_token) > 0)
        {
            $user_id = $user_token[0]['user_id'];
            $include_analytics = true;
            
            // ✅ show_hidden parametresini kontrol et
            if(isset($_GET['show_hidden']) && $_GET['show_hidden'] === '0') {
                $show_hidden = false;
                
                if(getenv('CI_ENVIRONMENT') == 'development') {
                    log_message('info', "🏠 HOME: Gizli ilanlar filtrelenecek (User ID: $user_id)");
                }
            }
        }
    }
    
    // ========================================
    // LATEST LISTINGS
    // ========================================
    $latest_args = array(
        'language_id' => getenv('LANGUAGE_ID'),
        'is_activated' => '1',
        'approval_status' => 'approved'
    );
    
    $latest_listings = $listingModel->where($latest_args)
                                    ->orderBy('property.id', 'DESC')
                                    ->get_pagination_with_analytics(9, 0, array(), false, $user_id, false, 'property.id DESC');
    
    // ========================================
    // TRENDING LISTINGS
    // ========================================
    $trending_args = array(
        'language_id' => getenv('LANGUAGE_ID'),
        'is_activated' => '1',
        'approval_status' => 'approved'
    );
    
    $trending_listings = $listingModel->where($trending_args)
                                      ->orderBy('is_featured', 'DESC')
                                      ->orderBy('counter_views', 'DESC')
                                      ->get_pagination_with_analytics(9, 0, array(), false, $user_id, false, 'is_featured DESC, counter_views DESC');
    
    // ========================================
    // GİZLİ İLAN FİLTRELEMESİ
    // ========================================
    $fields = $fieldModel->where('language_id', getenv('LANGUAGE_ID'))->findAll();
    
    $data['latest_listings'] = $this->processListings($latest_listings, $fields, $user_id, $show_hidden, $include_analytics);
    $data['trending_listings'] = $this->processListings($trending_listings, $fields, $user_id, $show_hidden, $include_analytics);
    
    // ========================================
    // DİĞER VERİLER
    // ========================================
    $data['categories'] = $this->categories(true);
    $data['agents'] = $this->agents(true);
    $data['banners'] = array(
        array("banner_url"=>"http://satisahazir.com/files/banner4.png"),
    );
    $data['news'] = $this->news(true);
    
    // Debug log
    if(getenv('CI_ENVIRONMENT') == 'development') {
        log_message('info', "🏠 HOME API Response:");
        log_message('info', "   Latest: " . count($data['latest_listings']) . " ilan");
        log_message('info', "   Trending: " . count($data['trending_listings']) . " ilan");
        log_message('info', "   show_hidden: " . ($show_hidden ? 'true' : 'false'));
    }
    
    return $this->respond($data);
}

/**
 * İlanları işle ve gizli olanları filtrele
 */
private function processListings($listings, $fields, $user_id, $show_hidden, $include_analytics)
{
    $favoriteModel = model('App\Models\FavoriteModel');
    $hiddenModel = model('App\Models\HiddenModel');
    $userModel = model('App\Models\UserModel');
    
    $processed_listings = array();
    $hidden_count = 0;
    
    // Analytics verilerini batch olarak al
    $property_ids = array_column($listings, 'property_id');
    $analytics_data = array();
    
    if($include_analytics && !empty($property_ids)) {
        $analytics_data = $this->getPropertyStatisticsBatch($property_ids);
    }
    
    foreach($listings as $listing)
    {
        // ✅ GİZLİ İLAN KONTROLÜ
        $is_hidden = false;
        
        if($user_id !== NULL && !$show_hidden)
        {
            $hiddens = $hiddenModel->where('property_id', $listing['id'])
                                   ->where('user_id', $user_id)
                                   ->where('lang_code', getenv('LANG_CODE'))
                                   ->findAll(1);
            
            if(count($hiddens) > 0)
            {
                $is_hidden = true;
                $hidden_count++;
                
                if(getenv('CI_ENVIRONMENT') == 'development') {
                    log_message('info', "  🚫 Gizli ilan filtrelendi: " . $listing['property_id']);
                }
                
                continue; // Bu ilanı ekleme
            }
        }
        
        // ✅ İLAN VERİLERİNİ HAZIRLA
        $n_listing = array();
        $n_listing['post_id'] = $listing['property_id'];
        $n_listing['idlisting'] = $listing['property_id'];
        $n_listing['category_id'] = "2";
        $n_listing['address'] = $listing['address'];
        $n_listing['lat'] = $listing['lat'];
        $n_listing['lng'] = $listing['lng'];
        
        $n_listing['is_favorite'] = 'null';
        $n_listing['is_hidden'] = $is_hidden ? '1' : 'null';
        
        if($user_id !== NULL)
        {
            $favorites = $favoriteModel->where('property_id', $listing['id'])
                                       ->where('user_id', $user_id)
                                       ->where('lang_code', getenv('LANG_CODE'))
                                       ->findAll(1);
            
            if(count($favorites) > 0)
                $n_listing['is_favorite'] = '1';
        }
        
        $n_listing['guid'] = getenv('WEBSITE_URL').'index.php/'.getenv('LISTING_URI').'/'.$listing['id'];
        
        // Images
        $n_listing['listing_images_path_medium'] = '';
        $n_listing['listing_images_path'] = '';
        if(isset($listing['image_repository']))
        {
            $images_paths = json_decode($listing['image_repository']);
            
            foreach($images_paths as $key=>$path)
            {
                if(file_exists(getenv('FILES_DIRECTORY').'files/strict_cache/851x678'.$path))
                {
                    $images_paths[$key] = 'strict_cache/851x678'.$path;
                }
            }
            
            $n_listing['listing_images_path_medium'] = join(',', $images_paths);
            $n_listing['listing_images_path'] = join(',', $images_paths);
        }
        
        // Agent
        $n_listing['agent_exists'] = '0';
        $users = $userModel->where('property_id', $listing['id'])->findAllListing(1);
        if(count($users) > 0)
        {
            $n_listing['agent_exists'] = '1';
        }
        
        $json_object = json_decode($listing['json_object']);
        
        $n_listing['post_title'] = '';
        if(isset($json_object->{"field_10"}))
            $n_listing['post_title'] = $json_object->{"field_10"};
        
        $n_listing['location_name'] = '';
        if(isset($json_object->{"field_7"}))
            $n_listing['location_name'] = $json_object->{"field_7"};
        
        // Deadline
        $n_listing['deadline'] = '';
        if(isset($json_object->{"field_1015"})){
            $expiry_date = \DateTime::createFromFormat('d/m/Y', $json_object->{"field_1015"});
            
            if($expiry_date) {
                $today = new \DateTime('now');
                $diff = $expiry_date->diff($today);
                $remaining_days = $diff->invert ? $diff->days : 0;
                $n_listing['deadline'] = "$remaining_days";
            }
        }
        
        // Process fields
        foreach($fields as $field)
        {
            if(in_array($field['id'], array(77,10,78,8,17,38,6,56,1017,1015)))continue;
            if($field['type'] == 'HTMLTABLE')continue;
            if($field['type'] == 'PEDIGREE')continue;
            if($field['type'] == 'UPLOAD')continue;
            
            $value = '';
            
            if(isset($json_object->{"field_".$field['id']}))
            {
                $value = $json_object->{"field_".$field['id']};
                
                if($field['type'] == 'TEXTAREA')
                {
                    $value = strip_tags($value);
                    $value = str_replace('&amp;', '&', $value);
                }
                
                if($field['type'] == 'TREE' && strlen($value) > 2)
                {
                    $value = substr($value,0, -2);
                }
                
                if($value == '-')
                    $value = '';
            }
            
            if($value === true || $value === 'true')
                $value = '1';
            
            if($value === false || $value === 'false')
                $value = '0';
            
            if(!empty($value))
                $n_listing['field_'.$field['id'].'_'.$field['type']] = $field['prefix'].$value.$field['suffix'];
            
            if($field['type'] == 'INPUTBOX' && !empty($value))
            {
                $n_listing['field_'.$field['id'].'_NUMBER'] = $field['prefix'].$value.$field['suffix'];
            }
        }
        
        $n_listing['field_5_DROPDOWN'] = '';
        if(!empty($listing['field_4']))
            $n_listing['field_5_DROPDOWN'] = $listing['field_4'];
        
        $n_listing['field_6_NUMBER'] = '';
        if(!empty($n_listing['field_36_NUMBER']))
            $n_listing['field_6_NUMBER'] = str_replace('TL', '', $n_listing['field_36_NUMBER']);
        
        if(!empty($n_listing['field_36_NUMBER']))
            $n_listing['field_36_NUMBER'] = str_replace('TL', '€', $n_listing['field_36_NUMBER']);
        
        if(!empty($n_listing['field_36_INPUTBOX']))
            $n_listing['field_36_INPUTBOX'] = str_replace('TL', '€', $n_listing['field_36_INPUTBOX']);
        
        $n_listing['field_7_NUMBER'] = '';
        if(!empty($n_listing['field_37_NUMBER']))
            $n_listing['field_7_NUMBER'] = $n_listing['field_37_NUMBER'];
        
        $n_listing['post_content_stripped'] = '';
        if(!empty($json_object->{"field_17"}))
            $n_listing['post_content_stripped'] = strip_tags($json_object->{"field_17"});
        
        // Analytics
        if($include_analytics && isset($analytics_data[$listing['property_id']])) {
            $n_listing['analytics'] = $analytics_data[$listing['property_id']];
        }
        
        $processed_listings[] = $n_listing;
    }
    
    // Debug log
    if(getenv('CI_ENVIRONMENT') == 'development' && !$show_hidden) {
        log_message('info', "  ✅ İşleme tamamlandı: " . count($processed_listings) . " görünür, $hidden_count gizli");
    }
    
    return $processed_listings;
}
    
    public function provinces($return_data = false)
    {
        $primaryModel = model('App\Models\TreefieldModel');
        $data = array();
        
        $items = $primaryModel->where('language_id', getenv('LANGUAGE_ID'))
                              ->where('field_id', 64)
                              ->where('level', 1)
                              ->orderBy('value', 'ASC')
                              ->findAll();

        foreach($items as $item)
        {
            $n_item = array();
            $n_item['id'] = $item['treefield_id'];
            $n_item['title'] = $item['value'];
            $n_item['level'] = $item['level'];
            $n_item['parent_id'] = $item['parent_id'];
            $n_item['image_url'] = empty($item['image_filename']) ? '' : 'files/'.$item['image_filename'];
            
            $data[] = $n_item;
        }

        if($return_data)
            return $data;

        return $this->respond($data);
    }

public function locations_hierarchy($return_data = false)
{
    $primaryModel = model('App\Models\TreefieldModel');
    $db = \Config\Database::connect();
    
    $data = array();
    
    try {
        // ADIM 1: Tüm il ve ilçeleri veritabanından çek (Level 0 ve 1)
        $items = $primaryModel->where('language_id', getenv('LANGUAGE_ID'))
                              ->where('field_id', 64)
                              ->whereIn('level', [0, 1])
                              ->orderBy('level', 'ASC')
                              ->orderBy('value', 'ASC')
                              ->findAll();
        
        if(empty($items)) {
            if($return_data) return array();
            return $this->respond(array('code' => 'empty', 'data' => array()));
        }
        
        // ADIM 2: Her il ve ilçe için ilan sayısını hesapla
        $locationStats = array();
        $parentTotals = array(); // İllerin toplam ilan sayıları
        
        foreach($items as $item) {
            $locationId = $item['treefield_id'];
            $locationTitle = $item['value'];
            $level = intval($item['level']);
            $parentId = $item['parent_id'];
            
            // İlan sayısını sorgula
            $builder = $db->table('property p');
            $builder->select('COUNT(*) as total');
            $builder->join('property_lang pl', 'p.id = pl.property_id');
            $builder->where('pl.language_id', getenv('LANGUAGE_ID'));
            $builder->where('p.is_activated', '1');
            $builder->where('p.approval_status', 'approved');
            $builder->like('pl.json_object', $locationTitle . ' -');
            
            $result = $builder->get()->getRowArray();
            $listingCount = $result ? intval($result['total']) : 0;
            
            // İstatistikleri kaydet
            $locationStats[$locationId] = array(
                'id' => $locationId,
                'title' => $locationTitle,
                'level' => $level,
                'parent_id' => $parentId,
                'count_listings' => $listingCount,
                'image_url' => empty($item['image_filename']) 
                    ? '' 
                    : 'https://satisahazir.com/files/' . $item['image_filename'],
                'value_path' => $item['value_path'] ?? '',
            );
            
            // İlçe ise (Level 1), parent'ın (ilin) toplamına ekle
            if($level === 1 && !empty($parentId)) {
                if(!isset($parentTotals[$parentId])) {
                    $parentTotals[$parentId] = 0;
                }
                $parentTotals[$parentId] += $listingCount;
            }
            
            // Debug log
            if(getenv('CI_ENVIRONMENT') == 'development') {
                log_message('info', "Location Stat: $locationTitle (Level $level) - $listingCount ilan");
            }
        }
        
        // ADIM 3: Sonuçları filtrele ve hazırla
        foreach($locationStats as $locationId => $stat) {
            $level = $stat['level'];
            $listingCount = $stat['count_listings'];
            
            // İlçe kontrolü (Level 1): İlan yoksa ekleme
            if($level === 1) {
                if($listingCount <= 0) {
                    if(getenv('CI_ENVIRONMENT') == 'development') {
                        log_message('info', "❌ İlçe atlandı (ilan yok): {$stat['title']}");
                    }
                    continue; // İlçede ilan yoksa atla
                }
                
                // İlçede ilan var, ekle
                $data[] = array(
                    'id' => $stat['id'],
                    'title' => $stat['title'],
                    'level' => (string)$stat['level'],
                    'parent_id' => $stat['parent_id'],
                    'count_listings' => $listingCount,
                    'image_url' => $stat['image_url'],
                    'value_path' => $stat['value_path'],
                );
                
                if(getenv('CI_ENVIRONMENT') == 'development') {
                    log_message('info', "✅ İlçe eklendi: {$stat['title']} - $listingCount ilan");
                }
            }
            // İl kontrolü (Level 0): Alt ilçelerde ilan yoksa ekleme
            else if($level === 0) {
                $totalCount = isset($parentTotals[$locationId]) ? $parentTotals[$locationId] : 0;
                
                if($totalCount <= 0) {
                    if(getenv('CI_ENVIRONMENT') == 'development') {
                        log_message('info', "❌ İl atlandı (alt ilçelerde ilan yok): {$stat['title']}");
                    }
                    continue; // İlde hiç ilan yoksa atla
                }
                
                // İlde ilan var, ekle
                $data[] = array(
                    'id' => $stat['id'],
                    'title' => $stat['title'],
                    'level' => (string)$stat['level'],
                    'parent_id' => $stat['parent_id'],
                    'count_listings' => $totalCount, // İl için toplam sayı
                    'image_url' => $stat['image_url'],
                    'value_path' => $stat['value_path'],
                );
                
                if(getenv('CI_ENVIRONMENT') == 'development') {
                    log_message('info', "✅ İl eklendi: {$stat['title']} - $totalCount ilan (toplam)");
                }
            }
        }
        
        // ADIM 4: Sonuçları sırala (Level ve alfabetik)
        usort($data, function($a, $b) {
            // Önce level'a göre sırala (0 önce, 1 sonra)
            if($a['level'] != $b['level']) {
                return intval($a['level']) - intval($b['level']);
            }
            // Aynı level ise alfabetik sırala
            return strcmp($a['title'], $b['title']);
        });
        
        // ADIM 5: Sonuç özeti
        $provinceCount = count(array_filter($data, function($item) {
            return $item['level'] === '0';
        }));
        
        $districtCount = count(array_filter($data, function($item) {
            return $item['level'] === '1';
        }));
        
        if(getenv('CI_ENVIRONMENT') == 'development') {
            log_message('info', "📊 Location Hierarchy Özet:");
            log_message('info', "   İller (Level 0): $provinceCount");
            log_message('info', "   İlçeler (Level 1): $districtCount");
            log_message('info', "   Toplam: " . count($data));
        }
        
        // ADIM 6: Yanıtı döndür
        if($return_data) {
            return $data; // Internal kullanım için sadece data array'i
        }
        
        // API yanıtı için detaylı format
        return $this->respond(array(
            'code' => 'success',
            'count' => count($data),
            'provinces' => $provinceCount,
            'districts' => $districtCount,
            'data' => $data
        ));
        
    } catch(\Exception $e) {
        // Hata yönetimi
        log_message('error', 'Location Hierarchy Error: ' . $e->getMessage());
        
        if($return_data) {
            return array();
        }
        
        return $this->respond(array(
            'code' => 'error',
            'message' => 'Lokasyonlar yüklenirken hata oluştu',
            'error' => getenv('CI_ENVIRONMENT') == 'development' ? $e->getMessage() : null,
            'data' => array()
        ));
    }
}

// ============================================
// DISTRICTS - Sadece ilanlı ilçeler
// ============================================
public function districts($return_data = false)
{
    $primaryModel = model('App\Models\TreefieldModel');
    $listingModel = model('App\Models\ListingModel');
    $data = array();
    
    try {
        // Parent ID parametresi
        $parentId = $_GET['parent_id'] ?? null;
        
        // İlçeleri çek (Level 2)
        $query = $primaryModel->where('language_id', getenv('LANGUAGE_ID'))
                              ->where('field_id', 64)
                              ->where('level', 2);
        
        if($parentId) {
            $query->where('parent_id', $parentId);
        }
        
        $items = $query->orderBy('value', 'ASC')->findAll();
        
        foreach($items as $item) {
            // İlan sayısını kontrol et
            $countListings = $listingModel->where('language_id', getenv('LANGUAGE_ID'))
                                          ->where('is_activated', '1')
                                          ->where('json_object LIKE \'%' . $item['value'] . ' -%\'', NULL)
                                          ->countAllResults();
            
            // Sadece ilanlı ilçeleri ekle
            if($countListings > 0) {
                $data[] = array(
                    'id' => $item['treefield_id'],
                    'title' => $item['value'],
                    'level' => $item['level'],
                    'parent_id' => $item['parent_id'],
                    'count_listings' => $countListings,
                    'image_url' => empty($item['image_filename']) 
                        ? '' 
                        : 'files/' . $item['image_filename'],
                );
            }
        }
        
        if($return_data) {
            return $data;
        }
        
        return $this->respond(array(
            'code' => 'success',
            'count' => count($data),
            'parent_id' => $parentId,
            'data' => $data
        ));
        
    } catch(\Exception $e) {
        log_message('error', 'Districts Error: ' . $e->getMessage());
        
        if($return_data) {
            return array();
        }
        
        return $this->respond(array(
            'code' => 'error',
            'message' => 'İlçeler yüklenirken hata oluştu',
            'data' => array()
        ));
    }
}

// ============================================
// NEIGHBORHOODS - Sadece ilanlı mahalleler
// ============================================
public function neighborhoods($return_data = false)
{
    $primaryModel = model('App\Models\TreefieldModel');
    $db = \Config\Database::connect();
    $data = array();
    
    try {
        // District ID parametresi (hem district_id hem parent_id destekle)
        $districtId = $_GET['district_id'] ?? $_GET['parent_id'] ?? null;
        
        if(empty($districtId)) {
            return $this->respond(array(
                'code' => 'error',
                'message' => 'district_id veya parent_id parametresi gerekli',
                'data' => array()
            ));
        }
        
        // Mahalleleri çek (Level 2, belirli ilçeye ait)
        $items = $primaryModel->where('language_id', getenv('LANGUAGE_ID'))
                              ->where('field_id', 64)
                              ->where('level', 2)
                              ->where('parent_id', $districtId)
                              ->orderBy('value', 'ASC')
                              ->findAll();
        
        if(empty($items)) {
            if($return_data) {
                return array();
            }
            
            return $this->respond(array(
                'code' => 'success',
                'message' => 'Bu ilçeye ait mahalle bulunamadı',
                'district_id' => $districtId,
                'count' => 0,
                'data' => array()
            ));
        }
        
        // Her mahalle için ilan sayısını kontrol et
        foreach($items as $item) {
            $neighborhoodTitle = $item['value'];
            
            // İlan sayısını sorgula
            $builder = $db->table('property p');
            $builder->select('COUNT(*) as total');
            $builder->join('property_lang pl', 'p.id = pl.property_id');
            $builder->where('pl.language_id', getenv('LANGUAGE_ID'));
            $builder->where('p.is_activated', '1');
            $builder->where('p.approval_status', 'approved');
            $builder->like('pl.json_object', $neighborhoodTitle . ' -');
            
            $result = $builder->get()->getRowArray();
            $countListings = $result ? intval($result['total']) : 0;
            
            // Sadece ilanlı mahalleleri ekle
            if($countListings > 0) {
                $data[] = array(
                    'id' => $item['treefield_id'],
                    'title' => $neighborhoodTitle,
                    'level' => '2',
                    'parent_id' => $item['parent_id'],
                    'count_listings' => $countListings,
                    'image_url' => empty($item['image_filename']) 
                        ? '' 
                        : 'https://satisahazir.com/files/' . $item['image_filename'],
                    'value_path' => $item['value_path'] ?? '',
                );
                
                if(getenv('CI_ENVIRONMENT') == 'development') {
                    log_message('info', "✅ Mahalle: $neighborhoodTitle - $countListings ilan");
                }
            }
        }
        
        if(getenv('CI_ENVIRONMENT') == 'development') {
            log_message('info', "📊 Mahalle Özet: " . count($data) . " ilanlı mahalle bulundu");
        }
        
        if($return_data) {
            return $data;
        }
        
        return $this->respond(array(
            'code' => 'success',
            'district_id' => $districtId,
            'count' => count($data),
            'data' => $data
        ));
        
    } catch(\Exception $e) {
        log_message('error', 'Neighborhoods Error: ' . $e->getMessage());
        
        if($return_data) {
            return array();
        }
        
        return $this->respond(array(
            'code' => 'error',
            'message' => 'Mahalleler yüklenirken hata oluştu',
            'error' => getenv('CI_ENVIRONMENT') == 'development' ? $e->getMessage() : null,
            'data' => array()
        ));
    }
}


// ⚠️ GÜNCELLENMİŞ: Eski neighborhoods metodu - geriye uyumluluk
public function neighborhoods_legacy($return_data = false)
{
    $primaryModel = model('App\Models\TreefieldModel');
    $listingModel = model('App\Models\ListingModel');
    $data = array();
    
    $parent_id = $_GET['parent_id'] ?? null;
    
    $query = $primaryModel->where('language_id', getenv('LANGUAGE_ID'))
                          ->where('field_id', 64)
                          ->where('level', 2);
    
    if($parent_id) {
        $query->where('parent_id', $parent_id);
    }
    
    $items = $query->orderBy('value', 'ASC')->findAll();

    foreach($items as $item)
    {
        $count_listings = $listingModel->where('language_id', getenv('LANGUAGE_ID'))
                                      ->where('json_object LIKE \'%'.$item['value'].' -%\'', NULL)
                                      ->countAllResults();
        
        if($count_listings > 0) {
            $n_item = array();
            $n_item['id'] = $item['treefield_id'];
            $n_item['title'] = $item['value'];
            $n_item['level'] = '2';
            $n_item['parent_id'] = $item['parent_id'];
            $n_item['count_listings'] = $count_listings;
            $n_item['image_url'] = empty($item['image_filename']) ? '' : 'https://satisahazir.com/files/'.$item['image_filename'];
            
            $data[] = $n_item;
        }
    }

    if($return_data)
        return $data;

    return $this->respond($data);
}

/**
 * TÜM İLLERİ VE İLÇELERİ GETİR (Mahalleler yok, İlan sayısı kontrolü yok)
 * EmptyPropertyState için özel endpoint
 * URL: /wp-json/wdk/v1/locations/all_for_search
 */
public function getAllForSearch($return_data = false)
{
    $primaryModel = model('App\Models\TreefieldModel');
    $data = array();
    
    try {
        if(getenv('CI_ENVIRONMENT') == 'development') {
            log_message('info', '🌍 getAllForSearch çağrıldı');
        }
        
        // ADIM 1: TÜM İLLERİ ÇEK (Level 0)
        $provinces = $primaryModel->where('language_id', getenv('LANGUAGE_ID'))
                                  ->where('field_id', 64)  // Location field ID
                                  ->where('level', 0)
                                  ->orderBy('value', 'ASC')
                                  ->findAll();
        
        $province_data = array();
        foreach($provinces as $province) {
            $province_data[] = array(
                'id' => $province['treefield_id'],
                'title' => $province['value'],
                'level' => '0',
                'parent_id' => $province['parent_id'] ?? '',
            );
        }
        
        // ADIM 2: TÜM İLÇELERİ ÇEK (Level 1)
        $districts = $primaryModel->where('language_id', getenv('LANGUAGE_ID'))
                                  ->where('field_id', 64)
                                  ->where('level', 1)
                                  ->orderBy('value', 'ASC')
                                  ->findAll();
        
        $district_data = array();
        foreach($districts as $district) {
            $district_data[] = array(
                'id' => $district['treefield_id'],
                'title' => $district['value'],
                'level' => '1',
                'parent_id' => $district['parent_id'] ?? '',
            );
        }
        
        // Debug log
        if(getenv('CI_ENVIRONMENT') == 'development') {
            log_message('info', '✅ getAllForSearch tamamlandı:');
            log_message('info', '   İller: ' . count($province_data));
            log_message('info', '   İlçeler: ' . count($district_data));
        }
        
        // ADIM 3: Yanıtı hazırla
        $response = array(
            'code' => 'success',
            'message' => 'All locations retrieved successfully',
            'data' => array(
                'provinces' => $province_data,
                'districts' => $district_data,
            )
        );
        
        if($return_data) {
            return $response;
        }
        
        return $this->respond($response);
        
    } catch(\Exception $e) {
        log_message('error', 'getAllForSearch error: ' . $e->getMessage());
        
        $error_response = array(
            'code' => 'error',
            'message' => 'Failed to retrieve all locations',
            'error' => getenv('CI_ENVIRONMENT') == 'development' ? $e->getMessage() : 'Internal server error',
            'data' => array(
                'provinces' => array(),
                'districts' => array(),
            )
        );
        
        if($return_data) {
            return $error_response;
        }
        
        return $this->respond($error_response, 500);
    }
}


}