<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Advertisement extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'ad_type',
        'position',
        'image_path',
        'html_content',
        'target_url',
        'start_date',
        'end_date',
        'is_active',
        'display_order',
        'speed',
        'direction',
        'animation_type',
        'text_color',
        'view_count',
        'click_count',
        'size',
        'advertiser_name',
        'advertiser_contact',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'start_date' => 'datetime',
        'end_date' => 'datetime',
        'is_active' => 'boolean',
        'view_count' => 'integer',
        'click_count' => 'integer',
        'display_order' => 'integer',
        'speed' => 'integer',
    ];

    /**
     * Scope query to only include active advertisements.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActive($query)
    {
        $now = now();

        return $query->where('is_active', 1)
            ->where('start_date', '<=', $now)
            ->where(function ($q) use ($now) {
                $q->whereNull('end_date')
                    ->orWhere('end_date', '>=', $now);
            });
    }

    /**
     * Scope query to get ads by position.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  string  $position
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeByPosition($query, $position)
    {
        return $query->where('position', $position);
    }

    /**
     * Increment the view count for this advertisement.
     *
     * @return bool
     */
    public function incrementViews()
    {
        $this->view_count += 1;

        return $this->save();
    }

    /**
     * Increment the click count for this advertisement.
     *
     * @return bool
     */
    public function incrementClicks()
    {
        $this->click_count += 1;

        return $this->save();
    }

    /**
     * دریافت تبلیغات فعال برای یک موقعیت خاص
     */
    public static function getActiveForPosition($position, $limit = 5)
    {
        $cacheKey = "advertisements_{$position}_{$limit}";
        
        return Cache::remember($cacheKey, now()->addMinutes(30), function () use ($position, $limit) {
            return static::where('is_active', true)
                ->where('start_date', '<=', now())
                ->where(function ($query) {
                    $query->whereNull('end_date')
                        ->orWhere('end_date', '>=', now());
                })
                ->where('position', $position)
                ->orderBy('display_order')
                ->limit($limit)
                ->get();
        });
    }

    /**
     * پاک کردن کش تبلیغات
     */
    public static function clearCache()
    {
        $positions = ['homepage_hero', 'homepage_sidebar', 'homepage_featured', 
                     'homepage_middle', 'homepage_bottom', 'popup'];
        
        foreach ($positions as $position) {
            Cache::forget("advertisements_{$position}_5");
        }
    }

    /**
     * پاک کردن کش هنگام تغییر رکورد
     */
    protected static function booted()
    {
        static::saved(function ($advertisement) {
            static::clearCache();
        });

        static::deleted(function ($advertisement) {
            static::clearCache();
        });
    }
}
