<?php

namespace App\Domain\Financial\Models;

use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class CashSession extends Model
{
    use BelongsToAcademy, HasUuid, Auditable;

    protected $fillable = [
        'academy_id', 'branch_id', 'user_id',
        'opening_balance', 'closing_balance', 'expected_balance', 'variance',
        'total_cash_in', 'total_cash_out', 'transactions_count',
        'status', 'opened_at', 'closed_at',
        'opening_notes', 'closing_notes', 'closed_by',
        'denominations', 'metadata',
    ];

    protected $casts = [
        'opening_balance' => 'integer',
        'closing_balance' => 'integer',
        'expected_balance' => 'integer',
        'variance' => 'integer',
        'total_cash_in' => 'integer',
        'total_cash_out' => 'integer',
        'transactions_count' => 'integer',
        'opened_at' => 'datetime',
        'closed_at' => 'datetime',
        'denominations' => 'array',
        'metadata' => 'array',
    ];

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

    public function branch(): BelongsTo
    {
        return $this->belongsTo(\App\Domain\Identity\Models\Branch::class);
    }

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

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

    public function posTransactions(): HasMany
    {
        return $this->hasMany(\App\Domain\POS\Models\POSTransaction::class);
    }

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

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

    public function scopeForUser($query, int $userId)
    {
        return $query->where('user_id', $userId);
    }

    public function isFinancialAudit(): bool
    {
        return true;
    }
}
