<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class PackagePricingTier extends Model
{
    protected $fillable = [
        'package_id',
        'validity_days',
        'ad_limit',
        'base_price',
        'discount_percentage',
        'final_price',
        'offer_label',
        'is_popular',
        'is_active',
    ];

    protected $casts = [
        'base_price' => 'decimal:2',
        'discount_percentage' => 'decimal:2',
        'final_price' => 'decimal:2',
        'is_popular' => 'boolean',
        'is_active' => 'boolean',
    ];

    // Relationships
    public function package()
    {
        return $this->belongsTo(AdPackage::class, 'package_id');
    }

    public function purchases()
    {
        return $this->hasMany(AdPackagePurchase::class, 'pricing_tier_id');
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopePopular($query)
    {
        return $query->where('is_popular', true);
    }

    public function scopeByValidity($query, $days)
    {
        return $query->where('validity_days', $days);
    }

    // Helper methods
    public function calculateFinalPrice()
    {
        if ($this->discount_percentage > 0) {
            return $this->base_price * (1 - ($this->discount_percentage / 100));
        }
        return $this->base_price;
    }

    public function getSavings()
    {
        return $this->base_price - $this->final_price;
    }

    public function getDiscountLabel()
    {
        if ($this->discount_percentage > 0) {
            return round($this->discount_percentage) . '% OFF';
        }
        return null;
    }

    // Automatically calculate final_price before saving
    protected static function boot()
    {
        parent::boot();

        static::saving(function ($tier) {
            if ($tier->isDirty(['base_price', 'discount_percentage'])) {
                $tier->final_price = $tier->calculateFinalPrice();
            }
        });
    }
}
