<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PackageAnalytics extends Model
{
    protected $table = 'package_analytics';

    protected $fillable = [
        'user_id',
        'package_id',
        'activated_at',
        'expires_at',
        'total_impressions',
        'total_views',
        'total_clicks',
        'roi_score',
        'status',
    ];

    protected $casts = [
        'activated_at' => 'datetime',
        'expires_at' => 'datetime',
        'roi_score' => 'decimal:2',
    ];

    /**
     * Get the user who owns this package analytics
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Scope to filter active packages
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active')
                    ->where('expires_at', '>', now());
    }

    /**
     * Scope to filter expired packages
     */
    public function scopeExpired($query)
    {
        return $query->where('status', 'expired')
                    ->orWhere('expires_at', '<=', now());
    }

    /**
     * Calculate and update ROI score based on performance
     */
    public function calculateROI(): float
    {
        $impressions = $this->total_impressions;
        $views = $this->total_views;
        $clicks = $this->total_clicks;

        // Simple ROI formula (can be enhanced)
        $ctr = $impressions > 0 ? ($clicks / $impressions) * 100 : 0;
        $viewRate = $impressions > 0 ? ($views / $impressions) * 100 : 0;
        
        $roi_score = min(10, ($ctr * 5) + ($viewRate * 0.5));
        
        $this->update(['roi_score' => $roi_score]);
        
        return $roi_score;
    }
}
