<?php

namespace App\Models\Rental;

use App\Models\Customer;
use App\Models\User;
use App\Models\Branch;
use App\Traits\BranchScoped;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PaymentVoucher extends Model
{
    use BranchScoped;

    protected $fillable = [
        'branch_id',
        'voucher_number',
        'voucher_date',
        'invoice_id',
        'rental_id',
        'customer_id',
        'amount_paid',
        'payment_method', // cash, check, transfer, card, etc.
        'reference_number',
        'check_number',
        'check_date',
        'bank_name',
        'notes',
        'received_by',
        'status', // confirmed, verified, cancelled
        'qr_code_data',
    ];

    protected $casts = [
        'voucher_date' => 'datetime',
        'check_date' => 'datetime',
        'amount_paid' => 'decimal:2',
    ];

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

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

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

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

    public function receiver(): BelongsTo
    {
        return $this->belongsTo(User::class, 'received_by');
    }

    public function creator(): BelongsTo
    {
        return $this->receiver();
    }

    public function getAmountAttribute()
    {
        return $this->amount_paid;
    }

    public function getReasonAttribute()
    {
        return $this->notes;
    }

    public function generateVoucherNumber()
    {
        $prefix = 'PV';
        $year = date('Y');
        $month = date('m');
        $count = static::whereYear('created_at', now()->year)
            ->whereMonth('created_at', now()->month)
            ->count() + 1;

        return sprintf('%s-%s-%s-%05d', $prefix, $year, $month, $count);
    }

    public function generateQRCodeData()
    {
        return json_encode([
            'voucher_number' => $this->voucher_number,
            'amount' => $this->amount_paid,
            'date' => $this->voucher_date->format('Y-m-d'),
            'payment_method' => $this->payment_method,
        ]);
    }
}
