<?php
// app/Models/SearchHistoryModel.php - GÜNCELLENMIŞ

namespace App\Models;

use CodeIgniter\Model;

class SearchHistoryModel extends Model
{
    protected $table = 'search_history';
    protected $primaryKey = 'id';
    
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false; // Manuel soft delete kullanacağız
    
    protected $allowedFields = [
        'user_id',
        'device_id',
        'search_query',
        'search_filters',
        'search_location',
        'search_category',
        'price_min',
        'price_max',
        'results_count',
        'is_active',
        'is_saved',
        'title',
        'notification_enabled',
        'created_at'
    ];
    
    protected $useTimestamps = false;
    protected $dateFormat = 'datetime';
    protected $createdField = 'created_at';
    
    /**
     * Arama kaydı oluştur
     */
  public function recordSearch($data)
{
    try {
        $searchData = [
            'user_id' => $data['user_id'] ?? null,
            'device_id' => $data['device_id'] ?? null,
            'search_query' => $data['search_query'] ?? null,
            'search_filters' => isset($data['search_filters']) ? json_encode($data['search_filters']) : null,
            'search_location' => $data['search_location'] ?? null,
            'search_category' => $data['search_category'] ?? null,
            'price_min' => $data['price_min'] ?? null,
            'price_max' => $data['price_max'] ?? null,
            'results_count' => $data['results_count'] ?? 0,
            'is_active' => 1,
            'is_saved' => $data['is_saved'] ?? 0,
            'title' => $data['title'] ?? null,
            'notification_enabled' => $data['notification_enabled'] ?? 0, // ✅ Default 0
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        $insert_id = $this->insert($searchData);
        
        // İstatistikleri güncelle
        $this->updateSearchStatistics($searchData);
        
        if(getenv('CI_ENVIRONMENT') == 'development') {
            log_message('info', '🔍 Arama kaydedildi - ID: ' . $insert_id);
            log_message('info', '   User ID: ' . ($searchData['user_id'] ?? 'null'));
            log_message('info', '   Search Query: ' . ($searchData['search_query'] ?? 'null'));
            log_message('info', '   Location: ' . ($searchData['search_location'] ?? 'null'));
            log_message('info', '   Category: ' . ($searchData['search_category'] ?? 'null'));
            log_message('info', '   Price: ' . ($searchData['price_min'] ?? '0') . ' - ' . ($searchData['price_max'] ?? 'max'));
        }
        
        return $insert_id;
        
    } catch(\Exception $e) {
        log_message('error', '❌ Arama kaydetme hatası: ' . $e->getMessage());
        return false;
    }
}
    
    /**
     * Kullanıcının aktif aramalarını getir
     */
    public function getUserActiveSearches($user_id, $limit = 50)
    {
        return $this->where('user_id', $user_id)
                    ->where('is_active', 1)
                    ->orderBy('created_at', 'DESC')
                    ->findAll($limit);
    }
    
    /**
     * Kullanıcının kayıtlı aramalarını getir
     */
    public function getUserSavedSearches($user_id, $limit = 50)
    {
        return $this->where('user_id', $user_id)
                    ->where('is_saved', 1)
                    ->where('is_active', 1)
                    ->orderBy('created_at', 'DESC')
                    ->findAll($limit);
    }
    
    /**
     * Aramayı kaydet (kullanıcı tarafından)
     */
    public function saveUserSearch($search_id, $title = null, $notification_enabled = 1)
    {
        try {
            $data = [
                'is_saved' => 1,
                'notification_enabled' => $notification_enabled
            ];
            
            if ($title) {
                $data['title'] = $title;
            }
            
            return $this->update($search_id, $data);
            
        } catch(\Exception $e) {
            log_message('error', '❌ Arama kaydetme hatası: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Aramayı soft delete (pasife al)
     */
    public function softDeleteSearch($search_id)
    {
        try {
            return $this->update($search_id, ['is_active' => 0]);
        } catch(\Exception $e) {
            log_message('error', '❌ Arama silme hatası: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Aramayı geri yükle
     */
    public function restoreSearch($search_id)
    {
        try {
            return $this->update($search_id, ['is_active' => 1]);
        } catch(\Exception $e) {
            log_message('error', '❌ Arama geri yükleme hatası: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Bildirimi aç/kapat
     */
    public function toggleNotification($search_id, $enabled)
    {
        try {
            return $this->update($search_id, ['notification_enabled' => $enabled ? 1 : 0]);
        } catch(\Exception $e) {
            log_message('error', '❌ Bildirim değiştirme hatası: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Bildirim için aktif aramaları getir
     */
    public function getNotificationEnabledSearches()
    {
        return $this->where('is_active', 1)
                    ->where('is_saved', 1)
                    ->where('notification_enabled', 1)
                    ->findAll();
    }
    
    /**
     * Aramayı güncelle
     */
    public function updateSearch($search_id, $data)
    {
        try {
            $updateData = [];
            
            if(isset($data['title'])) {
                $updateData['title'] = $data['title'];
            }
            
            if(isset($data['notification_enabled'])) {
                $updateData['notification_enabled'] = $data['notification_enabled'];
            }
            
            if(empty($updateData)) {
                return false;
            }
            
            return $this->update($search_id, $updateData);
            
        } catch(\Exception $e) {
            log_message('error', '❌ Arama güncelleme hatası: ' . $e->getMessage());
            return false;
        }
    }
    
  private function updateSearchStatistics($searchData)
{
    try {
         $statsModel = model('App\Models\SearchStatisticsModel');
        // Lokasyon istatistiği
        if (!empty($searchData['search_location'])) {
            // Birden fazla lokasyon olabilir (virgülle ayrılmış)
            $locations = explode(',', $searchData['search_location']);
            foreach ($locations as $locationId) {
                $locationId = trim($locationId);
                if (!empty($locationId)) {
                    $statsModel->incrementCount('location', $locationId, 'search_location');
                }
            }
        }
        
        // Kategori istatistiği
        if (!empty($searchData['search_category'])) {
            $statsModel->incrementCount('category', $searchData['search_category'], 'search_category');
        }
        
        // Fiyat aralığı istatistiği
        if (!empty($searchData['price_min']) || !empty($searchData['price_max'])) {
            $priceMin = $searchData['price_min'] ?? 0;
            $priceMax = $searchData['price_max'] ?? 999999999;
            
            $priceRange = $this->getPriceRangeLabel($priceMin, $priceMax);
            $statsModel->incrementCount('price_range', $priceRange, 'price_range');
        }
        
        // Arama sorgusu istatistiği
        if (!empty($searchData['search_query'])) {
            // Arama sorgusunu kelimelere ayır
            $keywords = explode(' ', strtolower(trim($searchData['search_query'])));
            foreach ($keywords as $keyword) {
                $keyword = trim($keyword);
                if (strlen($keyword) > 2) { // 2 karakterden uzun kelimeler
                    $statsModel->incrementCount('query', $keyword, 'search_query');
                }
            }
        }
        
        return true;
        
    } catch(\Exception $e) {
        log_message('error', '❌ İstatistik güncelleme hatası: ' . $e->getMessage());
        return false;
    }
}

private function getPriceRangeLabel($min, $max)
{
    if ($min == 0 && $max >= 999999999) {
        return 'Tüm Fiyatlar';
    } elseif ($min == 0) {
        return '0 - ' . number_format($max, 0, ',', '.') . ' TL';
    } elseif ($max >= 999999999) {
        return number_format($min, 0, ',', '.') . '+ TL';
    } else {
        return number_format($min, 0, ',', '.') . ' - ' . number_format($max, 0, ',', '.') . ' TL';
    }
}
    
    /**
     * İstatistik güncelleme
     */
 
    
    private function incrementSearchStat($type, $value)
    {
        $db = \Config\Database::connect();
        
        $sql = "INSERT INTO search_statistics (search_type, search_value, search_count, last_searched) 
                VALUES (?, ?, 1, NOW())
                ON DUPLICATE KEY UPDATE 
                    search_count = search_count + 1,
                    last_searched = NOW()";
        
        try {
            $db->query($sql, [$type, $value]);
        } catch(\Exception $e) {
            log_message('error', '❌ İstatistik güncelleme hatası: ' . $e->getMessage());
        }
    }
    
 
}