<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;

class AnalyticsController extends ResourceController
{
    use ResponseTrait;
    
    protected $analyticsModel;
    protected $tokenModel;
    protected $userModel;
    
    public function __construct()
    {
        $this->analyticsModel = model('App\Models\AnalyticsModel');
        $this->tokenModel = model('App\Models\TokenModel');
        $this->userModel = model('App\Models\UserModel');
    }
    
    /**
     * Gerçek client IP adresini al
     */
    private function getRealClientIP()
    {
        $ip_keys = array(
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_FORWARDED',
            'HTTP_X_CLUSTER_CLIENT_IP',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'REMOTE_ADDR'
        );
        
        foreach ($ip_keys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    $ip = trim($ip);
                    // Özel IP aralıklarını ve reserved IP'leri filtrele
                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                        return $ip;
                    }
                }
            }
        }
        
        return $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
    }
    
    /**
     * User ID'yi güvenli şekilde al (multiple sources)
     */
    private function getUserIdFromRequest($data_json = null)
    {
        $userId = null;
        
        // 1. Query parameter'dan al
        if (!empty($_GET['user_id'])) {
            $userId = $_GET['user_id'];
            log_message('debug', 'User ID from query param: ' . $userId);
        }
        
        // 2. POST body'den al
        if (!$userId && $data_json && !empty($data_json->user_id)) {
            $userId = $data_json->user_id;
            log_message('debug', 'User ID from JSON body: ' . $userId);
        }
        
        // 3. Custom header'dan al
        if (!$userId && !empty($_SERVER['HTTP_X_USER_ID'])) {
            $userId = $_SERVER['HTTP_X_USER_ID'];
            log_message('debug', 'User ID from X-User-ID header: ' . $userId);
        }
        
        // 4. Token'dan al
        if (!$userId && !empty($_GET['token'])) {
            $token = $_GET['token'];
            $user_token = $this->tokenModel->where('token', $token)->findAll(1);
            
            if (count($user_token) > 0) {
                $userId = $user_token[0]['user_id'];
                log_message('debug', 'User ID from token: ' . $userId);
            }
        }
        
        if ($userId) {
            log_message('info', '✅ Final User ID: ' . $userId);
        } else {
            log_message('warning', '⚠️ User ID could not be determined');
        }
        
        return $userId;
    }
    
    /**
     * İlan görüntüleme kaydı - DÜZELTILMIŞ
     */
    public function recordView()
    {
         $data_json = $this->request->getJSON();
    
    $userId = $this->getUserIdFromRequest($data_json);
    $clientIP = $this->getRealClientIP();
    $deviceType = $this->detectDeviceType($data_json);
    $platform = $this->detectPlatform($data_json); // ✅ YENİ
    
    log_message('info', '📊 RecordView - Property: ' . ($data_json->property_id ?? 'N/A') . 
                       ', User: ' . ($userId ?? 'NULL') . 
                       ', IP: ' . $clientIP . 
                       ', Platform: ' . $platform .  // ✅ YENİ
                       ', Device: ' . $deviceType);
    
    $viewData = [
        'property_id' => $data_json->property_id,
        'user_id' => $userId,
        'session_id' => $data_json->session_id ?? session_id(),
        'ip_address' => $clientIP,
        'user_agent' => $data_json->user_agent ?? $_SERVER['HTTP_USER_AGENT'] ?? '',
        'device_type' => $deviceType,
        'platform' => $platform, // ✅ YENİ - veritabanına kaydet
        'referrer' => $data_json->referrer ?? ($_SERVER['HTTP_REFERER'] ?? null)
    ];
        
        log_message('debug', 'View data to be recorded: ' . json_encode($viewData));
        
        $viewId = $this->analyticsModel->recordPropertyView($viewData);
        
        if ($viewId) {
            log_message('info', '✅ View recorded successfully - View ID: ' . $viewId);
            
            return $this->respond([
                'code' => 'success',
                'message' => 'Görüntüleme kaydedildi',
                'view_id' => $viewId,
                'user_id' => $userId,
                'ip_address' => $clientIP
            ]);
        } else {
            log_message('error', '❌ View recording failed');
            
            return $this->respond([
                'code' => 'failed',
                'message' => 'Görüntüleme kaydedilemedi'
            ], 500);
        }
    }
    
    /**
 * ✅ Device Type'ı akıllıca belirle - Detaylı Platform bilgisi
 */
