<?php

namespace App\Http\Controllers;

use App\Models\Shift;
use App\Models\Sale;
use Illuminate\Http\Request;
use Carbon\Carbon;

class ShiftController extends Controller
{
    public function check()
    {
        $activeShift = Shift::where('user_id', auth()->id())
            ->whereNull('end_time')
            ->first();

        if ($activeShift) {
            return redirect()->route('pos.index');
        }

        return view('transactions.pos.shift_open');
    }

    public function open(Request $request)
    {
        $request->validate([
            'starting_cash' => 'required|numeric|min:0'
        ]);

        Shift::create([
            'user_id' => auth()->id(),
            'start_time' => Carbon::now(),
            'starting_cash' => $request->starting_cash,
        ]);

        return redirect()->route('pos.index')->with('success', 'Shift berhasil dibuka. Selamat bertugas!');
    }

    public function close(Request $request)
    {
        $request->validate([
            'actual_ending_cash' => 'required|numeric|min:0'
        ]);

        $activeShift = Shift::where('user_id', auth()->id())
            ->whereNull('end_time')
            ->first();

        if ($activeShift) {
            // Calculate expected cash = starting cash + total cash sales during shift
            $cashSales = Sale::where('shift_id', $activeShift->id)
                ->sum('total_amount');
                
            $expectedCash = $activeShift->starting_cash + $cashSales;

            $activeShift->update([
                'end_time' => Carbon::now(),
                'total_sales' => $cashSales,
                'ending_cash' => $request->actual_ending_cash,
                'status' => 'closed',
            ]);
        }

        auth()->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        
        return redirect('/login')->with('success', 'Shift ditutup. Saldo akhir dicatat.');
    }
}
