<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Machine\Machine;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        // 每頁顯示筆數限制 (預設為 10)
        $perPage = (int) request()->input('per_page', 10);
        if ($perPage <= 0)
            $perPage = 10;

        // 從資料庫獲取真實統計數據
        $totalRevenue = \App\Models\Member\MemberWallet::sum('balance');
        $activeMachines = Machine::online()->count();
        $offlineMachines = Machine::offline()->count();
        $alertsPending = Machine::hasError()->count();
        $memberCount = \App\Models\Member\Member::count();

        // 獲取機台列表 (分頁)
        $machines = Machine::when($request->search, function ($query, $search) {
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('serial_no', 'like', "%{$search}%");
            });
        })
            ->orderByDesc('last_heartbeat_at')
            ->paginate($perPage)
            ->withQueryString();

        return view('admin.dashboard', compact(
            'totalRevenue',
            'activeMachines',
            'offlineMachines',
            'alertsPending',
            'memberCount',
            'machines'
        ));
    }
}
