<?php

namespace App\Models;

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

class PromotionPackage extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'price',
        'price_usd',
        'duration_days',
        'page_position',
        'max_products',
        'priority_level',
        'badge_text',
        'badge_color',
        'is_active',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'price_usd' => 'decimal:2',
        'is_active' => 'boolean',
    ];

    /**
     * Get promotions using this package
     */
    public function promotions()
    {
        return $this->hasMany(ProductPromotion::class, 'package_id');
    }

    /**
     * Scope to get only active packages
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope to filter by page position
     */
    public function scopeForPage($query, int $page)
    {
        return $query->where('page_position', $page);
    }

    /**
     * Check if package is active
     */
    public function isActive(): bool
    {
        return $this->is_active;
    }

    /**
     * Get remaining slots for this package (based on max concurrent promotions)
     */
    public function getRemainingSlots(): int
    {
        $maxSlots = PromotionSetting::get('page' . $this->page_position . '_max_slots', 5);
        $currentActive = ProductPromotion::where('status', 'active')
            ->whereHas('package', function($q) {
                $q->where('page_position', $this->page_position);
            })
            ->count();

        return max(0, $maxSlots - $currentActive);
    }
}
