carrentalservice/app/Http/Controllers/DashboardController.php
2026-02-19 22:05:20 +00:00

98 lines
3.6 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\Car;
use App\Models\Customer;
use App\Models\Rental;
use App\Models\Service;
use App\Models\Payment;
use Carbon\Carbon;
class DashboardController extends Controller
{
public function index()
{
// Basic stats
$totalCars = Car::count();
$availableCars = Car::where('status', 'available')->count();
$rentedCars = Car::where('status', 'rented')->count();
$maintenanceCars = Car::where('status', 'maintenance')->count();
$totalCustomers = Customer::count();
$activeCustomers = Customer::where('status', 'active')->count();
$totalRentals = Rental::count();
$activeRentals = Rental::where('status', 'active')->count();
$pendingRentals = Rental::where('status', 'pending')->count();
// Revenue stats
$totalRevenue = Payment::where('status', 'completed')->sum('amount');
$monthlyRevenue = Payment::where('status', 'completed')
->whereMonth('created_at', Carbon::now()->month)
->sum('amount');
// Service stats
$totalServices = Service::count();
$totalServiceCost = Service::sum('cost');
$pendingServices = Service::where('status', '!=', 'completed')->count();
// Recent data
$recentRentals = Rental::with(['car', 'customer'])->latest()->take(5)->get();
$recentServices = Service::with('car')->latest()->take(5)->get();
// Chart data - rentals per month (last 6 months)
$monthlyRentals = [];
$monthlyRevenueChart = [];
for ($i = 5; $i >= 0; $i--) {
$month = Carbon::now()->subMonths($i);
$monthlyRentals[] = Rental::whereMonth('created_at', $month->month)
->whereYear('created_at', $month->year)
->count();
$monthlyRevenueChart[] = Payment::where('status', 'completed')
->whereMonth('created_at', $month->month)
->whereYear('created_at', $month->year)
->sum('amount');
}
// Car status distribution for pie chart
$carStatusData = [
'available' => Car::where('status', 'available')->count(),
'rented' => Car::where('status', 'rented')->count(),
'maintenance' => Car::where('status', 'maintenance')->count(),
];
// Cars grouped by status for modal
$carsByStatus = [
'available' => Car::where('status', 'available')->get(),
'rented' => Car::where('status', 'rented')->get(),
'maintenance' => Car::where('status', 'maintenance')->get(),
];
// Top rented cars
$topCars = Rental::select('car_id')
->groupBy('car_id')
->orderByRaw('COUNT(*) DESC')
->take(5)
->get()
->map(function ($rental) {
$car = Car::find($rental->car_id);
$count = Rental::where('car_id', $rental->car_id)->count();
return [
'car' => $car,
'rentals_count' => $count
];
});
return view('dashboard', compact(
'totalCars', 'availableCars', 'rentedCars', 'maintenanceCars',
'totalCustomers', 'activeCustomers',
'totalRentals', 'activeRentals', 'pendingRentals',
'totalRevenue', 'monthlyRevenue',
'totalServices', 'totalServiceCost', 'pendingServices',
'recentRentals', 'recentServices',
'monthlyRentals', 'monthlyRevenueChart', 'carStatusData', 'carsByStatus', 'topCars'
));
}
}