<?php

namespace App\Models\Z_Website\Market;

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

class MarketPackage extends Model
{
    use HasFactory;

    protected $table = 'market_packages';

    protected $fillable = [
        'package_name',
        'description',
        'balance_type',
        'price',
        'stock',
        'image',
        'expiry_date',
        'sort_order',
        'sort_type',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'stock' => 'integer',
        'sort_order' => 'integer',
        'expiry_date' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    // Balance type validation
    const BALANCE_TYPES = [
        'balance',
        'gift_balance',
        'silk',
        'donate'
    ];

    // Scope for filtering by balance type
    public function scopeByBalanceType($query, $balanceType)
    {
        return $query->where('balance_type', $balanceType);
    }

    // Scope for available packages (in stock and not expired)
    public function scopeAvailable($query)
    {
        return $query->where(function ($query) {
            $query->where('stock', '>', 0)->orWhere('stock', -1); // In stock or unlimited
        })->where(function ($query) {
            $query->whereNull('expiry_date')->orWhere('expiry_date', '>', now());
        });
    }

    // Scope for expiring soon packages
    public function scopeExpiringSoon($query, $days = 7)
    {
        return $query->whereNotNull('expiry_date')
                    ->where('expiry_date', '>', now())
                    ->where('expiry_date', '<=', now()->addDays($days));
    }

    // Check if package is in stock
    public function isInStock()
    {
        return $this->stock === -1 || $this->stock > 0;
    }

    // Check if package is expired
    public function isExpired()
    {
        return $this->expiry_date && $this->expiry_date->isPast();
    }

    // Check if package is expiring soon
    public function isExpiringSoon($days = 7)
    {
        if (!$this->expiry_date) {
            return false;
        }

        return $this->expiry_date->isAfter(now()) &&
               $this->expiry_date->isBefore(now()->addDays($days));
    }

    // Get formatted price with currency symbol
    public function getFormattedPrice()
    {
        $symbols = [
            'balance' => '💎',
            'gift_balance' => '💖',
            'silk' => '⭐',
            'donate' => '💎'
        ];

        $symbol = $symbols[$this->balance_type] ?? '💎';
        return $symbol . ' ' . number_format($this->price, 2);
    }

    //Get Items From MarketItem by send package_id
    public static function getItems($packageId)
    {
        return MarketItem::where('package_id', $packageId)->get();
    }


}
