<?php

namespace App\Models;

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

class JournalEntry extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'entry_date',
        'voucher_no',
        'reference_no',
        'narration',
        'total_debit',
        'total_credit',
        'status',
        'created_by',
        'posted_by',
        'posted_at'
    ];

    protected $casts = [
        'entry_date' => 'date',
        'total_debit' => 'decimal:2',
        'total_credit' => 'decimal:2',
        'posted_at' => 'datetime'
    ];

    // সম্পর্ক
    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function postedBy()
    {
        return $this->belongsTo(User::class, 'posted_by');
    }

    public function items()
    {
        return $this->hasMany(JournalEntryItem::class);
    }

    // স্কোপস
    public function scopePosted($query)
    {
        return $query->where('status', 'posted');
    }

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

    public function scopeDateRange($query, $fromDate, $toDate)
    {
        return $query->whereBetween('entry_date', [$fromDate, $toDate]);
    }

    // হেল্পার মেথডস
    public function isPosted()
    {
        return $this->status === 'posted';
    }

    public function isBalanced()
    {
        return $this->total_debit == $this->total_credit;
    }

    public function getStatusBadgeAttribute()
    {
        $statuses = [
            'draft' => 'secondary',
            'posted' => 'success',
            'cancelled' => 'danger'
        ];

        $colors = $statuses[$this->status] ?? 'secondary';
        $labels = [
            'draft' => 'খসড়া',
            'posted' => 'পোস্ট হয়েছে',
            'cancelled' => 'বাতিল'
        ];

        return '<span class="badge bg-' . $colors . '">' . ($labels[$this->status] ?? $this->status) . '</span>';
    }
}