<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class AnalyticsEvent extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'event_type',
        'event_data',
        'ip_address',
        'user_agent',
        'session_id',
        'referrer',
        'page_url',
        'country',
        'city',
        'device_type',
        'browser',
        'os',
    ];

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

    // Relationships
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // Scopes
    public function scopeByType($query, $eventType)
    {
        return $query->where('event_type', $eventType);
    }

    public function scopeByDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('created_at', [$startDate, $endDate]);
    }

    public function scopeByUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    public function scopeBySession($query, $sessionId)
    {
        return $query->where('session_id', $sessionId);
    }

    // Static methods for common events
    public static function trackEvent(string $eventType, array $eventData = [], ?int $userId = null, ?string $sessionId = null)
    {
        return self::create([
            'user_id' => $userId,
            'event_type' => $eventType,
            'event_data' => $eventData,
            'session_id' => $sessionId,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
            'page_url' => request()->fullUrl(),
            'referrer' => request()->header('referer'),
            'country' => request()->header('CF-IPCountry') ?? 'Unknown',
            'city' => request()->header('CF-IPCity') ?? 'Unknown',
            'device_type' => self::detectDeviceType(request()->userAgent()),
            'browser' => self::detectBrowser(request()->userAgent()),
            'os' => self::detectOS(request()->userAgent()),
        ]);
    }

    // Helper methods for device detection
    private static function detectDeviceType(?string $userAgent)
    {
        if (!$userAgent) return 'Unknown';
        
        $userAgent = strtolower($userAgent);
        
        if (preg_match('/mobile|android|iphone|ipad|phone/i', $userAgent)) {
            return 'Mobile';
        } elseif (preg_match('/tablet|ipad/i', $userAgent)) {
            return 'Tablet';
        } else {
            return 'Desktop';
        }
    }

    private static function detectBrowser(?string $userAgent)
    {
        if (!$userAgent) return 'Unknown';
        
        $userAgent = strtolower($userAgent);
        
        if (strpos($userAgent, 'chrome') !== false) return 'Chrome';
        if (strpos($userAgent, 'firefox') !== false) return 'Firefox';
        if (strpos($userAgent, 'safari') !== false) return 'Safari';
        if (strpos($userAgent, 'edge') !== false) return 'Edge';
        if (strpos($userAgent, 'opera') !== false) return 'Opera';
        
        return 'Other';
    }

    private static function detectOS(?string $userAgent)
    {
        if (!$userAgent) return 'Unknown';
        
        $userAgent = strtolower($userAgent);
        
        if (strpos($userAgent, 'windows') !== false) return 'Windows';
        if (strpos($userAgent, 'mac os') !== false) return 'macOS';
        if (strpos($userAgent, 'linux') !== false) return 'Linux';
        if (strpos($userAgent, 'android') !== false) return 'Android';
        if (strpos($userAgent, 'iphone') !== false || strpos($userAgent, 'ipad') !== false) return 'iOS';
        
        return 'Other';
    }
}
