<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Advertisement extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'title', 'title_ar', 'description', 'image', 'media_type', 'video_path',
        'link_url', 'link_text',
        'position', 'target', 'display_mode', 'starts_at', 'ends_at',
        'impressions', 'clicks', 'is_active', 'sort_order',
    ];

    protected $casts = [
        'starts_at' => 'datetime',
        'ends_at'   => 'datetime',
        'is_active' => 'boolean',
    ];

    public function scopeActive($q)
    {
        return $q->where('is_active', true)
            ->where(fn($q) => $q->whereNull('starts_at')->orWhere('starts_at', '<=', now()))
            ->where(fn($q) => $q->whereNull('ends_at')->orWhere('ends_at', '>=', now()));
    }

    public function scopeForPosition($q, string $position)
    {
        return $q->where('position', $position);
    }

    /** سلايدر الرئيسية للمريض (أعلى الصفحة). */
    public function scopePatientHomeSlider($q)
    {
        return $q->where('display_mode', 'slider')
            ->where('position', 'home_top')
            ->where(fn ($q) => $q->where('target', 'all')->orWhere('target', 'patients'));
    }

    public function isVideo(): bool
    {
        return $this->media_type === 'video' && $this->video_path;
    }

    public function getCtrAttribute(): float
    {
        return $this->impressions > 0
            ? round(($this->clicks / $this->impressions) * 100, 2)
            : 0;
    }
}
