<?php

namespace App\Http\Controllers;

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

class ShiftController extends Controller
{
    public function index()
    {
        $shifts = Shift::latest()->paginate(10);
        return view('attendance.shifts.index', compact('shifts'));
    }

    public function create()
    {
        return view('attendance.shifts.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:normal,flexible',
            'start_time' => 'required_if:type,normal',
            'end_time' => 'required_if:type,normal',
            'flexible_hours' => 'required_if:type,flexible|nullable|integer|min:1',
            'grace_period' => 'required|integer|min:0',
            'overtime_allowed' => 'nullable|boolean',
            'overtime_rate' => 'nullable|numeric|min:1',
            'min_overtime_minutes' => 'nullable|integer|min:0',
            'max_overtime_minutes' => 'nullable|integer|min:0',
        ]);

        Shift::create($request->all() + [
            'is_night_shift' => $request->has('is_night_shift'),
            'overtime_allowed' => $request->has('overtime_allowed'),
        ]);

        return redirect()->route('shifts.index')->with('success', 'Shift created successfully.');
    }

    public function edit(Shift $shift)
    {
        return view('attendance.shifts.edit', compact('shift'));
    }

    public function update(Request $request, Shift $shift)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:normal,flexible',
            'start_time' => 'required_if:type,normal',
            'end_time' => 'required_if:type,normal',
            'flexible_hours' => 'required_if:type,flexible|nullable|integer|min:1',
            'grace_period' => 'required|integer|min:0',
            'overtime_allowed' => 'nullable|boolean',
            'overtime_rate' => 'nullable|numeric|min:1',
            'min_overtime_minutes' => 'nullable|integer|min:0',
            'max_overtime_minutes' => 'nullable|integer|min:0',
        ]);

        $shift->update($request->all() + [
            'is_night_shift' => $request->has('is_night_shift'),
            'overtime_allowed' => $request->has('overtime_allowed'),
        ]);

        return redirect()->route('shifts.index')->with('success', 'Shift updated successfully.');
    }

    public function destroy(Shift $shift)
    {
        $shift->delete();
        return redirect()->route('shifts.index')->with('success', 'Shift deleted successfully.');
    }
}
