<?php

namespace App\Http\Controllers;

use App\Models\Employee;
use App\Models\Roster;
use Illuminate\Http\Request;

class RosterController extends Controller
{
    public function index()
    {
        $rosters = Roster::with('employee')->latest()->paginate(15);

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

    public function create()
    {
        $employees = Employee::active()->get();

        return view('rosters.create', compact('employees'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'employee_id'      => ['required', 'exists:employees,id'],
            'duty_start_date'  => ['nullable', 'date'],
            'duty_end_date'    => ['nullable', 'date', 'after_or_equal:duty_start_date'],
            'shift'            => ['required', 'in:morning,afternoon,night,custom'],
            'starts_at'        => ['nullable', 'date_format:H:i'],
            'ends_at'          => ['nullable', 'date_format:H:i'],
            'duty_title'       => ['nullable', 'string', 'max:255'],
            'notes'            => ['nullable', 'string'],
        ]);

        // duty_date is legacy; set from duty_start_date or today
        $data['duty_date'] = $data['duty_start_date'] ?? now()->toDateString();

        Roster::create($data);

        return redirect()->route('rosters.index')->with('success', __('Roster entry created successfully.'));
    }

    public function destroy(Roster $roster)
    {
        $roster->delete();

        return redirect()->route('rosters.index')->with('success', __('Roster removed successfully.'));
    }
}
