<?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 Estimate extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'estimate_number',
        'customer_id',
        'issue_date',
        'expiry_date',
        'status',
        'subtotal',
        'tax_amount',
        'discount_amount',
        'discount_type',
        'total',
        'currency',
        'notes',
        'terms',
        'created_by',
        'sent_at',
        'viewed_at',
        'accepted_at',
    ];

    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',
            'sent_at' => 'datetime',
            'viewed_at' => 'datetime',
            'accepted_at' => 'datetime',
        ];
    }

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

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

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

    /**
     * Check if estimate is expired
     */
    public function isExpired(): bool
    {
        return $this->expiry_date < now() && $this->status !== 'accepted';
    }

    /**
     * Accessor for quotation_number (compatibility with quotation views)
     */
    public function getQuotationNumberAttribute(): string
    {
        return $this->estimate_number;
    }

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