<?php

namespace App\Models;

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

class Advertisement extends Model
{
    use HasFactory;

    protected $fillable = [
        'title_ar',
        'title_en',
        'image',
        'url',
        'status',
        'start_date',
        'end_date',
        'sort_order',
        'targeted_audience',
        'targeted_language',
    ];

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

    public function scopeActive($query)
    {
        return $query->where('status', 'active')
            ->where(function ($q) {
                $q->whereNull('start_date')
                    ->orWhere('start_date', '<=', now());
            })
            ->where(function ($q) {
                $q->whereNull('end_date')
                    ->orWhere('end_date', '>=', now());
            });
    }

    public function scopeFilterByAudience($query, $audience)
    {
        return $query->where('targeted_audience', $audience);
    }

    public function scopeFilterByLanguage($query, $language)
    {
        return $query->where('targeted_language', $language);
    }

    public function scopeSortBy($query, $field, $direction = 'asc')
    {
        $allowedFields = ['sort_order', 'start_date', 'end_date', 'created_at'];

        if (in_array($field, $allowedFields)) {
            return $query->orderBy($field, $direction);
        }

        return $query->orderBy('sort_order', 'asc');
    }
}
