<?php

namespace Kylin\Catering\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Kylin\Catering\Enums\OrderStatus;
use Kylin\Catering\Enums\OrderType;
use Kylin\Catering\Enums\PaymentMethod;
use Kylin\Catering\Enums\PaymentStatus;

/**
 * 餐饮订单模型
 *
 * 餐饮系统订单，支持堂食/外卖/自取等多种订单类型，
 * 关联桌号、菜品明细、支付信息。
 *
 * @property int           $id
 * @property string        $order_no      订单号
 * @property OrderType     $order_type    订单类型
 * @property OrderStatus   $status        订单状态
 * @property PaymentStatus $payment_status 支付状态
 */
class Order extends Model
{
    protected $table = 'catering_orders';
    protected $fillable = [
        'order_no',
        'table_id',
        'user_id',
        'order_type',
        'status',
        'total_amount',
        'discount_amount',
        'actual_amount',
        'payment_method',
        'payment_status',
        'remark',
    ];

    protected $casts = [
        'table_id' => 'integer',
        'user_id' => 'integer',
        'order_type' => OrderType::class,
        'status' => OrderStatus::class,
        'total_amount' => 'decimal:2',
        'discount_amount' => 'decimal:2',
        'actual_amount' => 'decimal:2',
        'payment_method' => PaymentMethod::class,
        'payment_status' => PaymentStatus::class,
    ];

    public function table(): BelongsTo
    {
        return $this->belongsTo(Table::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class);
    }

    public function items(): HasMany
    {
        return $this->hasMany(OrderItem::class);
    }

    public function recalculateAmounts(): void
    {
        $this->total_amount = $this->items->sum(fn ($item) => $item->price * $item->quantity);
        $this->actual_amount = $this->total_amount - $this->discount_amount;
        $this->save();
    }
}
