<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class Quote extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'prospect_email',
        'prospect_name',
        'number',
        'status',
        'items',
        'subtotal',
        'tax',
        'total',
        'currency',
        'notes',
        'valid_until',
        'accepted_at',
        'sent_at',
        'created_by',
    ];

    protected function casts(): array
    {
        return [
            'items' => 'array',
            'subtotal' => 'decimal:2',
            'tax' => 'decimal:2',
            'total' => 'decimal:2',
            'valid_until' => 'date',
            'accepted_at' => 'datetime',
            'sent_at' => 'datetime',
        ];
    }

    public static function generateNumber(): string
    {
        return 'QT-'.strtoupper(Str::random(6));
    }

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

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function isExpired(): bool
    {
        if (! $this->valid_until) {
            return false;
        }

        return $this->valid_until->isPast();
    }

    public function markAccepted(): void
    {
        $this->update([
            'status' => 'accepted',
            'accepted_at' => now(),
        ]);
    }

    public function markSent(): void
    {
        $this->update([
            'status' => 'sent',
            'sent_at' => now(),
        ]);
    }

    public function getRecipientEmail(): ?string
    {
        return $this->user?->email ?? $this->prospect_email;
    }

    public function getRecipientName(): ?string
    {
        return $this->user?->name ?? $this->prospect_name;
    }
}
