<?php

namespace App\Models;

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

class Receipt extends Model
{
    use HasFactory;

    protected $primaryKey = 'receipt_id';

    protected $fillable = [
        'booking_id',
        'receipt_number',
        'total_amount',
        'advance_payment',
        'due_amount',
        'payment_method',
        'card_type',
        'transaction_id',
        'notes',
        'status',
        'issued_at',
    ];

    protected $casts = [
        'total_amount' => 'decimal:2',
        'advance_payment' => 'decimal:2',
        'due_amount' => 'decimal:2',
        'issued_at' => 'datetime',
    ];

    /**
     * Get the booking for this receipt.
     */
    public function booking()
    {
        return $this->belongsTo(Booking::class, 'booking_id');
    }

    /**
     * Generate a unique receipt number.
     */
    public static function generateReceiptNumber()
    {
        $prefix = 'RCP';
        $year = date('Y');
        $month = date('m');
        
        // Get the last receipt number for this month
        $lastReceipt = self::where('receipt_number', 'like', $prefix . $year . $month . '%')
            ->orderBy('receipt_number', 'desc')
            ->first();
        
        if ($lastReceipt) {
            $lastNumber = (int) substr($lastReceipt->receipt_number, -4);
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }
        
        return $prefix . $year . $month . str_pad($newNumber, 4, '0', STR_PAD_LEFT);
    }

    /**
     * Get status badge color.
     */
    public function getStatusBadgeColor()
    {
        return match($this->status) {
            'Paid' => 'bg-green-100 text-green-800',
            'Partial' => 'bg-yellow-100 text-yellow-800',
            'Pending' => 'bg-red-100 text-red-800',
            default => 'bg-gray-100 text-gray-800',
        };
    }
}