private function detectDeviceType($data_json = null)
{
    // 1. JSON body'den al (öncelikli)
    if ($data_json && !empty($data_json->device_type)) {
        $deviceType = strtolower($data_json->device_type);
        log_message('debug', '📱 Device type from JSON body: ' . $deviceType);
        return $deviceType;
    }
    
    // 2. Custom header'dan al
    if (!empty($_SERVER['HTTP_X_DEVICE_TYPE'])) {
        $deviceType = strtolower($_SERVER['HTTP_X_DEVICE_TYPE']);
        log_message('debug', '📱 Device type from X-Device-Type header: ' . $deviceType);
        return $deviceType;
    }
    
    // 3. User Agent'tan çıkar
    $userAgent = $data_json->user_agent ?? $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    log_message('debug', '📱 Detecting device type from User-Agent: ' . $userAgent);
    
    // SatisaHazir custom user agent kontrolü
    if (stripos($userAgent, 'SatisaHazir-Android') !== false) {
        // Android tablet kontrolü
        if (stripos($userAgent, 'Tab') !== false || stripos($userAgent, 'Pad') !== false) {
            log_message('debug', '📱 Detected: SatisaHazir Android App (Tablet)');
            return 'tablet';
        }
        log_message('debug', '📱 Detected: SatisaHazir Android App (Mobile)');
        return 'mobile';
    }
    
    if (stripos($userAgent, 'SatisaHazir-iOS') !== false) {
        // iPad kontrolü
        if (stripos($userAgent, 'iPad') !== false) {
            log_message('debug', '📱 Detected: SatisaHazir iOS App (iPad)');
            return 'tablet';
        }
        log_message('debug', '📱 Detected: SatisaHazir iOS App (iPhone)');
        return 'mobile';
    }
    
    // Fallback
    log_message('warning', '⚠️ Could not detect device type, defaulting to mobile. User-Agent: ' . $userAgent);
    return 'mobile';
}

/**
 * ✅ Platform bilgisini al (ios/android)
 */
