<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class SearchAnalytics extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'query',
        'search_type',
        'filters',
        'results_count',
        'ip_address',
        'user_agent',
    ];

    protected $casts = [
        'filters' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * Get the user who performed the search
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Log a search query
     */
    public static function logSearch($userId, $query, $searchType, $filters, $resultsCount, $ipAddress = null, $userAgent = null)
    {
        return self::create([
            'user_id' => $userId,
            'query' => $query,
            'search_type' => $searchType,
            'filters' => $filters,
            'results_count' => $resultsCount,
            'ip_address' => $ipAddress,
            'user_agent' => $userAgent,
        ]);
    }

    /**
     * Get trending searches
     */
    public static function getTrendingSearches($limit = 10, $days = 7)
    {
        return self::select('query', DB::raw('COUNT(*) as search_count'))
            ->where('created_at', '>=', now()->subDays($days))
            ->groupBy('query')
            ->orderBy('search_count', 'desc')
            ->limit($limit)
            ->get()
            ->map(function ($item) {
                return [
                    'query' => $item->query,
                    'count' => $item->search_count,
                ];
            });
    }

    /**
     * Get popular searches by type
     */
    public static function getPopularSearchesByType($searchType, $limit = 10, $days = 7)
    {
        return self::select('query', DB::raw('COUNT(*) as search_count'))
            ->where('search_type', $searchType)
            ->where('created_at', '>=', now()->subDays($days))
            ->groupBy('query')
            ->orderBy('search_count', 'desc')
            ->limit($limit)
            ->get();
    }

    /**
     * Get search statistics
     */
    public static function getSearchStats($days = 30)
    {
        $totalSearches = self::where('created_at', '>=', now()->subDays($days))->count();
        
        $searchesByType = self::select('search_type', DB::raw('COUNT(*) as count'))
            ->where('created_at', '>=', now()->subDays($days))
            ->groupBy('search_type')
            ->get()
            ->pluck('count', 'search_type');

        $avgResultsCount = self::where('created_at', '>=', now()->subDays($days))
            ->avg('results_count');

        return [
            'total_searches' => $totalSearches,
            'searches_by_type' => $searchesByType,
            'average_results_count' => round($avgResultsCount, 2),
        ];
    }

    /**
     * Get user's search history
     */
    public static function getUserSearchHistory($userId, $limit = 20)
    {
        return self::where('user_id', $userId)
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get(['query', 'search_type', 'results_count', 'created_at']);
    }
} 