<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use Illuminate\Http\Request;

class EmployeeController extends Controller
{
    public function index()
    {
        $employees = Employee::latest()->get();
        return view('admin.employees.index', compact('employees'));
    }

    public function create()
    {
        return view('admin.employees.form', ['employee' => new Employee]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'      => 'required|string|max:255',
            'email'     => 'required|email|unique:employees,email',
            'handle'    => 'nullable|string|max:100',
            'role'      => 'required|in:operator,senior_operator,manager',
            'is_active' => 'boolean',
            'notes'     => 'nullable|string',
        ]);
        $data['is_active'] = $request->boolean('is_active', true);
        Employee::create($data);
        return redirect()->route('admin.employees.index')->with('success', 'Employee created.');
    }

    public function edit(Employee $employee)
    {
        return view('admin.employees.form', compact('employee'));
    }

    public function update(Request $request, Employee $employee)
    {
        $data = $request->validate([
            'name'      => 'required|string|max:255',
            'email'     => 'required|email|unique:employees,email,' . $employee->id,
            'handle'    => 'nullable|string|max:100',
            'role'      => 'required|in:operator,senior_operator,manager',
            'is_active' => 'boolean',
            'notes'     => 'nullable|string',
        ]);
        $data['is_active'] = $request->boolean('is_active');
        $employee->update($data);
        return redirect()->route('admin.employees.index')->with('success', 'Employee updated.');
    }

    public function destroy(Employee $employee)
    {
        $employee->delete();
        return redirect()->route('admin.employees.index')->with('success', 'Employee removed.');
    }
}
