<?php

namespace Modules\Bms\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class BmsPackage extends Model
{
    protected $table = 'bms_packages';

    protected $fillable = [
        'business_id', 'venue_id', 'hall_id', 'name', 'name_ar', 'description', 'description_ar',
        'fnb_level', 'price', 'price_per_person', 'min_pax', 'max_pax',
        'is_active', 'sort_order',
    ];

    protected $casts = [
        'price'            => 'decimal:2',
        'price_per_person' => 'boolean',
        'min_pax'          => 'integer',
        'max_pax'          => 'integer',
        'is_active'        => 'boolean',
        'sort_order'       => 'integer',
    ];

    public function hall(): BelongsTo
    {
        return $this->belongsTo(BmsHall::class, 'hall_id');
    }

    public function venue(): BelongsTo
    {
        return $this->belongsTo(BmsVenue::class, 'venue_id');
    }

    public function items(): HasMany
    {
        return $this->hasMany(BmsPackageItem::class, 'package_id');
    }

    /**
     * Halls this package is offered in (1.8.1 — a package may span many halls).
     */
    public function halls(): BelongsToMany
    {
        return $this->belongsToMany(BmsHall::class, 'bms_package_hall', 'package_id', 'hall_id')->withTimestamps();
    }

    /**
     * Computed base cost of the package at a reference guest count: fixed items
     * cost qty×unit_cost; per-guest items scale with the guest count. Used for
     * margin visibility against the sale price (1.8.3).
     */
    public function computedCost(?int $guests = null): float
    {
        $guests = $guests ?: ($this->min_pax ?: 1);
        $total = 0.0;
        foreach ($this->items as $item) {
            if ($item->is_addon) {
                continue; // add-ons are optional extras, not part of the package cost
            }
            $qty = (float) $item->quantity;
            $effective = $item->qty_mode === 'per_guest' ? $qty * $guests : $qty;
            $total += $effective * (float) $item->unit_cost;
        }
        return round($total, 2);
    }
}
