[Back] <?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Response;
use League\Csv\Writer;
use SplTempFileObject;
use Barryvdh\DomPDF\Facade\Pdf;
use Request;
use Session;
use DB;
use Illuminate\Support\Facades\Hash;
class mycont extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
function generateAllReport()
{
// Fetch input parameters using the static Request facade
$type = Request::query('type');
$format = Request::query('format');
// Define mappings for table names, headers, and views
$config = [
'asset' => [
'table' => 'Asset',
'columns' => ['id', 'item', 'serial_no', 'assetTag', 'location', 'remarks', 'status'],
'headers' => ['ID', 'Item', 'Serial No', 'Asset Tag', 'Location', 'Status', 'Remarks'],
'view' => 'asset-report',
'title' => 'Assets Report',
],
'print-asset' => [
'table' => 'PrintAsset',
'columns' => ['id', 'type', 'location', 'dept', 'brand', 'model', 'assetTag', 'Serial_No', 'remarks', 'status'],
'headers' => ['ID', 'Type', 'Location', 'Department', 'Brand', 'Model', 'Asset Tag', 'Serial No', 'Status', 'Remarks'],
'view' => 'print-asset-report',
'title' => 'Printer Assets Report',
],
'comp-asset' => [
'table' => 'CompAsset',
'columns' => ['id', 'brand', 'model', 'assetTag', 'Serial_No', 'status', 'location', 'remarks'],
'headers' => ['ID', 'Brand', 'Model', 'Asset Tag', 'Serial No', 'Status', 'Location', 'Remarks'],
'view' => 'comp-asset-report',
'title' => 'Computer Assets Report',
],
];
// Validate the type
if (!array_key_exists($type, $config)) {
return redirect()->back()->with('error', 'Invalid report type selected.');
}
// Fetch data from the database
$assets = DB::table($config[$type]['table'])
->select($config[$type]['columns'])
->orderBy('id')
->get();
// Prepare data for the view
$data = [
'assets' => $assets,
'title' => $config[$type]['title'],
];
if ($format === 'pdf') {
$pdf = Pdf::loadView($config[$type]['view'], $data);
return $pdf->download(strtolower(str_replace(' ', '_', $config[$type]['title'])) . '_report.pdf');
} elseif ($format === 'csv') {
$csv = Writer::createFromString('');
$csv->insertOne($config[$type]['headers']);
foreach ($assets as $asset) {
$row = [];
foreach ($config[$type]['columns'] as $column) {
$row[] = $asset->$column ?? 'N/A';
}
$csv->insertOne($row);
}
$csvContent = $csv->getContent();
return Response::make($csvContent, 200, [
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="' . strtolower(str_replace(' ', '_', $config[$type]['title'])) . '_report.csv"',
]);
}
return redirect()->back()->with('error', 'Invalid format selected.');
}
function generateReport()
{
// Get search text and format from the request
$searchText = Request::query('searchTxtHist');
$format = Request::query('format');
// Start query builder
$query = DB::table('AssetHistory')
->join('user', 'AssetHistory.user_id', '=', 'user.id')
->select(
'AssetHistory.*',
'username as username',
DB::raw("
CASE
WHEN type = 'CompAsset' THEN 'Computer'
WHEN type = 'PrintAsset' THEN 'Printer'
WHEN type = 'Asset' THEN 'Other Asset'
ELSE 'Unknown'
END AS type_label
")
)
->orderBy('created_at', 'desc');
// Apply search filter
if ($searchText) {
$query->where(function ($q) use ($searchText) {
$q->where('username', 'LIKE', '%' . $searchText . '%') // Search by username
->orWhere('asset_id', 'LIKE', '%' . $searchText . '%') // Search by asset_id
->orWhere('location', 'LIKE', '%' . $searchText . '%') // Search by location
->orWhere('start_date', 'LIKE', '%' . $searchText . '%') // Search by start_date
->orWhere('remarks', 'LIKE', '%' . $searchText . '%') // Search by remarks
->orWhere(DB::raw("
CASE
WHEN type = 'CompAsset' THEN 'Computer'
WHEN type = 'PrintAsset' THEN 'Printer'
WHEN type = 'Asset' THEN 'Other Asset'
ELSE 'Unknown'
END
"), 'LIKE', '%' . $searchText . '%'); // Search by translated type label
});
}
// Retrieve results
$history = $query->get();
// Add type-specific details
foreach ($history as $entry) {
if ($entry->type === 'CompAsset' || $entry->type === 'PrintAsset') {
$details = DB::table($entry->type)
->select('model', 'brand')
->where('id', $entry->asset_id)
->first();
$entry->details = $details ? "{$details->model} - {$details->brand}" : 'N/A';
} elseif ($entry->type === 'Asset') {
$details = DB::table('Asset')
->select('item')
->where('id', $entry->asset_id)
->first();
$entry->details = $details ? $details->item : 'N/A';
}
}
// Prepare data for report
$data = ['history' => $history];
// Generate report based on format
if ($format === 'csv') {
// Create CSV
$csv = Writer::createFromString('');
$csv->insertOne([
'Asset ID', 'Type', 'Details', 'User', 'Status',
'Location', 'Start Date', 'End Date', 'Remarks', 'Created At', 'Updated At'
]);
foreach ($history as $entry) {
$csv->insertOne([
$entry->asset_id,
$entry->type_label,
$entry->details ?? 'N/A',
$entry->username,
$entry->status,
$entry->location,
$entry->start_date ?? 'N/A',
$entry->end_date ?? 'N/A',
$entry->remarks,
$entry->created_at,
$entry->updated_at
]);
}
return Response::make($csv->getContent(), 200, [
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="asset_history_report.csv"'
]);
} else {
// Default to PDF
$pdf = Pdf::loadView('asset-history-report', $data);
return $pdf->download('asset_history_report.pdf');
}
}
function requestAsset()
{
\Request::validate([
'asset_id' => 'required|integer',
'asset_type' => 'required|string|in:CompAsset,PrintAsset,Asset',
'location' => 'required|string|max:255',
]);
$assetId = \Request::get('asset_id');
$assetType = \Request::get('asset_type');
$location = \Request::get('location');
$userId = Session::get('user_id');
if (!$userId) {
return back()->with('error', 'You must be logged in to request an asset.');
}
// Fetch user data and username
$user = DB::table('user')->where('id', $userId)->first();
if (!$user) {
return back()->with('error', 'User not found.');
}
$username = $user->username; // Adjust to your actual column name for username
$tableMap = [
'CompAsset' => 'CompAsset',
'PrintAsset' => 'PrintAsset',
'Asset' => 'Asset',
];
$table = $tableMap[$assetType] ?? null;
if (!$table) {
return back()->with('error', 'Invalid asset type.');
}
return DB::transaction(function () use ($table, $assetId, $userId, $username, $location, $assetType) {
$asset = DB::table($table)->where('id', $assetId)->first();
if (!$asset) {
return back()->with('error', 'Asset not found.');
}
if (strtolower($asset->status) !== 'available') {
return back()->with('error', 'Asset is not available.');
}
// Update asset status
DB::table($table)->where('id', $assetId)->update([
'status' => 'Pending',
]);
// Insert into AssetHistory with proper remarks
DB::table('AssetHistory')->insert([
'asset_id' => $assetId,
'type' => $assetType,
'user_id' => $userId,
'status' => 'Requested',
'location' => $location,
'start_date' => now(),
'remarks' => 'Asset requested by ' . $username . '.', // Maintained this format
'created_at' => now(),
'updated_at' => now()
]);
return back()->with('success', 'Asset request submitted successfully.');
});
}
function manageRequest()
{
Request::validate([
'asset_id' => 'required|integer',
'asset_type' => 'required|string|in:CompAsset,PrintAsset,Asset',
'action' => 'required|string|in:approve,reject',
]);
$assetId = Request::input('asset_id');
$assetType = Request::input('asset_type');
$action = Request::input('action');
$remarks = $action === 'approve' ? 'Approved by admin.' : 'Rejected by admin.';
$status = $action === 'approve' ? 'Approved' : 'Rejected';
$tableMap = [
'CompAsset' => 'CompAsset',
'PrintAsset' => 'PrintAsset',
'Asset' => 'Asset',
];
$table = $tableMap[$assetType] ?? null;
if (!$table) {
return back()->with('error', 'Invalid asset type.');
}
DB::transaction(function () use ($table, $assetId, $status, $remarks, $action) {
// Fetch the requested asset history entry
$assetHistory = DB::table('AssetHistory')
->where('asset_id', $assetId)
->where('status', 'Requested')
->first();
if (!$assetHistory) {
throw new Exception('No pending request found for this asset.');
}
// Update the AssetHistory table
DB::table('AssetHistory')
->where('id', $assetHistory->id)
->update([
'status' => $action === 'approve' ? 'In Use' : 'Rejected',
'remarks' => $remarks,
'end_date' => $action === 'reject' ? now() : null, // Set end_date if rejected
'updated_at' => now(),
]);
// If approved, update the asset table with the new location
$updateData = ['status' => $action === 'approve' ? 'In Use' : 'Available'];
if ($action === 'approve') {
$updateData['location'] = $assetHistory->location; // Set location from AssetHistory
}
DB::table($table)->where('id', $assetId)->update($updateData);
});
return back()->with('success', "Request has been {$status}.");
}
function returnAsset()
{
Request::validate([
'asset_id' => 'required|integer',
'asset_type' => 'required|string|in:CompAsset,PrintAsset,Asset',
]);
$assetId = Request::input('asset_id');
$assetType = Request::input('asset_type');
$end_date = Request::input('end_date');
$userId = Session::get('user_id'); // Retrieve user_id from session
// Fetch username
$user = DB::table('user')->where('id', $userId)->first();
if (!$user) {
return back()->with('error', 'User not found.');
}
$username = $user->username; // Adjust column name as per your database
$tableMap = [
'CompAsset' => 'CompAsset',
'PrintAsset' => 'PrintAsset',
'Asset' => 'Asset',
];
$table = $tableMap[$assetType] ?? null;
if (!$table) {
return back()->with('error', 'Invalid asset type.');
}
DB::transaction(function () use ($table, $assetId, $end_date, $username) {
// Update the AssetHistory record
DB::table('AssetHistory')->where('asset_id', $assetId)->where('status', 'In Use')->update([
'status' => 'Approved',
'end_date' => now(),
'remarks' => 'Returned by ' . $username . '.', // Updated to include username
'updated_at' => now(),
]);
// Update the asset status back to Available and clear the location
DB::table($table)->where('id', $assetId)->update([
'status' => 'Available',
'location' => '', // Clear the location
]);
});
return back()->with('success', 'Asset has been returned successfully.');
}
function viewHistory()
{
// Get the logged-in user ID and user level from session
$userId = Session::get('user_id');
$userLevel = Session::get('userlevel'); // Get user level from session
if (!$userId) {
return redirect()->route('login')->with('error', 'Please log in to view history.');
}
// Get the search text from the request
$searchText = Request::query('searchTxtHist');
// Start query builder
$query = DB::table('AssetHistory')
->join('user', 'AssetHistory.user_id', '=', 'user.id')
->select(
'AssetHistory.*',
'user.username as username',
DB::raw("
CASE
WHEN AssetHistory.type = 'CompAsset' THEN 'Computer'
WHEN AssetHistory.type = 'PrintAsset' THEN 'Printer'
WHEN AssetHistory.type = 'Asset' THEN 'Other Asset'
ELSE 'Unknown'
END AS type_label
")
)
->orderBy('AssetHistory.created_at', 'desc');
// Apply condition: If user is not admin, filter by user_id
if ($userLevel !== 'admin') {
$query->where('AssetHistory.user_id', $userId);
}
// Apply search filter
if ($searchText) {
$query->where(function ($q) use ($searchText) {
$q->where('user.username', 'LIKE', '%' . $searchText . '%')
->orWhere('AssetHistory.asset_id', 'LIKE', '%' . $searchText . '%')
->orWhere('AssetHistory.location', 'LIKE', '%' . $searchText . '%')
->orWhere('AssetHistory.start_date', 'LIKE', '%' . $searchText . '%')
->orWhere('AssetHistory.remarks', 'LIKE', '%' . $searchText . '%')
->orWhere(DB::raw("
CASE
WHEN AssetHistory.type = 'CompAsset' THEN 'Computer'
WHEN AssetHistory.type = 'PrintAsset' THEN 'Printer'
WHEN AssetHistory.type = 'Asset' THEN 'Other Asset'
ELSE 'Unknown'
END
"), 'LIKE', '%' . $searchText . '%');
});
}
// Paginate results (10 items per page)
$history = $query->paginate(10);
// Add type-specific details
foreach ($history as $entry) {
if ($entry->type === 'CompAsset' || $entry->type === 'PrintAsset') {
$details = DB::table($entry->type)
->select('model', 'brand')
->where('id', $entry->asset_id)
->first();
$entry->details = $details ? "{$details->model} - {$details->brand}" : 'N/A';
} elseif ($entry->type === 'Asset') {
$details = DB::table('Asset')
->select('item')
->where('id', $entry->asset_id)
->first();
$entry->details = $details ? $details->item : 'N/A';
}
}
// Return view with results
return view('history', compact('history'));
}
function ManageAsset(){
//Add Asset
if (Request::get("btnViewAddAsset")){
return view("manageasset/formAddAsset");
}else if(Request::get('btnAddAsset')){
$item = Request::get('item');
$assetTag = Request::get('assetTag');
$serial_no = Request::get('serial_no');
$Remarks = Request::get('Remarks');
$status = Request::get('status');
$location = Request::get('location');
DB::table("Asset")
->insert([
"item" => $item,
"assetTag" => $assetTag,
"Serial_No" => $Serial_No,
"Remarks" => $Remarks,
"status" => $status,
"location" => $location
]);
return redirect ('manageasset');
}
//delete Asset
if (Request::get("btnViewDeleteAsset")){
$id = Request::get("id");
$data = DB::table("Asset")
->where('id',$id)
->first();
return view("manageasset/formDeleteAsset",compact('data'));
}else if(Request::get('btnDeleteAsset')){
$id = Request::get('id');
DB::table("Asset")
->where("id",$id)
->delete();
return redirect ('manageasset');
}
//edit Asset
if (Request::get("btnViewEditAsset")){
$id = Request::get("id");
$data = DB::table("Asset")
->where('id',$id)
->first();
return view("manageasset/formEditAsset",compact('data'));
}else if(Request::get('btnUpdateAsset')){
$item = Request::get('item');
$assetTag = Request::get('assetTag');
$serial_no = Request::get('serial_no');
$remarks = Request::get('remarks');
$status = Request::get('status');
$location = Request::get('location');
$id = Request::get('id');
DB::table("Asset")
->where("id",$id)
->update([
"item" => $item,
"assetTag" => $assetTag,
"serial_no" => $serial_no,
"remarks" => $remarks,
"status" => $status,
"location" => $location
]);
return redirect ('manageasset');
}
//Add Print
if (Request::get("btnViewAddPrint")){
return view("manageasset/formAddAssetPrint");
}else if(Request::get('btnAddPrint')){
$type = Request::get('type');
$location = Request::get('location');
$dept = Request::get('dept');
$brand = Request::get('brand');
$model = Request::get('model');
$assetTag = Request::get('assetTag');
$Serial_No = Request::get('Serial_No');
$Remarks = Request::get('Remarks');
$status = Request::get('status');
DB::table("PrintAsset")
->insert([
"type" => $type,
"location" => $location,
"dept" => $dept,
"brand" => $brand,
"model" => $model,
"assetTag" => $assetTag,
"Serial_No" => $Serial_No,
"Remarks" => $Remarks,
"status" => $status
]);
return redirect ('manageasset');
}
//delete Print
if (Request::get("btnViewDeletePrint")){
$id = Request::get("id");
$data = DB::table("PrintAsset")
->where('id',$id)
->first();
return view("manageasset/formDeleteAssetPrint",compact('data'));
}else if(Request::get('btnDeletePrint')){
$id = Request::get('id');
DB::table("PrintAsset")
->where("id",$id)
->delete();
return redirect ('manageasset');
}
//edit Print
if (Request::get("btnViewEditPrint")){
$id = Request::get("id");
$data = DB::table("PrintAsset")
->where('id',$id)
->first();
return view("manageasset/formEditAssetPrint",compact('data'));
}else if(Request::get('btnUpdateAssetPrint')){
$type = Request::get('type');
$location = Request::get('location');
$dept = Request::get('dept');
$brand = Request::get('brand');
$model = Request::get('model');
$assetTag = Request::get('assetTag');
$Serial_No = Request::get('Serial_No');
$remarks = Request::get('remarks');
$status = Request::get('status');
$id = Request::get('id');
DB::table("PrintAsset")
->where("id",$id)
->update([
"type" => $type,
"location" => $location,
"dept" => $dept,
"brand" => $brand,
"model" => $model,
"assetTag" => $assetTag,
"Serial_No" => $Serial_No,
"remarks" => $remarks,
"status" => $status
]);
return redirect ('manageasset');
}
//Add Comp
if (Request::get("btnViewAddComp")){
return view("manageasset/formAddAssetComp");
}else if(Request::get('btnAddComp')){
$brand = Request::get('brand');
$model = Request::get('model');
$assetTag = Request::get('assetTag');
$Serial_No = Request::get('Serial_No');
$Remarks = Request::get('Remarks');
$status = Request::get('status');
$location = Request::get('location');
DB::table("CompAsset")
->insert([
"brand" => $brand,
"model" => $model,
"assetTag" => $assetTag,
"Serial_No" => $Serial_No,
"status" => $status,
"location" => $location,
"Remarks" => $Remarks
]);
return redirect ('manageasset');
}
//edit Comp
if (Request::get("btnViewEditComp")){
$id = Request::get("id");
$data = DB::table("CompAsset")
->where('id',$id)
->first();
return view("manageasset/formEditAssetComp",compact('data'));
}else if(Request::get('btnUpdateAssetComp')){
$brand = Request::get('brand');
$model = Request::get('model');
$assetTag = Request::get('assetTag');
$Serial_No = Request::get('Serial_No');
$Remarks = Request::get('Remarks');
$location = Request::get('location');
$status = Request::get('status');
$id = Request::get('id');
DB::table("CompAsset")
->where("id",$id)
->update([
"brand" => $brand,
"model" => $model,
"assetTag" => $assetTag,
"Serial_No" => $Serial_No,
"status" => $status,
"location" => $location,
"Remarks" => $Remarks
]);
return redirect ('manageasset');
}
//delete Comp
if (Request::get("btnViewDeleteComp")){
$id = Request::get("id");
$data = DB::table("CompAsset")
->where('id',$id)
->first();
return view("manageasset/formDeleteAssetComp",compact('data'));
}else if(Request::get('btnDeleteComp')){
$id = Request::get('id');
DB::table("CompAsset")
->where("id",$id)
->delete();
return redirect ('manageasset');
}
$CompAsset = DB::table("CompAsset")->get();
$PrintAsset = DB::table("PrintAsset")->get();
$Asset = DB::table("Asset")->get();
$totalCompAsset = DB::table("CompAsset")->count();
$totalPrintAsset = DB::table("PrintAsset")->count();
$totalOtherAsset = DB::table("Asset")->count();
$statusCounts = DB::table('CompAsset')
->select('Status', DB::raw('COUNT(*) as total'))
->groupBy('Status')
->pluck('total', 'Status'); // This will create an associative array like ['In Use' => 10, 'Under Maintenance' => 5]
// Extract individual counts
$inUseCount = $statusCounts->get('In Use', 0); // Default to 0 if the status is not present
$underMaintenanceCount = $statusCounts->get('Under Maintenance', 0);
$availableCount = $statusCounts->get('Available', 0);
$retiredCount = $statusCounts->get('Retired', 0);
$pendingCount = $statusCounts->get('Pending', 0);
$statusCountsPrint = DB::table('PrintAsset')
->select('status', DB::raw('COUNT(*) as total'))
->groupBy('status')
->pluck('total', 'status'); // This will create an associative array like ['In Use' => 10, 'Under Maintenance' => 5]
// Extract individual counts
$inUseCountPrint = $statusCountsPrint->get('In Use', 0); // Default to 0 if the status is not present
$underMaintenanceCountPrint = $statusCountsPrint->get('Under Maintenance', 0);
$availableCountPrint = $statusCountsPrint->get('Available', 0);
$retiredCountPrint = $statusCountsPrint->get('Retired', 0);
$pendingCountPrint = $statusCountsPrint->get('Pending', 0);
$statusCountsOther = DB::table('Asset')
->select('status', DB::raw('COUNT(*) as total'))
->groupBy('status')
->pluck('total', 'status'); // This will create an associative array like ['In Use' => 10, 'Under Maintenance' => 5]
// Extract individual counts
$inUseCountOther = $statusCountsOther->get('In Use', 0); // Default to 0 if the status is not present
$underMaintenanceCountOther = $statusCountsOther->get('Under Maintenance', 0);
$availableCountOther = $statusCountsOther->get('Available', 0);
$retiredCountOther = $statusCountsOther->get('Retired', 0);
$pendingCountOther = $statusCountsOther->get('Pending', 0);
return view("manageassetview",compact('CompAsset','PrintAsset','Asset','totalCompAsset','totalPrintAsset','totalOtherAsset',
'inUseCount','underMaintenanceCount','availableCount','retiredCount','pendingCount',
'inUseCountPrint','underMaintenanceCountPrint','availableCountPrint','retiredCountPrint','pendingCountPrint',
'inUseCountOther','underMaintenanceCountOther','availableCountOther','retiredCountOther','pendingCountOther'));
}
function ListAsset(){
if (Request::get("btnSearchAst")){
$CompAsset = DB::table("CompAsset")
->where("brand","LIKE","%".Request::get("searchTxtAst")."%")
->orwhere("status","LIKE","%".Request::get("searchTxtAst")."%")
->orwhere("model","LIKE","%".Request::get("searchTxtAst")."%")
->orwhere("assetTag","LIKE","%".Request::get("searchTxtAst")."%")
->get();
$PrintAsset = DB::table("PrintAsset")
->where("brand","LIKE","%".Request::get("searchTxtAst")."%")
->orwhere("status","LIKE","%".Request::get("searchTxtAst")."%")
->orwhere("type","LIKE","%".Request::get("searchTxtAst")."%")
->orwhere("brand","LIKE","%".Request::get("searchTxtAst")."%")
->get();
$Asset = DB::table("Asset")
->where("item","LIKE","%".Request::get("searchTxtAst")."%")
->orwhere("status","LIKE","%".Request::get("searchTxtAst")."%")
->orwhere("assetTag","LIKE","%".Request::get("searchTxtAst")."%")
->get();
}else{
$CompAsset = DB::table("CompAsset")->get();
$PrintAsset = DB::table("PrintAsset")->get();
$Asset = DB::table("Asset")->get();
}
return view("main",compact('CompAsset','PrintAsset','Asset'));
}
function ListUser(){
if (Request::get("btnViewAdd")) {
return view("manageuser/formAddUser");
}
// Add User
else if (Request::get('btnAddUser')) {
$fullname = Request::get('fullname');
$username = Request::get('username');
$password = Request::get('password');
$status = Request::get('status');
$level = Request::get('level');
// Hash the password before saving
$hashedPassword = Hash::make($password);
DB::table("user")->insert([
"username" => $username,
"fullname" => $fullname,
"password" => $hashedPassword, // Use hashed password
"status" => $status,
"userlevel" => $level
]);
return redirect('listuser');
}
// View Edit User Form
if (Request::get("btnViewEdit")) {
$id = Request::get("id");
$data = DB::table("user")
->where('id', $id)
->first();
return view("manageuser/formEditUser", compact('data'));
}
// Update User
else if (Request::get('btnUpdateUser')) {
$fullname = Request::get('fullname');
$username = Request::get('username');
$password = Request::get('password');
$level = Request::get('level');
$status = Request::get('status');
$id = Request::get('id');
$updateData = [
"username" => $username,
"fullname" => $fullname,
"status" => $status,
"userlevel" => $level
];
// Check if password is provided; hash only if entered
if (!empty($password)) {
$updateData['password'] = Hash::make($password);
}
DB::table("user")
->where("id", $id)
->update($updateData);
return redirect('listuser');
}
//search user button
if (Request::get("btnSearch")){
$data = DB::table("user")
->where("fullname","LIKE","%".Request::get("searchTxt")."%")
->get();
}else{
$data = DB::table("user")->get();
}
$totalUsers = $data->count();
$statusCounts = DB::table('user')
->select('status', DB::raw('COUNT(*) as total'))
->groupBy('status')
->pluck('total', 'status');
$ActiveCount = $statusCounts->get('Active', 0); // Default to 0 if the status is not present
$DeactiveCount = $statusCounts->get('Deactive', 0);
return view ("viewuser", compact('data','totalUsers','ActiveCount','DeactiveCount'));
}
function Logout(){
Session::forget("username");
return redirect("/login");
}
function Login()
{
if (Request::get("btnLogin")) {
// Get username and password from the request
$usr = Request::get("username");
$pwd = Request::get("password");
// Retrieve user by username
$user = DB::table('user')
->where('username', $usr)
->first(); // Only fetch user data by username
// Check if user exists
if ($user && Hash::check($pwd, $user->password)) { // Verify hashed password
// Check if the user is deactivated
if ($user->status === 'Deactive') {
echo "Your account is deactivated. Please contact the administrator.";
echo "<meta http-equiv='REFRESH' content='3;url=login'>";
return;
}
// Set session variables
Session::put("username", $user->username);
Session::put("fullname", $user->fullname);
Session::put("userlevel", $user->userlevel);
Session::put("user_id", $user->id); // Store user_id in session
// Redirect to the main page after successful login
return redirect("/main");
} else {
// If user not found or password doesn't match
echo "Wrong username/password";
echo "<meta http-equiv='REFRESH' content='3;url=login'>";
}
} else {
// If no form submission detected, just show the login page
echo "None";
}
}
}