<?php

namespace App\Models;

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

class Receipt extends Model
{
    protected $fillable = [
        'receipt_number',
        'public_token',
        'template',
        'invoice_id',
        'customer_id',
        'amount',
        'payment_method',
        'transaction_reference',
        'notes',
        'created_by',
    ];

    protected function casts(): array
    {
        return [
            'amount' => 'decimal:2',
        ];
    }

    /**
     * Get the invoice that this receipt belongs to
     */
    public function invoice(): BelongsTo
    {
        return $this->belongsTo(Invoice::class);
    }

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

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

    /**
     * Public share URL (requires public_token).
     */
    public function getPublicUrl(): ?string
    {
        if (empty($this->public_token)) {
            return null;
        }

        $publicBase = trim((string) config('invoice.public_base_url', ''));

        return $publicBase !== ''
            ? rtrim($publicBase, '/').'/receipt/'.$this->public_token
            : route('receipt.public', ['token' => $this->public_token], absolute: true);
    }
}
