<?php

namespace App\Models;

use App\Models\Scopes\BranchScope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class CashReconciliation extends Model
{
    public const STATUSES = ['active', 'superseded'];

    protected $fillable = [
        'reconciliation_number', 'business_id', 'branch_id', 'financial_account_id', 'reconciliation_date',
        'version', 'status', 'opening_cash', 'cash_in', 'cash_out', 'expected_cash', 'physical_cash',
        'variance', 'variance_explanation', 'reconciled_by', 'reconciled_at', 'superseded_by_id', 'superseded_at',
    ];

    protected function casts(): array
    {
        return [
            'reconciliation_date' => 'date',
            'version' => 'integer',
            'opening_cash' => 'decimal:2',
            'cash_in' => 'decimal:2',
            'cash_out' => 'decimal:2',
            'expected_cash' => 'decimal:2',
            'physical_cash' => 'decimal:2',
            'variance' => 'decimal:2',
            'reconciled_at' => 'datetime',
            'superseded_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::addGlobalScope(new BranchScope());
    }

    public function business(): BelongsTo { return $this->belongsTo(Business::class); }
    public function branch(): BelongsTo { return $this->belongsTo(Branch::class); }
    public function financialAccount(): BelongsTo { return $this->belongsTo(FinancialAccount::class); }
    public function reconciler(): BelongsTo { return $this->belongsTo(User::class, 'reconciled_by'); }
    public function supersededBy(): BelongsTo { return $this->belongsTo(self::class, 'superseded_by_id'); }
}
