<?php

namespace App\Http\Controllers;

use App\Http\Requests\CashMovementRequest;
use App\Http\Requests\CloseShiftRequest;
use App\Http\Requests\OpenShiftRequest;
use App\Models\Shift;
use App\Services\ShiftService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class ShiftController extends Controller
{
    public function index(ShiftService $service): View
    {
        $user = auth()->user();
        $shifts = Shift::query()
            ->with(['register', 'movements'])
            ->where('outlet_id', $user->outlet_id)
            ->latest()
            ->paginate(20);

        foreach ($shifts as $shift) {
            if (! $shift->closed_at) {
                $shift->expected_cash = $service->expectedCash($shift);
            }
        }

        return view('shifts.index', compact('shifts'));
    }

    public function open(OpenShiftRequest $request): RedirectResponse
    {
        $user = $request->user();
        Shift::query()->create([
            'outlet_id' => $user->outlet_id,
            'register_id' => $request->validated()['register_id'],
            'user_id' => $user->id,
            'opened_at' => now(),
            'opening_cash' => $request->validated()['opening_cash'],
        ]);

        return back()->with('success', 'Shift dibuka.');
    }

    public function move(CashMovementRequest $request): RedirectResponse
    {
        $shift = Shift::query()->findOrFail($request->validated()['shift_id']);
        abort_if($shift->closed_at, 422, 'Shift sudah ditutup.');

        $shift->movements()->create([
            'type' => $request->validated()['type'],
            'amount' => $request->validated()['amount'],
            'note' => $request->validated()['note'] ?? null,
            'created_by' => $request->user()->id,
        ]);

        return back()->with('success', 'Cash movement disimpan.');
    }

    public function close(CloseShiftRequest $request, Shift $shift, ShiftService $service): RedirectResponse
    {
        abort_if($shift->closed_at, 422, 'Shift sudah ditutup.');
        $service->close($shift, $request->validated()['closing_cash']);

        return back()->with('success', 'Shift ditutup.');
    }
}
