<?php

namespace App\Services;

use App\Models\Order;
use App\Models\Shift;

class ShiftService
{
    public function close(Shift $shift, int $closingCash): Shift
    {
        $expectedCash = $this->expectedCash($shift);
        $variance = $closingCash - $expectedCash;

        $shift->update([
            'closing_cash' => $closingCash,
            'expected_cash' => $expectedCash,
            'variance' => $variance,
            'closed_at' => now(),
        ]);

        return $shift->fresh(['movements']);
    }

    public function expectedCash(Shift $shift): int
    {
        $cashSales = (int) Order::query()
            ->where('register_id', $shift->register_id)
            ->whereBetween('paid_at', [$shift->opened_at, $shift->closed_at ?? now()])
            ->where('status', 'PAID')
            ->whereHas('payments', fn ($q) => $q->where('method', 'CASH'))
            ->sum('total');

        $in = (int) $shift->movements()->where('type', 'IN')->sum('amount');
        $out = (int) $shift->movements()->where('type', 'OUT')->sum('amount');

        return (int) ($shift->opening_cash + $cashSales + $in - $out);
    }
}
