<?php

namespace Modules\SystemCore\App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class CorePricingRule extends Model
{
    use SoftDeletes;

    protected $table = 'core_pricing_rules';

    protected $fillable = [
        'product_id',
        'customer_id',
        'min_quantity',
        'max_quantity',
        'price',
        'discount_percentage',
        'valid_from',
        'valid_until',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'min_quantity' => 'integer',
            'max_quantity' => 'integer',
            'price' => 'decimal:2',
            'discount_percentage' => 'decimal:2',
            'valid_from' => 'date',
            'valid_until' => 'date',
            'is_active' => 'boolean',
        ];
    }

    /**
     * Get product
     */
    public function product(): BelongsTo
    {
        return $this->belongsTo(CoreProduct::class, 'product_id');
    }

    /**
     * Get customer
     */
    public function customer(): BelongsTo
    {
        return $this->belongsTo(CoreCustomer::class, 'customer_id');
    }

    /**
     * Scope for active rules
     */
    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true)
            ->where(function ($q) {
                $q->whereNull('valid_from')
                    ->orWhere('valid_from', '<=', now());
            })
            ->where(function ($q) {
                $q->whereNull('valid_until')
                    ->orWhere('valid_until', '>=', now());
            });
    }
}
