102 lines
3.2 KiB
PHP
102 lines
3.2 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Admin;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use Illuminate\Http\Request;
|
|
use App\Models\User;
|
|
use App\Models\Booking;
|
|
use App\Models\Measurement;
|
|
use Illuminate\Support\Facades\DB;
|
|
use App\Services\ApiService;
|
|
|
|
|
|
class DashboardController extends Controller
|
|
{
|
|
/**
|
|
* API Service
|
|
*
|
|
* @var ApiService
|
|
*/
|
|
protected $apiService;
|
|
|
|
/**
|
|
* Constructor
|
|
*
|
|
* @param ApiService $apiService
|
|
*/
|
|
public function __construct(ApiService $apiService)
|
|
{
|
|
$this->apiService = $apiService;
|
|
}
|
|
|
|
public function index()
|
|
{
|
|
// Periksa apakah token API tersedia di session
|
|
$token = session('api_token');
|
|
$tokenType = session('token_type');
|
|
$userData = session('user_data');
|
|
|
|
if (!$token || !$tokenType) {
|
|
return redirect()->route('admin.login')
|
|
->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
|
|
}
|
|
|
|
// Tampilkan data dari API atau gunakan data yang sudah ada di session
|
|
try {
|
|
// Coba ambil data dari API untuk dashboard
|
|
// Jika tidak berhasil, gunakan data lokal saja
|
|
$response = $this->apiService->get('api/admin/dashboard');
|
|
|
|
if (!$response->successful()) {
|
|
// Token tidak valid atau kedaluwarsa
|
|
\Log::warning('Dashboard API Error: Token tidak valid', [
|
|
'status' => $response->status(),
|
|
'body' => $response->json()
|
|
]);
|
|
|
|
if ($response->status() === 401) {
|
|
session()->forget(['api_token', 'token_type', 'user_data']);
|
|
return redirect()->route('admin.login')
|
|
->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
|
|
}
|
|
} else {
|
|
// Jika berhasil, gunakan data dari API
|
|
$apiData = $response->json();
|
|
if (isset($apiData['data'])) {
|
|
// Simpan data dari API ke variabel untuk dikirim ke view
|
|
$dashboardData = $apiData['data'];
|
|
return view('admin.dashboard', compact('dashboardData', 'userData'));
|
|
}
|
|
}
|
|
} catch (\Exception $e) {
|
|
\Log::error('Dashboard API Error:', [
|
|
'message' => $e->getMessage(),
|
|
'trace' => $e->getTraceAsString()
|
|
]);
|
|
}
|
|
|
|
// Jika tidak berhasil mengambil data dari API, gunakan data lokal
|
|
// Menghitung total data untuk statistik
|
|
$totalCustomers = User::where('role', 'pelanggan')->count();
|
|
$totalOrders = Booking::count() ?? 0;
|
|
|
|
// Menghitung total pengukuran dari data JSON di tabel bookings
|
|
$totalMeasurements = Booking::whereNotNull('measurements')->count() ?? 0;
|
|
|
|
// Mengambil pesanan terbaru
|
|
$recentOrders = Booking::with('customer')
|
|
->latest()
|
|
->take(5)
|
|
->get();
|
|
|
|
return view('admin.dashboard', compact(
|
|
'totalCustomers',
|
|
'totalOrders',
|
|
'totalMeasurements',
|
|
'recentOrders',
|
|
'userData'
|
|
));
|
|
}
|
|
}
|