MIF_E31211908/app/Http/Controllers/Authentication/AuthController.php

122 lines
3.8 KiB
PHP

<?php
namespace App\Http\Controllers\Authentication;
use App\Http\Controllers\Controller;
use App\Models\Barang;
use App\Models\Notifikasi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
/**
* Handle user authentication.
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse|\Illuminate\Contracts\View\View
*/
public function login(Request $request)
{
$data = ['title' => 'Login'];
if (!$request->ajax() && $request->getMethod() === 'GET') {
return view('page.auth.index', compact('data'));
}
$credentials = $request->only('email', 'password');
$user = User::where('email', $credentials['email'])->first();
if (!$user) {
return response()->json(['message' => 'Email tidak ada di database!'], 200);
}
if (!Hash::check($credentials['password'], $user->password)) {
return response()->json(['message' => 'Password salah!'], 200);
}
if (Auth::attempt($credentials)) {
$this->checkForExpiredItems();
$this->checkForAlmostExpiredItems();
return response()->json([
'message' => 'Berhasil Login!',
'redirect' => route('dashboard')
], 200);
}
return response()->json(['message' => 'Gagal Login!'], 200);
}
private function checkForExpiredItems()
{
$expiredItems = Barang::where('kadaluarsa', '<', now()->toDateString())->get();
$users = User::all();
foreach ($expiredItems as $item) {
foreach ($users as $user) {
$notificationExists = Notifikasi::where('user_id', $user->id)
->where('barang_id', $item->id)
->where('message', "Barang {$item->nama} sudah kadaluarsa.")
->exists();
if (!$notificationExists) {
Notifikasi::create([
'user_id' => $user->id,
'barang_id' => $item->id,
'message' => "Barang {$item->nama} sudah kadaluarsa.",
'created_at' => now(),
'updated_at' => now()
]);
}
}
}
}
private function checkForAlmostExpiredItems()
{
$almostExpiredItems = Barang::where('kadaluarsa', '>=', now()->toDateString())
->where('kadaluarsa', '<=', now()->addWeek()->toDateString())
->get();
$users = User::all();
foreach ($almostExpiredItems as $item) {
foreach ($users as $user) {
$daysLeft = now()->diffInDays(Carbon::parse($item->kadaluarsa), false);
$message = $daysLeft > 0
? "Barang {$item->nama} akan kadaluarsa dalam {$daysLeft} hari."
: "Barang {$item->nama} akan kadaluarsa hari ini.";
$notificationExists = Notifikasi::where('user_id', $user->id)
->where('barang_id', $item->id)
->where('message', $message)
->exists();
if (!$notificationExists) {
Notifikasi::create([
'user_id' => $user->id,
'barang_id' => $item->id,
'message' => $message,
]);
}
}
}
}
/**
* Handle user logout.
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
Auth::logout();
return response()->json(['message' => 'Berhasil Logout!', 'redirect' => route('login')], 200);
}
}