<?php

namespace App\Repositories\Eloquent;

use App\Models\CashRegister;
use Illuminate\Database\Eloquent\Model;

class CashRegisterRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new CashRegister();
    }

    public function getForBranch(int $branchId, int $limit = 30)
    {
        return $this->model->where('branch_id', $branchId)
            ->with('user')
            ->orderBy('register_date', 'desc')
            ->limit($limit)
            ->get();
    }

    public function getOpenRegister(int $branchId): ?CashRegister
    {
        return $this->model->where('branch_id', $branchId)
            ->where('status', 'open')
            ->first();
    }

    public function findWithTransactions(int $id): ?CashRegister
    {
        return $this->model->with(['user', 'transactions'])->find($id);
    }

    public function findByDate(int $branchId, $date): ?CashRegister
    {
        return $this->model->where('branch_id', $branchId)
            ->whereDate('register_date', $date)
            ->first();
    }

    public function getOrCreateForDate(int $branchId, $date, int $userId, float $openingBalance): CashRegister
    {
        $existing = $this->findByDate($branchId, $date);

        if ($existing) {
            return $existing;
        }

        return $this->create([
            'branch_id' => $branchId,
            'user_id' => $userId,
            'opening_balance' => $openingBalance,
            'expected_balance' => $openingBalance,
            'status' => CashRegister::STATUS_OPEN,
            'register_date' => today(),
        ]);
    }
}
