<?php

namespace App\Models\Tenant;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class OnlineOrder extends Model
{
    use BelongsToTenant, SoftDeletes;

    public const STATUSES = [
        'new' => 'Nouă',
        'confirmed' => 'Confirmată',
        'packed' => 'Pregătită',
        'shipped' => 'Expediată',
        'delivered' => 'Livrată',
        'cancelled' => 'Anulată',
    ];

    public const DELIVERY = [
        'pickup' => 'Ridicare din service',
        'courier' => 'Curier',
        'post' => 'Poștă',
    ];

    protected $fillable = [
        'company_id', 'number', 'tracking_token', 'client_id', 'shop_customer_id',
        'customer_name', 'customer_phone', 'customer_email',
        'delivery_method', 'address', 'status',
        'subtotal', 'delivery_fee', 'total', 'notes',
    ];

    protected $casts = [
        'subtotal' => 'decimal:2',
        'delivery_fee' => 'decimal:2',
        'total' => 'decimal:2',
    ];

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

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

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

    public function trackingUrl(): string
    {
        return url('/shop/order/' . $this->tracking_token);
    }

    public function recalcTotal(): void
    {
        $this->subtotal = (float) $this->items()->sum('total');
        $this->total = round((float) $this->subtotal + (float) $this->delivery_fee, 2);
        $this->save();
    }

    public static function generateNumber(int $companyId): string
    {
        $year = date('y');
        $count = static::withoutGlobalScopes()
            ->where('company_id', $companyId)
            ->whereYear('created_at', date('Y'))
            ->count();
        return sprintf('SO-%s-%04d', $year, $count + 1);
    }

    protected static function booted(): void
    {
        static::creating(function (self $o) {
            if (empty($o->tracking_token)) {
                $o->tracking_token = Str::random(24);
            }
        });
    }
}
