<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Shift;
use Illuminate\Support\Facades\DB;

class ShiftController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:view-staff')->only(['index', 'show']);
        $this->middleware('permission:create-staff')->only(['create', 'store']);
        $this->middleware('permission:edit-staff')->only(['edit', 'update']);
        $this->middleware('permission:delete-staff')->only(['destroy']);
    }

    public function index()
    {
        $shifts = Shift::paginate(10);
        return view('backend.shifts.index', compact('shifts'));
    }

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

    public function store(Request $request)
    {
        $request->validate([
            'shift_name' => 'required|string|max:100|unique:shifts,shift_name',
        ]);

        DB::table('shifts')->insert([
            'shift_name' => $request->shift_name
        ]);

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

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

    public function update(Request $request, Shift $shift)
    {
        $request->validate([
            'shift_name' => 'required|string|max:100|unique:shifts,shift_name,' . $shift->shift_id . ',shift_id',
        ]);

        DB::table('shifts')
            ->where('shift_id', $shift->shift_id)
            ->update(['shift_name' => $request->shift_name]);

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

    public function destroy(Shift $shift)
    {
        // Check if shift is being used
        $staffCount = DB::table('staff')->where('shift_id', $shift->shift_id)->count();
        
        if ($staffCount > 0) {
            return back()->with('error', 'Cannot delete shift. It is being used by ' . $staffCount . ' staff member(s).');
        }

        DB::table('shifts')->where('shift_id', $shift->shift_id)->delete();
        
        return redirect()->route('shifts.index')->with('success', 'Shift deleted successfully!');
    }
} 