<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Campagna extends Model
{
    use LogsActivity;

    protected $table = 'campagne';

    protected $fillable = ['start_date', 'end_date', 'descrizione'];

    protected function casts(): array
    {
        return [
            'start_date' => 'date',
            'end_date' => 'date',
        ];
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['start_date', 'end_date', 'descrizione'])
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }

    /**
     * Is this campaign currently active?
     */
    public function getIsAttivaAttribute(): bool
    {
        $today = now()->toDateString();
        return $this->start_date->toDateString() <= $today
            && $this->end_date->toDateString() >= $today;
    }

    /**
     * Find the currently active campaign (if any).
     */
    public static function attiva(): ?static
    {
        return static::where('start_date', '<=', now())
            ->where('end_date', '>=', now())
            ->first();
    }

    /**
     * Assignments counted for this campaign.
     */
    public function assegnazioniConteggiate()
    {
        return $this->hasMany(Assegnazione::class, 'campaign_id')
            ->where('counted_in_campaign', true);
    }

    /**
     * All assignments with assigned_at in this campaign's range.
     */
    public function assegnazioniNelRange()
    {
        return Assegnazione::where('assigned_at', '>=', $this->start_date)
            ->where('assigned_at', '<=', $this->end_date);
    }

    /**
     * Campaign coverage percentage.
     * Numerator: assignments counted for campaign
     * Denominator: ALL assignments with assigned_at in campaign range (returned or not)
     */
    public function getPercentualePercorrenzaAttribute(): float
    {
        $totaleNelRange = $this->assegnazioniNelRange()->count();

        if ($totaleNelRange === 0) {
            return 0.0;
        }

        $conteggiate = $this->assegnazioniConteggiate()->count();

        return round(($conteggiate / $totaleNelRange) * 100, 1);
    }

    public function scopeCompletate($query)
    {
        return $query->where('end_date', '<', now())->orderByDesc('end_date');
    }
}
