<?php

namespace App\Http\Controllers\Asset;

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

class EmployeeController extends Controller
{
    public function index(Request $request)
{
    $departments = \App\Models\EmpDep::where('is_active', 1)->orderBy('name')->get();

    $query = \App\Models\Employee::with('department');

    if ($request->filled('department')) {
        $query->where('emp_dep_id', $request->department);
    }

    if ($request->filled('search')) {
        $query->where('name', 'like', '%' . $request->search . '%');
    }

    $employees = $query->orderBy('name')->paginate(10)->appends($request->query());

    return view('asset.employees.index', compact('employees', 'departments'));
}


    public function store(Request $request)
    {
        $request->validate([
            'emp_dep_id' => 'nullable|exists:emp_deps,id',
            'name'       => 'required|string|max:100',
            'email'      => 'nullable|email',
            'phone'      => 'nullable|string|max:20',
            'designation'=> 'nullable|string|max:100',
            'location'   => 'nullable|string|max:100',
            'status'     => 'required|in:active,inactive',
        ]);

        Employee::create($request->all());
        return redirect()->back()->with('success','Employee added successfully.');
    }

    public function destroy($id)
    {
        Employee::findOrFail($id)->delete();
        return redirect()->back()->with('success','Employee deleted.');
    }

    public function toggle($id)
    {
        $emp = Employee::findOrFail($id);
        $emp->status = $emp->status === 'active' ? 'inactive' : 'active';
        $emp->save();
        return redirect()->back()->with('success','Status updated.');
    }

    public function edit($id)
{
    $employee = \App\Models\Employee::with('department')->findOrFail($id);
    $departments = \App\Models\EmpDep::where('is_active', 1)->orderBy('name')->get();
    return response()->json(['employee' => $employee, 'departments' => $departments]);
}

public function update(Request $request, $id)
{
    $employee = \App\Models\Employee::findOrFail($id);

    $request->validate([
        'emp_dep_id' => 'nullable|exists:emp_deps,id',
        'name'       => 'required|string|max:100',
        'email'      => 'nullable|email',
        'phone'      => 'nullable|string|max:20',
        'designation'=> 'nullable|string|max:100',
        'location'   => 'nullable|string|max:100',
        'status'     => 'required|in:active,inactive',
    ]);

    $employee->update($request->all());

    return redirect()->back()->with('success', 'Employee updated successfully.');
}

}