private function detectPlatform($data_json = null)
{
    // 1. JSON body'den al
    if ($data_json && !empty($data_json->platform)) {
        $platform = strtolower($data_json->platform);
        log_message('debug', '📱 Platform from JSON body: ' . $platform);
        return $platform;
    }
    
    // 2. Custom header'dan al
    if (!empty($_SERVER['HTTP_X_PLATFORM'])) {
        $platform = strtolower($_SERVER['HTTP_X_PLATFORM']);
        log_message('debug', '📱 Platform from X-Platform header: ' . $platform);
        return $platform;
    }
    
    // 3. User Agent'tan çıkar
    $userAgent = $data_json->user_agent ?? $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    if (stripos($userAgent, 'SatisaHazir-iOS') !== false || stripos($userAgent, 'iOS') !== false) {
        return 'ios';
    }
    
    if (stripos($userAgent, 'SatisaHazir-Android') !== false || stripos($userAgent, 'Android') !== false) {
        return 'android';
    }
    
    return 'unknown';
}
    
    /**
     * Görüntüleme süresi güncelleme - YORUM SATIRI (İSTEĞE BAĞLI KULLANILMAYACAK)
     */

 public function updateViewDuration()
{
    $data_json = $this->request->getJSON();
    
    if (empty($data_json->view_id)) {
        log_message('error', '❌ updateViewDuration - view_id missing');
        return $this->respond([
            'code' => 'failed',
            'message' => 'View ID gerekli'
        ], 400);
    }
    
    $viewId = $data_json->view_id;
    $duration = $data_json->duration ?? 0;
    $isFinal = $data_json->is_final ?? false;
    
    log_message('info', '⏱️ updateViewDuration - View ID: ' . $viewId . 
                       ', Duration: ' . $duration . 's' .
                       ', Is Final: ' . ($isFinal ? 'yes' : 'no'));
    
    // ✅ Sadece UPDATE - çok hafif işlem
    $result = $this->analyticsModel->updateViewDuration($viewId, $duration);
    
    if ($result) {
        log_message('info', '✅ View duration updated - View ID: ' . $viewId);
        
        return $this->respond([
            'code' => 'success',
            'message' => 'Görüntüleme süresi güncellendi',
            'view_id' => $viewId,
            'duration' => $duration
        ]);
    } else {
        log_message('error', '❌ View duration update failed - View ID: ' . $viewId);
        
        return $this->respond([
            'code' => 'failed',
            'message' => 'Görüntüleme süresi güncellenemedi'
        ], 500);
    }
}
    
 
    
    /**
     * Uygulama açılış kaydı
     */
    public function recordAppOpen()
    {
        // User ID'yi al
        $userId = $this->getUserIdFromRequest();
        
        if (!$userId) {
            log_message('warning', '⚠️ RecordAppOpen - User ID bulunamadı');
            return $this->respond([
                'code' => 'failed',
                'message' => 'User ID gerekli'
            ], 400);
        }
        
        log_message('info', '📱 RecordAppOpen - User ID: ' . $userId);
        
        $success = $this->analyticsModel->recordAppOpen($userId);
        
        return $this->respond([
            'code' => $success ? 'success' : 'failed',
            'message' => $success ? 'Uygulama açılışı kaydedildi' : 'Kayıt başarısız'
        ]);
    }
    
    /**
     * İlan istatistiklerini getir
     */
    public function getPropertyStats()
    {
        // User ID'yi al
        $userId = $this->getUserIdFromRequest();
        
        if (!$userId) {
            return $this->respond([
                'code' => 'failed',
                'message' => 'Token veya User ID gerekli'
            ], 401);
        }
        
        // Kullanıcı tipini kontrol et
        $user = $this->userModel->find($userId);
        
        if (!$user) {
            return $this->respond([
                'code' => 'failed',
                'message' => 'Kullanıcı bulunamadı'
            ], 404);
        }
        
        // Property ID kontrolü
        if (empty($_GET['property_id'])) {
            return $this->respond([
                'code' => 'failed',
                'message' => 'Property ID gerekli'
            ], 400);
        }
        
        $propertyId = $_GET['property_id'];
        
        // Yetki kontrolü (Admin her şeyi görebilir, Agent sadece kendi ilanlarını)
        if ($user['type'] == 'AGENT') {
            $builder = $this->db->table('property_user');
            $propertyUser = $builder->where('property_id', $propertyId)
                                   ->where('user_id', $userId)
                                   ->get()->getRowArray();
            
            if (!$propertyUser) {
                return $this->respond([
                    'code' => 'failed',
                    'message' => 'Bu ilan için yetkiniz yok'
                ], 403);
            }
        } elseif ($user['type'] != 'ADMIN' && $user['type'] != 'SUPER_ADMIN') {
            return $this->respond([
                'code' => 'failed',
                'message' => 'Bu işlem için yetkiniz yok'
            ], 403);
        }
        
        $stats = $this->analyticsModel->getPropertyStatistics($propertyId);
        
        return $this->respond([
            'code' => 'success',
            'data' => $stats
        ]);
    }
    
    /**
     * Agent portföy istatistiklerini getir
     */
    public function getAgentPortfolioStats()
    {
        // User ID'yi al
        $userId = $this->getUserIdFromRequest();
        
        if (!$userId) {
            return $this->respond([
                'code' => 'failed',
                'message' => 'Token veya User ID gerekli'
            ], 401);
        }
        
        // Kullanıcı tipini kontrol et
        $user = $this->userModel->find($userId);
        
        if (!$user) {
            return $this->respond([
                'code' => 'failed',
                'message' => 'Kullanıcı bulunamadı'
            ], 404);
        }
        
        // Agent ID belirle
        $agentId = null;
        if ($user['type'] == 'AGENT') {
            $agentId = $userId;
        } elseif (($user['type'] == 'ADMIN' || $user['type'] == 'SUPER_ADMIN') && !empty($_GET['agent_id'])) {
            $agentId = $_GET['agent_id'];
        } else {
            return $this->respond([
                'code' => 'failed',
                'message' => 'Agent ID belirlenemedi'
            ], 400);
        }
        
        log_message('info', '📊 GetAgentPortfolioStats - Agent ID: ' . $agentId);
        
        $stats = $this->analyticsModel->getAgentPortfolioStatistics($agentId);
        
        return $this->respond([
            'code' => 'success',
            'data' => $stats
        ]);
    }
    
    /**
     * Kullanıcı istatistiklerini getir
     */
    public function getUserStats()
    {
        // Current User ID'yi al
        $currentUserId = $this->getUserIdFromRequest();
        
        if (!$currentUserId) {
            return $this->respond([
                'code' => 'failed',
                'message' => 'Token veya User ID gerekli'
            ], 401);
        }
        
        // Kullanıcı tipini kontrol et
        $user = $this->userModel->find($currentUserId);
        
        if (!$user) {
            return $this->respond([
                'code' => 'failed',
                'message' => 'Kullanıcı bulunamadı'
            ], 404);
        }
        
        // Hangi kullanıcının istatistikleri isteniyorsa
        $targetUserId = $_GET['target_user_id'] ?? $_GET['user_id'] ?? $currentUserId;
        
        // Yetki kontrolü
        if ($targetUserId != $currentUserId && $user['type'] != 'ADMIN' && $user['type'] != 'SUPER_ADMIN') {
            return $this->respond([
                'code' => 'failed',
                'message' => 'Bu kullanıcının istatistiklerini görme yetkiniz yok'
            ], 403);
        }
        
        log_message('info', '📊 GetUserStats - Target User ID: ' . $targetUserId);
        
        $stats = $this->analyticsModel->getUserStatistics($targetUserId);
        
        return $this->respond([
            'code' => 'success',
            'data' => $stats
        ]);
    }
    
    /**
     * Admin dashboard istatistikleri
     */
    public function getAdminDashboard()
    {
        // User ID'yi al
        $userId = $this->getUserIdFromRequest();
        
        if (!$userId) {
            return $this->respond([
                'code' => 'failed',
                'message' => 'Token veya User ID gerekli'
            ], 401);
        }
        
        // Admin kontrolü
        $user = $this->userModel->find($userId);
        
        if (!$user || ($user['type'] != 'ADMIN' && $user['type'] != 'SUPER_ADMIN')) {
            return $this->respond([
                'code' => 'failed',
                'message' => 'Bu işlem için admin yetkisi gerekli'
            ], 403);
        }
        
        // Filtreler
        $filters = [
            'date_from' => $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days')),
            'date_to' => $_GET['date_to'] ?? date('Y-m-d')
        ];
        
        log_message('info', '📊 GetAdminDashboard - User ID: ' . $userId . ', Filters: ' . json_encode($filters));
        
        $stats = $this->analyticsModel->getAllStatistics($filters);
        
        return $this->respond([
            'code' => 'success',
            'data' => $stats
        ]);
    }
    
    /**
 * Arama kaydı oluştur
 */

