|
4 | 4 |
|
5 | 5 | use App\Common\Helpers; |
6 | 6 | use App\Http\Controllers\Controller; |
| 7 | +use App\Http\Requests\Employee\EmployeeRequest; |
7 | 8 | use App\Models\EmployeeInfo; |
8 | 9 | use Auth; |
9 | 10 | use DB; |
| 11 | +use Exception; |
10 | 12 | use Illuminate\Http\Request; |
11 | 13 | use Inertia\Inertia; |
12 | 14 | use Log; |
| 15 | +use Mail; |
| 16 | +use Str; |
13 | 17 |
|
14 | 18 | class EmployeeInfoController extends Controller |
15 | 19 | { |
@@ -89,10 +93,53 @@ public function index(Request $request) |
89 | 93 | return Inertia::render('employees/Index', ['employees' => $employees]); |
90 | 94 | } |
91 | 95 |
|
| 96 | + /** |
| 97 | + * Show the form for creating a new employee info. |
| 98 | + */ |
92 | 99 | public function create() |
93 | 100 | { |
94 | 101 | Log::info('Employee Info: Accessed employee registration page', ['action_user_id' => Auth::id()]); |
95 | 102 |
|
96 | 103 | return Inertia::render('employees/Create'); |
97 | 104 | } |
| 105 | + |
| 106 | + /** |
| 107 | + * Store a newly created employee info in storage. |
| 108 | + */ |
| 109 | + public function store(EmployeeRequest $request) |
| 110 | + { |
| 111 | + try { |
| 112 | + $data = $request->validated(); |
| 113 | + |
| 114 | + $genPassword = Str::random(12); |
| 115 | + $request->merge(['password' => $genPassword]); |
| 116 | + |
| 117 | + $userData = [ |
| 118 | + 'name' => $data['name'], |
| 119 | + 'email' => $data['email'], |
| 120 | + 'password' => $request['password'], |
| 121 | + ]; |
| 122 | + |
| 123 | + $employeeData = $request->except(['name', 'email', 'password']); |
| 124 | + |
| 125 | + $employee = EmployeeInfo::create($employeeData); |
| 126 | + $employee->user()->create($userData); |
| 127 | + |
| 128 | + Log::info('Employee Info: A new employee was registered in the system.', ['action_user_id' => Auth::id()]); |
| 129 | + |
| 130 | + // TODO: Enable email sending after setting up mail server |
| 131 | + // Mail::to($employee->user->email)->send(new EmployeeInfoMail($employee, $genPassword)); |
| 132 | + |
| 133 | + // TODO: Redirect to employee details page after implementing the show page |
| 134 | + return to_route('employees.show', ['employee' => $employee->id])->with('success', 'Employee registered successfully.'); |
| 135 | + } catch (Exception $e) { |
| 136 | + Log::error('Employee Info: Error while registering new employee', [ |
| 137 | + 'action_user_id' => Auth::id(), |
| 138 | + 'error' => $e->getMessage(), |
| 139 | + ]); |
| 140 | + |
| 141 | + return back()->withInput()->with('error', 'An error occurred while registering the employee. Please try again.'); |
| 142 | + } |
| 143 | + |
| 144 | + } |
98 | 145 | } |
0 commit comments