<?php

namespace App\Models;

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

class JournalEntry extends Model
{
    protected $fillable = [
        'entry_number',
        'date',
        'reference',
        'reference_type',
        'reference_id',
        'description',
        'partner_id',
        'branch_id',
        'created_by',
        'is_auto',
        'status',
    ];

    protected $casts = [
        'date' => 'date',
        'is_auto' => 'boolean',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($entry) {
            if (empty($entry->entry_number)) {
                $entry->entry_number = static::generateEntryNumber();
            }
        });
    }

    public static function generateEntryNumber(): string
    {
        $prefix = 'JE';
        $date = now()->format('Ymd');
        $count = static::whereDate('created_at', today())->count() + 1;
        
        return $prefix . $date . '-' . str_pad($count, 4, '0', STR_PAD_LEFT);
    }

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

    public function partner(): BelongsTo
    {
        return $this->belongsTo(Partner::class);
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

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

    public function reviewer(): BelongsTo
    {
        return $this->belongsTo(User::class, 'reviewed_by');
    }

    public function approvedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    public function lines(): HasMany
    {
        return $this->hasMany(JournalEntryLine::class);
    }

    public function auditLogs(): HasMany
    {
        return $this->hasMany(JournalAuditLog::class);
    }

    public function scopePosted($query)
    {
        return $query->where('status', 'posted');
    }

    public function scopeManual($query)
    {
        return $query->where('is_auto', false);
    }

    public function scopeAuto($query)
    {
        return $query->where('is_auto', true);
    }

    /**
     * Get total debits
     */
    public function getTotalDebitsAttribute(): float
    {
        return $this->lines->sum('debit');
    }

    /**
     * Get total credits
     */
    public function getTotalCreditsAttribute(): float
    {
        return $this->lines->sum('credit');
    }

    /**
     * Check if entry is balanced
     */
    public function isBalanced(): bool
    {
        return abs($this->total_debits - $this->total_credits) < 0.01;
    }

    /**
     * Get status badge color
     */
    public function getStatusColorAttribute(): string
    {
        return match ($this->status) {
            'draft' => 'secondary',
            'posted' => 'success',
            'void' => 'danger',
            default => 'secondary',
        };
    }
}
