<?php

declare(strict_types=1);

namespace App\Models\Barangay;

use App\Models\Model;
use App\Enums\Barangay\DocumentStatus;
use App\Enums\Barangay\PaymentStatus;
use Hypervel\Database\Eloquent\SoftDeletes;

class DocumentRequest extends Model
{
    use SoftDeletes;

    protected ?string $table = 'barangay_document_requests';

    protected array $fillable = [
        'hashkey', 'request_no', 'resident_user_id', 'request_type_id',
        'purpose', 'fee_amount', 'payment_status', 'payment_method',
        'payment_ref', 'qrph_code', 'status',
        'requested_by', 'processed_by', 'claimed_at', 'notes',
    ];

    protected array $casts = [
        'fee_amount'     => 'decimal:2',
        'status'         => DocumentStatus::class,
        'payment_status' => PaymentStatus::class,
        'claimed_at'     => 'datetime',
    ];

    public function requestType()
    {
        return $this->belongsTo(RequestType::class, 'request_type_id');
    }

    public function resident()
    {
        return $this->belongsTo(\App\Models\User::class, 'resident_user_id');
    }

    public function processedBy()
    {
        return $this->belongsTo(\App\Models\User::class, 'processed_by');
    }

    public function requestedBy()
    {
        return $this->belongsTo(\App\Models\User::class, 'requested_by');
    }

    public function payments()
    {
        return $this->hasMany(RequestPayment::class, 'request_id');
    }

    public function latestPayment()
    {
        return $this->payments()->latest()->first();
    }

    public static function generateRequestNo(): string
    {
        $year = date('Y');
        $count = static::whereYear('created_at', $year)->count() + 1;
        return sprintf('REQ-%s-%05d', $year, $count);
    }

    public function scopePending($query)
    {
        return $query->whereIn('status', [DocumentStatus::DRAFT, DocumentStatus::PENDING_PAYMENT]);
    }

    public function scopeForProcessing($query)
    {
        return $query->where('status', DocumentStatus::PAID);
    }
}
