<?php

namespace App\Models;

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

class PettyCashTransaction extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'transaction_number',
        'transaction_date',
        'type',
        'amount',
        'given_to',
        'description',
        'notes',
        'status',
        'returned_from_id',
        'returned_amount',
        'bank_account_id',
        'created_by',
        'approved_by',
        'approved_at',
    ];

    protected function casts(): array
    {
        return [
            'transaction_date' => 'date',
            'amount' => 'decimal:2',
            'returned_amount' => 'decimal:2',
            'approved_at' => 'datetime',
        ];
    }

    /**
     * Generate transaction number
     */
    public static function generateTransactionNumber(): string
    {
        $lastTransaction = static::withTrashed()
            ->where('transaction_number', 'like', 'PC-%')
            ->orderBy('id', 'desc')
            ->first();

        if ($lastTransaction) {
            $lastNumber = (int) substr($lastTransaction->transaction_number, 3);
            $nextNumber = $lastNumber + 1;
        } else {
            $nextNumber = 1;
        }

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

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

    /**
     * Get the user who approved this transaction
     */
    public function approver(): BelongsTo
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    /**
     * Get the original transaction this return is linked to
     */
    public function returnedFrom(): BelongsTo
    {
        return $this->belongsTo(PettyCashTransaction::class, 'returned_from_id');
    }

    /**
     * Get the bank account for top-ups
     */
    public function bankAccount(): BelongsTo
    {
        return $this->belongsTo(BankAccount::class);
    }

    /**
     * Get all returns for this transaction
     */
    public function returns()
    {
        return $this->hasMany(PettyCashTransaction::class, 'returned_from_id')->where('type', 'return');
    }
}
