<?php

namespace App\Models;

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

class Order extends Model
{
    protected $fillable = [
        'number', 'customer_name', 'customer_email', 'customer_phone',
        'customer_address', 'customer_postal_code', 'customer_city', 'customer_country',
        'shipping_method_id', 'shipping_cost', 'shipping_relay_id', 'shipping_relay_label',
        'subtotal', 'total', 'status', 'notes', 'items',
        'coupon_id', 'coupon_code', 'discount_amount',
        'stripe_payment_intent_id', 'stripe_payment_status',
    ];

    protected $casts = [
        'subtotal' => 'decimal:2',
        'total' => 'decimal:2',
        'shipping_cost' => 'decimal:2',
        'discount_amount' => 'decimal:2',
        'items' => 'array',
    ];

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

    public function shippingMethod(): BelongsTo
    {
        return $this->belongsTo(ShippingMethod::class, 'shipping_method_id');
    }

    public static function generateNumber(): string
    {
        $prefix = 'ORD-' . date('Ymd');
        $last = static::where('number', 'like', $prefix . '%')->orderByDesc('id')->first();
        $seq = $last ? (int) substr($last->number, -4) + 1 : 1;
        return $prefix . '-' . str_pad($seq, 4, '0', STR_PAD_LEFT);
    }
}
