<?php
// app/Models/Package.php

namespace App\Models;

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

class Package extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'slug',
        'description',
        'price',
        'discount_price',
        'duration_days',
        'is_featured',
        'is_active',
        'sort_order',
        'features'
    ];

    protected $casts = [
        'features' => 'array',
        'price' => 'decimal:2',
        'discount_price' => 'decimal:2',
        'is_featured' => 'boolean',
        'is_active' => 'boolean'
    ];

    public function services(): BelongsToMany
    {
        return $this->belongsToMany(Service::class, 'package_services')
                    ->withPivot('quantity')
                    ->withTimestamps();
    }

    // Accessor for final price after discount
    public function getFinalPriceAttribute()
    {
        return $this->discount_price ?? $this->price;
    }

    // Accessor for discount percentage
    public function getDiscountPercentageAttribute()
    {
        if ($this->discount_price && $this->price > 0) {
            return round((($this->price - $this->discount_price) / $this->price) * 100);
        }
        return 0;
    }

    // Check if package has discount
    public function getHasDiscountAttribute()
    {
        return !is_null($this->discount_price) && $this->discount_price < $this->price;
    }

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

    // Scope for featured packages
    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    // Scope for ordered packages
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order')->orderBy('created_at', 'desc');
    }
}