<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;

class SupplierPayment extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'payment_number',
        'purchase_id',
        'bank_account_id',
        'supplier_id',
        'payment_date',
        'reference_number',
        'total_amount',
        'paid_amount',
        'due_amount',
        'payment_source',
        'notes',
        'attachment',
        'created_by',
    ];

    protected function casts(): array
    {
        return [
            'payment_date' => 'date',
            'total_amount' => 'decimal:2',
            'paid_amount' => 'decimal:2',
            'due_amount' => 'decimal:2',
        ];
    }

    /**
     * Generate payment number
     */
    public static function generatePaymentNumber(): string
    {
        $lastPayment = static::withTrashed()
            ->where('payment_number', 'like', 'SPAY-%')
            ->orderBy('id', 'desc')
            ->first();

        if ($lastPayment) {
            $lastNumber = (int) substr($lastPayment->payment_number, 5);
            $nextNumber = $lastNumber + 1;
        } else {
            $nextNumber = 1;
        }

        return 'SPAY-'.str_pad($nextNumber, 6, '0', STR_PAD_LEFT);
    }

    /**
     * Get the purchase this payment belongs to
     */
    public function purchase(): BelongsTo
    {
        return $this->belongsTo(Purchase::class);
    }

    /**
     * Get the supplier this payment belongs to
     */
    public function supplier(): BelongsTo
    {
        return $this->belongsTo(Supplier::class);
    }

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

    /**
     * Get the attachment URL
     */
    public function getAttachmentUrlAttribute(): ?string
    {
        if (! $this->attachment) {
            return null;
        }

        if (filter_var($this->attachment, FILTER_VALIDATE_URL)) {
            return $this->attachment;
        }

        return Storage::disk('public')->exists($this->attachment)
            ? Storage::disk('public')->url($this->attachment)
            : null;
    }
}