/**
 * Arama istatistiklerini getir
 */
public function getSearchStatistics()
{
    $searchModel = model('App\Models\SearchHistoryModel');
    
    try {
        $summary = $searchModel->getSearchStatisticsSummary();
        $topLocations = $searchModel->getTopSearchedLocations(10);
        $topCategories = $searchModel->getTopSearchedCategories(10);
        $topPriceRanges = $searchModel->getTopSearchedPriceRanges(10);
        $topQueries = $searchModel->getTopSearchQueries(20);
        $trend = $searchModel->getSearchTrend(30);
        
        return $this->respond([
            'code' => 'success',
            'data' => [
                'summary' => $summary,
                'top_locations' => $topLocations,
                'top_categories' => $topCategories,
                'top_price_ranges' => $topPriceRanges,
                'top_queries' => $topQueries,
                'trend_30_days' => $trend,
            ]
        ]);
        
    } catch(\Exception $e) {
        log_message('error', 'getSearchStatistics error: ' . $e->getMessage());
        
        return $this->respond([
            'code' => 'error',
            'message' => 'Failed to get statistics',
            'error' => getenv('CI_ENVIRONMENT') == 'development' ? $e->getMessage() : null
        ], 500);
    }
}

/**
 * Aramayı kaydet - DÜZELTİLDİ
 */
