<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $client = $user->client;

        $installations = $client ? $client->installations()->with(['cameras', 'devices'])->get() : collect([]);
        
        $camerasCount = $installations->sum(function($inst) {
            return $inst->cameras->count();
        });

        $latestInvoice = $client
            ? $client->invoices()->where('status', 'pending')->orderBy('due_date', 'asc')->first()
            : null;

        $tickets = $client
            ? $client->tickets()->orderBy('updated_at', 'desc')->take(4)->get()
            : collect([]);

        return view('client.dashboard', compact('installations', 'camerasCount', 'latestInvoice', 'tickets'));
    }
}
