<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class CashDrawer extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'opened_on', 'opening_balance', 'expected_balance', 'actual_balance',
        'difference', 'status', 'opened_by', 'opened_at', 'closed_by', 'closed_at', 'notes',
    ];

    protected $casts = [
        'opened_on' => 'date',
        'opening_balance' => 'decimal:2',
        'expected_balance' => 'decimal:2',
        'actual_balance' => 'decimal:2',
        'difference' => 'decimal:2',
        'opened_at' => 'datetime',
        'closed_at' => 'datetime',
    ];

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

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

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

    public function dailyClosing(): HasOne
    {
        return $this->hasOne(DailyClosing::class);
    }

    public function isOpen(): bool
    {
        return $this->status === 'open';
    }

    public static function currentOpen(): ?self
    {
        return static::query()->where('status', 'open')->latest('id')->first();
    }
}