public function saveSearch()
{
    $data_json = $this->request->getJSON();
    
    if(empty($data_json->search_id)) {
        return $this->respond([
            'code' => 'error',
            'message' => 'search_id required'
        ], 400);
    }
    
    $tokenModel = model('App\Models\TokenModel');
    $searchModel = model('App\Models\SearchHistoryModel');
    
    // ✅ Token'ı JSON body'den AL
    if(empty($data_json->token)) {
        return $this->respond([
            'code' => 'error',
            'message' => 'Token required'
        ], 401);
    }
    
    $token = $data_json->token; // ✅ JSON'dan al
    $user_token = $tokenModel->where('token', $token)->findAll(1);
    
    if(count($user_token) == 0) {
        return $this->respond([
            'code' => 'error',
            'message' => 'Invalid token'
        ], 401);
    }
    
    $user_id = $user_token[0]['user_id'];
    
    // ✅ Kullanıcı yetkisi kontrolü
    $search = $searchModel->where('id', $data_json->search_id)
                         ->where('user_id', $user_id)
                         ->first();
    
    if (!$search) {
        return $this->respond([
            'code' => 'error',
            'message' => 'Search not found or unauthorized'
        ], 404);
    }
    
    try {
        $result = $searchModel->saveUserSearch(
            $data_json->search_id,
            $data_json->title ?? null,
            $data_json->notification_enabled ?? 1
        );
        
        if($result) {
            return $this->respond([
                'code' => 'success',
                'message' => 'Search saved successfully'
            ]);
        } else {
            return $this->respond([
                'code' => 'error',
                'message' => 'Failed to save search'
            ], 500);
        }
        
    } catch(\Exception $e) {
        log_message('error', 'saveSearch error: ' . $e->getMessage());
        
        return $this->respond([
            'code' => 'error',
            'message' => 'Server error',
            'error' => getenv('CI_ENVIRONMENT') == 'development' ? $e->getMessage() : null
        ], 500);
    }
}

/**
 * Aramayı sil (soft delete) - DÜZELTİLDİ
 */
public function deleteSearch()
{
    $data_json = $this->request->getJSON();
    
    if(empty($data_json->search_id)) {
        return $this->respond([
            'code' => 'error',
            'message' => 'search_id required'
        ], 400);
    }
    
    $tokenModel = model('App\Models\TokenModel');
    $searchModel = model('App\Models\SearchHistoryModel');
    
    // ✅ Token'ı JSON body'den AL
    if(empty($data_json->token)) {
        return $this->respond([
            'code' => 'error',
            'message' => 'Token required'
        ], 401);
    }
    
    $token = $data_json->token; // ✅ JSON'dan al
    $user_token = $tokenModel->where('token', $token)->findAll(1);
    
    if(count($user_token) == 0) {
        return $this->respond([
            'code' => 'error',
            'message' => 'Invalid token'
        ], 401);
    }
    
    $user_id = $user_token[0]['user_id'];
    
    // ✅ Kullanıcı yetkisi kontrolü
    $search = $searchModel->where('id', $data_json->search_id)
                         ->where('user_id', $user_id)
                         ->first();
    
    if (!$search) {
        return $this->respond([
            'code' => 'error',
            'message' => 'Search not found or unauthorized'
        ], 404);
    }
    
    try {
        $result = $searchModel->softDeleteSearch($data_json->search_id);
        
        if($result) {
            return $this->respond([
                'code' => 'success',
                'message' => 'Search deleted successfully'
            ]);
        } else {
            return $this->respond([
                'code' => 'error',
                'message' => 'Failed to delete search'
            ], 500);
        }
        
    } catch(\Exception $e) {
        log_message('error', 'deleteSearch error: ' . $e->getMessage());
        
        return $this->respond([
            'code' => 'error',
            'message' => 'Server error',
            'error' => getenv('CI_ENVIRONMENT') == 'development' ? $e->getMessage() : null
        ], 500);
    }
}

/**
 * Bildirim durumunu değiştir - DÜZELTİLDİ
 */
