<?php

namespace App\Models;

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

class PushCampaign extends Model
{
    use HasFactory;

    protected $fillable = [
        'key',
        'name',
        'payload_json',
        'schedule_json',
        'status',
        'sent_at',
        'target_count',
    ];

    protected $casts = [
        'payload_json' => 'array',
        'schedule_json' => 'array',
        'sent_at' => 'datetime',
        'target_count' => 'integer',
    ];

    public function pushLogs()
    {
        return $this->hasMany(PushLog::class);
    }

    public function getStatusColorAttribute(): string
    {
        return match ($this->status) {
            'draft' => 'gray',
            'scheduled' => 'yellow',
            'sending' => 'blue',
            'sent' => 'green',
            'failed' => 'red',
            default => 'gray'
        };
    }

    public function getStatusTextAttribute(): string
    {
        return match ($this->status) {
            'draft' => 'پیش‌نویس',
            'scheduled' => 'زمان‌بندی شده',
            'sending' => 'در حال ارسال',
            'sent' => 'ارسال شده',
            'failed' => 'ناموفق',
            default => $this->status
        };
    }

    public function getDeliveredCountAttribute(): int
    {
        return $this->pushLogs()->whereNotNull('delivered_at')->count();
    }

    public function getClickedCountAttribute(): int
    {
        return $this->pushLogs()->whereNotNull('clicked_cta_at')->count();
    }

    public function getCtrAttribute(): float
    {
        $delivered = $this->delivered_count;
        return $delivered > 0 ? round(($this->clicked_count / $delivered) * 100, 1) : 0.0;
    }
}
