<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Schedule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class EmployeeController extends Controller
{
    public function index()
    {
        return view('admin.employee')->with([
            'employees'=> User::all(), 
            'schedules'=>Schedule::all()
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
            'position' => 'required|in:HRD,Staff,Manager'
        ]);

        $user = new User;
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = Hash::make($request->password);
        $user->role = $request->position;
        $user->save();

        if($request->schedule){
            $schedule = Schedule::whereSlug($request->schedule)->first();
            $user->schedules()->attach($schedule);
        }

        return redirect()->route('employees.index')
            ->with('success', 'Employee has been created successfully!');
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users,email,'.$id
        ]);

        $user = User::findOrFail($id);
        $user->name = $request->name;
        $user->email = $request->email;
        if($request->password) {
            $user->password = Hash::make($request->password);
        }
        $user->save();

        if ($request->schedule) {
            $user->schedules()->detach();
            $schedule = Schedule::whereSlug($request->schedule)->first();
            $user->schedules()->attach($schedule);
        }

        return redirect()->route('employees.index')
            ->with('success', 'Employee has been updated successfully!');
    }

    public function destroy($id)
    {
        $user = User::findOrFail($id);
        $user->schedules()->detach();
        $user->delete();
        
        return redirect()->route('employees.index')
            ->with('success', 'Employee has been deleted successfully!');
    }
}
