<?php
// app/Models/Receipt.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Receipt extends Model
{
    use HasFactory;

    protected $fillable = [
        'branch_id',
        'receipt_number',
        'client_id',
        'receipt_date',
        'payment_method',
        'amount',
        'currency',
        'exchange_rate',
        'reference_type',
        'reference_id',
        'collected_by',
        'status',
        'notes',
        'reference_number'
    ];

    protected $casts = [
        'receipt_date' => 'datetime',
        'amount' => 'decimal:2',
        'exchange_rate' => 'decimal:4'
    ];

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

    public function client()
    {
        return $this->belongsTo(Client::class);
    }

    public function collector()
    {
        return $this->belongsTo(User::class, 'collected_by');
    }

    // Scopes
    public function scopeByBranch($query, $branchId)
    {
        return $query->where('branch_id', $branchId);
    }

    public function scopeByClient($query, $clientId)
    {
        return $query->where('client_id', $clientId);
    }

    public function scopeByDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('receipt_date', [$startDate, $endDate]);
    }

    // Methods
    public function getAmountInBaseCurrency()
    {
        return $this->amount * $this->exchange_rate;
    }

    public function getReference()
    {
        switch ($this->reference_type) {
            case 'loan_repayment':
                return $this->belongsTo(LoanRepayment::class, 'reference_id');
            case 'savings_deposit':
                return $this->belongsTo(SavingsTransaction::class, 'reference_id');
            case 'fee_payment':
                return $this->belongsTo(LoanPenalty::class, 'reference_id');
            default:
                return null;
        }
    }

    /**
     * Generate unique receipt number
     */
    public static function generateReceiptNumber()
    {
        do {
            $number = 'RCP-' . date('Y') . '-' . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
        } while (self::where('receipt_number', $number)->exists());

        return $number;
    }

    /**
     * Boot the model
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($receipt) {
            if (empty($receipt->receipt_number)) {
                $receipt->receipt_number = self::generateReceiptNumber();
            }
        });
    }
}
