<?php

namespace App\Models;

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

class LedgerEntry extends Model
{
    use HasFactory;

    protected $fillable = [
        'reference_number',
        'type',
        'category',
        'amount',
        'direction',
        'balance_after',
        'description',
        'reference_type',
        'reference_id',
        'user_id',
        'supplier_id',
        'company_id',
    ];

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

    public function reference()
    {
        return $this->morphTo();
    }

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

    public function supplier()
    {
        return $this->belongsTo(Supplier::class);
    }

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public static function generateReferenceNumber(): string
    {
        $prefix = 'LE';
        $date = now()->format('Ymd');
        $lastEntry = self::whereDate('created_at', today())->latest()->first();
        $sequence = $lastEntry ? ((int) substr($lastEntry->reference_number, -4)) + 1 : 1;
        return $prefix . $date . str_pad($sequence, 4, '0', STR_PAD_LEFT);
    }

    public static function recordIncome(
        float $amount,
        string $category,
        string $description,
        Model $reference,
        ?int $userId = null,
        ?int $supplierId = null,
        ?int $companyId = null
    ): self {
        return self::create([
            'reference_number' => self::generateReferenceNumber(),
            'type' => 'income',
            'category' => $category,
            'amount' => $amount,
            'direction' => 'credit',
            'description' => $description,
            'reference_type' => get_class($reference),
            'reference_id' => $reference->id,
            'user_id' => $userId,
            'supplier_id' => $supplierId,
            'company_id' => $companyId,
        ]);
    }

    public static function recordExpense(
        float $amount,
        string $category,
        string $description,
        Model $reference,
        ?int $userId = null,
        ?int $supplierId = null,
        ?int $companyId = null
    ): self {
        return self::create([
            'reference_number' => self::generateReferenceNumber(),
            'type' => 'expense',
            'category' => $category,
            'amount' => $amount,
            'direction' => 'debit',
            'description' => $description,
            'reference_type' => get_class($reference),
            'reference_id' => $reference->id,
            'user_id' => $userId,
            'supplier_id' => $supplierId,
            'company_id' => $companyId,
        ]);
    }
}
