<?php

namespace App\Models;

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

class LedgerTransaction extends Model
{
    use HasFactory;

    protected $fillable = [
        'reference',
        'user_id',
        'media_owner_id',
        'booking_id',
        'booking_item_id',
        'payment_id',
        'type',
        'direction',
        'currency',
        'amount',
        'balance_after',
        'description',
        'meta',
    ];

    protected $casts = [
        'amount'       => 'decimal:2',
        'balance_after'=> 'decimal:2',
        'meta'         => 'array',
    ];

    // ============================================================
    // Boot — auto generate reference
    // ============================================================
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($ledger) {
            if (empty($ledger->reference)) {
                $latest = static::latest('id')->first();
                $next   = $latest ? $latest->id + 1 : 1;
                $ledger->reference = 'LDG-' . str_pad($next, 6, '0', STR_PAD_LEFT);
            }
        });
    }

    // ============================================================
    // Scopes
    // ============================================================
    public function scopeCredits($query)
    {
        return $query->where('direction', 'credit');
    }

    public function scopeDebits($query)
    {
        return $query->where('direction', 'debit');
    }

    public function scopeForOwner($query, int $mediaOwnerId)
    {
        return $query->where('media_owner_id', $mediaOwnerId);
    }

    public function scopeForBooking($query, int $bookingId)
    {
        return $query->where('booking_id', $bookingId);
    }

    // ============================================================
    // Helpers
    // ============================================================
    public function isCredit(): bool
    {
        return $this->direction === 'credit';
    }

    public function isDebit(): bool
    {
        return $this->direction === 'debit';
    }

    public function getFormattedAmount(): string
    {
        $prefix = $this->isCredit() ? '+' : '-';
        return $prefix . $this->currency . ' ' . number_format($this->amount, 0);
    }

    public function getTypeLabel(): string
    {
        return match($this->type) {
            'payment_received' => 'Payment Received',
            'platform_fee'     => 'Platform Fee',
            'payout_released'  => 'Payout Released',
            'payout_held'      => 'Payout Held',
            'refund_issued'    => 'Refund Issued',
            'penalty_applied'  => 'Penalty Applied',
            'adjustment'       => 'Adjustment',
            default            => ucfirst($this->type),
        };
    }

    // ============================================================
    // Relationships
    // ============================================================
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function mediaOwner()
    {
        return $this->belongsTo(MediaOwner::class);
    }

    public function booking()
    {
        return $this->belongsTo(Booking::class);
    }

    public function bookingItem()
    {
        return $this->belongsTo(BookingItem::class);
    }

    public function payment()
    {
        return $this->belongsTo(Payment::class);
    }
}