<?php

namespace App\Models;

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

class OwnerPayment extends Model
{
    protected $fillable = [
        'owner_id', 'voucher_number', 'payment_date', 'total_amount',
        'payment_method', 'proof_file', 'owner_signature_taken', 'remarks',
    ];

    protected $casts = [
        'total_amount' => 'decimal:2',
        'payment_date' => 'date',
        'owner_signature_taken' => 'boolean',
    ];

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

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

    // Generate next voucher number
    public static function generateVoucherNumber(): string
    {
        $prefix = Setting::get('voucher_prefix', 'OV');
        $year = date('Y');
        $last = static::where('voucher_number', 'like', "{$prefix}-{$year}-%")
            ->orderByDesc('voucher_number')
            ->first();

        if ($last) {
            $lastNumber = (int) substr($last->voucher_number, -4);
            $nextNumber = $lastNumber + 1;
        } else {
            $nextNumber = 1;
        }

        return sprintf('%s-%s-%04d', $prefix, $year, $nextNumber);
    }
}
