<?php

namespace App\Models;

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

class HeroSlide extends Model
{
    use HasFactory;

    public const TYPES = ['promo', 'advertisement', 'announcement', 'sponsored'];

    protected $fillable = [
        'image_path',
        'slide_type',
        'badge_text',
        'title',
        'subtitle',
        'button_text',
        'button_link',
        'button2_text',
        'button2_link',
        'slide_link',
        'open_in_new_tab',
        'starts_at',
        'ends_at',
        'is_active',
        'sort_order',
        'impressions_count',
        'clicks_count',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'open_in_new_tab' => 'boolean',
        'starts_at' => 'datetime',
        'ends_at' => 'datetime',
        'impressions_count' => 'integer',
        'clicks_count' => 'integer',
    ];

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

    public function isAdType(): bool
    {
        return in_array($this->slide_type, ['advertisement', 'sponsored'], true);
    }

    public function imageUrl(): string
    {
        return \App\Support\MjsImages::url($this->image_path, $this->id ?? 0);
    }

    public function linkTarget(): string
    {
        return $this->open_in_new_tab ? '_blank' : '_self';
    }

    public function isScheduled(): bool
    {
        return $this->starts_at !== null || $this->ends_at !== null;
    }

    public function scheduleStatus(): string
    {
        if (!$this->is_active) {
            return 'hidden';
        }

        if ($this->starts_at && $this->starts_at->isFuture()) {
            return 'upcoming';
        }

        if ($this->ends_at && $this->ends_at->isPast()) {
            return 'expired';
        }

        return 'live';
    }
}
