<?php
// app/Models/SearchStatisticsModel.php

namespace App\Models;

use CodeIgniter\Model;

class SearchStatisticsModel extends Model
{
    protected $table = 'search_statistics';
    protected $primaryKey = 'id';
    
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    
    protected $allowedFields = [
        'search_type',
        'search_value',
        'search_count',
        'last_searched',
        'created_at'
    ];
    
    protected $useTimestamps = false;
    
    /**
     * İstatistik sayacını artır
     */
    public function incrementCount($type, $value, $field)
    {
        try {
            $db = \Config\Database::connect();
            
            $sql = "INSERT INTO search_statistics (search_type, search_value, search_count, last_searched, created_at) 
                    VALUES (?, ?, 1, NOW(), NOW())
                    ON DUPLICATE KEY UPDATE 
                        search_count = search_count + 1,
                        last_searched = NOW()";
            
            $db->query($sql, [$type, $value]);
            
            return true;
            
        } catch(\Exception $e) {
            error_log('❌ incrementCount hatası: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * En popüler aramaları getir
     */
    public function getTopSearches($type, $limit = 10)
    {
        return $this->where('search_type', $type)
                    ->orderBy('search_count', 'DESC')
                    ->findAll($limit);
    }
    
    /**
     * Tüm istatistikleri getir
     */
    public function getAllStatistics()
    {
        return $this->orderBy('search_count', 'DESC')->findAll();
    }
}