public function toggleSearchNotification()
{
    $data_json = $this->request->getJSON();
    
    if(empty($data_json->search_id)) {
        return $this->respond([
            'code' => 'error',
            'message' => 'search_id required'
        ], 400);
    }
    
    $tokenModel = model('App\Models\TokenModel');
    $searchModel = model('App\Models\SearchHistoryModel');
    
    // ✅ Token'ı JSON body'den AL
    if(empty($data_json->token)) {
        return $this->respond([
            'code' => 'error',
            'message' => 'Token required'
        ], 401);
    }
    
    $token = $data_json->token; // ✅ JSON'dan al
    $user_token = $tokenModel->where('token', $token)->findAll(1);
    
    if(count($user_token) == 0) {
        return $this->respond([
            'code' => 'error',
            'message' => 'Invalid token'
        ], 401);
    }
    
    $user_id = $user_token[0]['user_id'];
    
    // ✅ Kullanıcı yetkisi kontrolü
    $search = $searchModel->where('id', $data_json->search_id)
                         ->where('user_id', $user_id)
                         ->first();
    
    if (!$search) {
        return $this->respond([
            'code' => 'error',
            'message' => 'Search not found or unauthorized'
        ], 404);
    }
    
    try {
        $enabled = $data_json->enabled ?? true;
        $result = $searchModel->toggleNotification($data_json->search_id, $enabled);
        
        if($result) {
            return $this->respond([
                'code' => 'success',
                'message' => 'Notification status updated',
                'notification_enabled' => $enabled
            ]);
        } else {
            return $this->respond([
                'code' => 'error',
                'message' => 'Failed to update notification'
            ], 500);
        }
        
    } catch(\Exception $e) {
        log_message('error', 'toggleSearchNotification error: ' . $e->getMessage());
        
        return $this->respond([
            'code' => 'error',
            'message' => 'Server error',
            'error' => getenv('CI_ENVIRONMENT') == 'development' ? $e->getMessage() : null
        ], 500);
    }
}

// app/Controllers/AnalyticsController.php

public function recordSearch()
{
    error_log('===============================');
    error_log('recordSearch API ÇAĞRILDI');
    
    try {
        $json = $this->request->getJSON(true);
        error_log('📥 Gelen JSON: ' . print_r($json, true));
        
        if (!isset($json['token']) || !isset($json['device_id'])) {
            error_log('❌ Token veya device_id yok!');
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Token ve device_id gerekli'
            ])->setStatusCode(400);
        }

        $tokenModel = model('App\Models\TokenModel');
        $searchHistoryModel = model('App\Models\SearchHistoryModel');
        
        $tokenData = $tokenModel->where('token', $json['token'])->first();
        error_log('🔐 Token validation: ' . ($tokenData ? 'BAŞARILI' : 'BAŞARISIZ'));
        
        if (!$tokenData) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Geçersiz token'
            ])->setStatusCode(401);
        }

        $userId = $tokenData['user_id'];
        
        // ✅ search_filters JSON'unu parse et
        $searchFilters = $json['search_filters'] ?? [];
        
        if (is_string($searchFilters)) {
            $searchFilters = json_decode($searchFilters, true) ?? [];
        }
        
        error_log('🔍 Parsed search_filters: ' . print_r($searchFilters, true));
        
        // ✅ Arama verisini hazırla
        $searchData = [
            'user_id' => $userId,
            'device_id' => $json['device_id'],
            
            // Arama metni
            'search_query' => $json['search_query'] ?? 
                             $searchFilters['search'] ?? 
                             $searchFilters['field_search'] ?? 
                             null,
                             
            // Lokasyon ID
            'search_location' => $json['search_location'] ?? 
                                $searchFilters['search_location'] ?? 
                                $searchFilters['location_id'] ?? 
                                null,
                                
            // Kategori ID
            'search_category' => $json['search_category'] ?? 
                                $searchFilters['search_category'] ?? 
                                $searchFilters['category_id'] ?? 
                                null,
                                
            // Fiyat
            'price_min' => $json['price_min'] ?? 
                          $searchFilters['field_6_min'] ?? 
                          $searchFilters['min_price'] ?? 
                          null,
                          
            'price_max' => $json['price_max'] ?? 
                          $searchFilters['field_6_max'] ?? 
                          $searchFilters['max_price'] ?? 
                          null,
            
            // Filters'ı JSON olarak sakla
            'search_filters' => is_array($searchFilters) ? json_encode($searchFilters) : $searchFilters,
            
            'results_count' => $json['results_count'] ?? 0,
            'is_saved' => 0,
            'notification_enabled' => 0,
        ];
        
        error_log('💾 Final searchData: ' . print_r($searchData, true));

        $searchId = $searchHistoryModel->recordSearch($searchData);
        error_log('💾 recordSearch result: ' . ($searchId ? $searchId : 'FALSE'));

        if ($searchId) {
            $response = [
                'success' => true,
                'message' => 'Arama başarıyla kaydedildi',
                'search_id' => $searchId
            ];
            error_log('📤 Response gönderiliyor: ' . json_encode($response));
            return $this->response->setJSON($response);
        }
        
        return $this->response->setJSON([
            'success' => false,
            'message' => 'Arama kaydedilemedi'
        ])->setStatusCode(500);

    } catch (\Exception $e) {
        error_log('💥 EXCEPTION: ' . $e->getMessage());
        error_log('Stack trace: ' . $e->getTraceAsString());
        
        return $this->response->setJSON([
            'success' => false,
            'message' => 'Sunucu hatası: ' . $e->getMessage()
        ])->setStatusCode(500);
    }
}

