<?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;

class CashRegister extends Model
{
    use HasFactory;

    protected $fillable = [
        'branch_id',
        'user_id',
        'register_date',
        'opening_balance',
        'cash_sales',
        'cash_expenses',
        'cash_in',
        'cash_out',
        'expected_balance',
        'actual_balance',
        'variance',
        'notes',
        'status',
        'closed_at',
    ];

    protected $casts = [
        'register_date' => 'date',
        'opening_balance' => 'decimal:2',
        'cash_sales' => 'decimal:2',
        'cash_expenses' => 'decimal:2',
        'cash_in' => 'decimal:2',
        'cash_out' => 'decimal:2',
        'expected_balance' => 'decimal:2',
        'actual_balance' => 'decimal:2',
        'variance' => 'decimal:2',
        'closed_at' => 'datetime',
    ];

    public const STATUS_OPEN = 'open';
    public const STATUS_CLOSED = 'closed';

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

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

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

    public function scopeForBranch($query, int $branchId)
    {
        return $query->where('branch_id', $branchId);
    }

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

    public function calculateExpectedBalance(): float
    {
        // Cash tray logic: opening balance + money in - money out
        // cash_sales = tendered amounts (money added to drawer)
        // cash_expenses = change given + expenses (money removed from drawer)
        return $this->opening_balance + $this->cash_sales - $this->cash_expenses;
    }

    public function updateExpectedBalance(): void
    {
        $this->update(['expected_balance' => $this->calculateExpectedBalance()]);
    }

    public function close(float $actualBalance, ?string $notes = null): void
    {
        $expectedBalance = $this->calculateExpectedBalance();

        $this->update([
            'expected_balance' => $expectedBalance,
            'actual_balance' => $actualBalance,
            'variance' => $actualBalance - $expectedBalance,
            'notes' => $notes,
            'status' => self::STATUS_CLOSED,
            'closed_at' => now(),
        ]);
    }
}
