<?php

namespace App\Models;

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

class MarketingCampaignAnalytic extends Model
{
    protected $fillable = [
        'campaign_id',
        'date',
        'impressions',
        'clicks',
        'conversions',
        'demographics',
    ];

    protected $casts = [
        'date' => 'date',
        'demographics' => 'array',
    ];

    /**
     * Campaign relationship
     */
    public function campaign(): BelongsTo
    {
        return $this->belongsTo(MarketingCampaign::class, 'campaign_id');
    }

    /**
     * Get CTR for this day
     */
    public function getCtrAttribute(): float
    {
        if ($this->impressions === 0) {
            return 0;
        }

        return round(($this->clicks / $this->impressions) * 100, 2);
    }

    /**
     * Get conversion rate
     */
    public function getConversionRateAttribute(): float
    {
        if ($this->clicks === 0) {
            return 0;
        }

        return round(($this->conversions / $this->clicks) * 100, 2);
    }

    /**
     * Get analytics for date range
     */
    public static function getForDateRange($campaignId, $startDate, $endDate)
    {
        return self::where('campaign_id', $campaignId)
            ->whereBetween('date', [$startDate, $endDate])
            ->orderBy('date')
            ->get();
    }

    /**
     * Get aggregated stats for campaign
     */
    public static function getAggregatedStats($campaignId)
    {
        $analytics = self::where('campaign_id', $campaignId)->get();

        return [
            'total_impressions' => $analytics->sum('impressions'),
            'total_clicks' => $analytics->sum('clicks'),
            'total_conversions' => $analytics->sum('conversions'),
            'average_ctr' => $analytics->avg('ctr'),
            'average_conversion_rate' => $analytics->avg('conversion_rate'),
        ];
    }
}