// ✅ Kayıtlı aramaları getirirken lokasyon ve kategori isimlerini ekle
public function getUserSearches()
{
    try {
        $token = $this->request->getGet('token');
        $type = $this->request->getGet('type') ?? 'all';

        if(empty($token)) {
            return $this->respond([
                'code' => 'error',
                'message' => 'Token required'
            ], 401);
        }

        $tokenModel = model('App\Models\TokenModel');
        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if(count($user_token) == 0) {
            return $this->respond([
                'code' => 'error',
                'message' => 'Invalid token'
            ], 401);
        }

        $user_id = $user_token[0]['user_id'];
        
        $db = \Config\Database::connect();
        
        // Aramaları getir
        $builder = $db->table('search_history sh');
        $builder->select('sh.*');
        $builder->where('sh.user_id', $user_id);
        
        if($type === 'saved') {
            $builder->where('sh.is_saved', 1);
        } elseif($type === 'recent') {
            $builder->where('sh.is_saved', 0);
        }
          $builder->where('sh.is_active', 1);
        $builder->orderBy('sh.created_at', 'DESC');
        $builder->limit(100);
        
        $searches = $builder->get()->getResultArray();
        
        error_log('📊 Found ' . count($searches) . ' searches for user ' . $user_id);
        
        if(empty($searches)) {
            return $this->respond([
                'code' => 'success',
                'data' => [],
                'count' => 0
            ]);
        }
        
        // ✅ Tüm benzersiz location ve category ID'leri topla
        $allLocationIds = [];
        $allCategoryIds = [];
        
        foreach($searches as $search) {
            if(!empty($search['search_location'])) {
                $ids = array_map('trim', explode(',', $search['search_location']));
                $allLocationIds = array_merge($allLocationIds, array_filter($ids, 'is_numeric'));
            }
            
            if(!empty($search['search_category'])) {
                $ids = array_map('trim', explode(',', $search['search_category']));
                $allCategoryIds = array_merge($allCategoryIds, array_filter($ids, 'is_numeric'));
            }
        }
        
        $allLocationIds = array_unique($allLocationIds);
        $allCategoryIds = array_unique($allCategoryIds);
        
        error_log('🔍 Unique location IDs: ' . implode(',', $allLocationIds));
        error_log('🔍 Unique category IDs: ' . implode(',', $allCategoryIds));
        
        // ✅ Tüm lokasyon isimlerini tek sorguda getir
        $locationNamesMap = [];
        if(!empty($allLocationIds)) {
            $locBuilder = $db->table('treefield t');
            $locBuilder->select('tl.treefield_id, tl.value');
            $locBuilder->join('treefield_lang tl', 't.id = tl.treefield_id');
            $locBuilder->where('tl.language_id', getenv('LANGUAGE_ID'));
            $locBuilder->where('t.field_id', 64);
            $locBuilder->whereIn('tl.treefield_id', $allLocationIds);
            
            $locResults = $locBuilder->get()->getResultArray();
            
            foreach($locResults as $loc) {
                $locationNamesMap[$loc['treefield_id']] = $loc['value'];
            }
            
            error_log('✅ Loaded ' . count($locationNamesMap) . ' location names');
        }
        
        // ✅ Tüm kategori isimlerini tek sorguda getir
        $categoryNamesMap = [];
        if(!empty($allCategoryIds)) {
            $catBuilder = $db->table('treefield t');
            $catBuilder->select('tl.treefield_id, tl.value');
            $catBuilder->join('treefield_lang tl', 't.id = tl.treefield_id');
            $catBuilder->where('tl.language_id', getenv('LANGUAGE_ID'));
            $catBuilder->where('t.field_id', 79);
            $catBuilder->whereIn('tl.treefield_id', $allCategoryIds);
            
            $catResults = $catBuilder->get()->getResultArray();
            
            foreach($catResults as $cat) {
                $categoryNamesMap[$cat['treefield_id']] = $cat['value'];
            }
            
            error_log('✅ Loaded ' . count($categoryNamesMap) . ' category names');
        }
        
        // ✅ Her aramaya isimleri ata
        foreach($searches as &$search) {
            // Parse search_filters
            if(!empty($search['search_filters']) && is_string($search['search_filters'])) {
                $filters = json_decode($search['search_filters'], true);
                $search['parsed_filters'] = $filters ?? [];
            } else {
                $search['parsed_filters'] = [];
            }
            
            // Lokasyon isimleri
            $locationNames = [];
            if(!empty($search['search_location'])) {
                $locationIds = array_map('trim', explode(',', $search['search_location']));
                foreach($locationIds as $locId) {
                    if(isset($locationNamesMap[$locId])) {
                        $locationNames[] = $locationNamesMap[$locId];
                    }
                }
            }
            $search['location_names'] = !empty($locationNames) ? implode(', ', $locationNames) : null;
            
            // Kategori isimleri
            $categoryNames = [];
            if(!empty($search['search_category'])) {
                $categoryIds = array_map('trim', explode(',', $search['search_category']));
                foreach($categoryIds as $catId) {
                    if(isset($categoryNamesMap[$catId])) {
                        $categoryNames[] = $categoryNamesMap[$catId];
                    }
                }
            }
            $search['category_name'] = !empty($categoryNames) ? implode(', ', $categoryNames) : null;
            
            error_log("🔍 Search #{$search['id']}: {$search['location_names']} | {$search['category_name']}");
        }

        return $this->respond([
            'code' => 'success',
            'data' => $searches,
            'count' => count($searches)
        ]);

    } catch(\Exception $e) {
        error_log('❌ getUserSearches error: ' . $e->getMessage());
        error_log('Stack trace: ' . $e->getTraceAsString());
        return $this->respond([
            'code' => 'error',
            'message' => 'Database error: ' . $e->getMessage()
        ], 500);
    }
}
/**
 * Kullanıcının arama geçmişi - DÜZELTİLDİ
 */
