<?php

namespace App\Models;

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

class Quotation extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'quotation_number',
        'public_token',
        'customer_id',
        'issue_date',
        'expiry_date',
        'status',
        'subtotal',
        'tax_amount',
        'discount_amount',
        'discount_type',
        'total',
        'currency',
        'template',
        'exchange_rate',
        'notes',
        'terms',
        'reference_number',
        'sales_person',
        'created_by',
        'sent_at',
        'viewed_at',
        'converted_to_invoice_id',
    ];

    protected function casts(): array
    {
        return [
            'issue_date' => 'date',
            'expiry_date' => 'date',
            'subtotal' => 'decimal:2',
            'tax_amount' => 'decimal:2',
            'discount_amount' => 'decimal:2',
            'total' => 'decimal:2',
            'exchange_rate' => 'decimal:4',
            'sent_at' => 'datetime',
            'viewed_at' => 'datetime',
        ];
    }

    /**
     * Get the customer that owns the quotation
     */
    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class);
    }

    /**
     * Get the user who created the quotation
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get all items for this quotation
     */
    public function items(): HasMany
    {
        return $this->hasMany(QuotationItem::class)->orderBy('sort_order');
    }

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

    /**
     * Get the invoice this quotation was converted to
     */
    public function convertedInvoice(): BelongsTo
    {
        return $this->belongsTo(Invoice::class, 'converted_to_invoice_id');
    }

    /**
     * Check if quotation is expired
     */
    public function isExpired(): bool
    {
        return $this->expiry_date && $this->expiry_date < now();
    }

    /**
     * Check if quotation can be converted to invoice
     */
    public function canBeConverted(): bool
    {
        return $this->status !== 'converted' && ! $this->isExpired();
    }

    /**
     * Get or generate public token for quotation
     */
    public function getPublicToken(): string
    {
        if (empty($this->public_token)) {
            $this->public_token = \Illuminate\Support\Str::random(32);
            $this->save();
        }

        return $this->public_token;
    }

    /**
     * Get public quotation URL (same rules as admin share-link: optional INVOICE_PUBLIC_BASE_URL).
     */
    public function getPublicUrl(): string
    {
        $token = $this->getPublicToken();
        $publicBase = trim((string) config('invoice.public_base_url', ''));

        if ($publicBase !== '') {
            return rtrim($publicBase, '/').'/quotation/'.$token;
        }

        return route('quotation.public', ['token' => $token], absolute: true);
    }
}