public function getUserSearchHistory()
{
    $tokenModel = model('App\Models\TokenModel');
    $searchModel = model('App\Models\SearchHistoryModel');
    
    // ✅ Token'ı GET veya POST'tan al
    $token = $_GET['token'] ?? null;
    
    if (!$token) {
        $data_json = $this->request->getJSON();
        $token = $data_json->token ?? null;
    }
    
    if(empty($token)) {
        return $this->respond([
            'code' => 'error',
            'message' => 'Token required'
        ], 401);
    }
    
    $user_token = $tokenModel->where('token', $token)->findAll(1);
    
    if(count($user_token) == 0) {
        return $this->respond([
            'code' => 'error',
            'message' => 'Invalid token'
        ], 401);
    }
    
    $user_id = $user_token[0]['user_id'];
    $limit = $_GET['limit'] ?? 20;
    
    try {
        $history = $searchModel->getUserActiveSearches($user_id, $limit);
        
        return $this->respond([
            'code' => 'success',
            'count' => count($history),
            'data' => $history
        ]);
        
    } catch(\Exception $e) {
        log_message('error', 'getUserSearchHistory error: ' . $e->getMessage());
        
        return $this->respond([
            'code' => 'error',
            'message' => 'Failed to get history',
            'error' => getenv('CI_ENVIRONMENT') == 'development' ? $e->getMessage() : null
        ], 500);
    }
}
}