<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\User;
use App\Models\Order;
use App\Models\Transaction;

class AdminDashboard extends Component
{
    public $totalUsers;
    public $totalOrders;
    public $totalTransactions;
    public $recentActivity;

    public function mount()
    {
        $this->loadStatistics();
    }

    public function loadStatistics()
    {
        if(auth()->user()->hasRole('admin')) {
            $this->totalUsers = User::count();
            $this->totalOrders = Order::count();
            $this->totalTransactions = Transaction::count();
            
        
            $this->recentActivity = Transaction::with('user')
                ->orderBy('created_at', 'desc')
                ->take(10)
                ->get();
        } else {
            $managedUsers = auth()->user()->managedUsers;
            $this->totalUsers = User::whereIn('id', $managedUsers->pluck('id'))->count();
            $this->totalOrders = Order::whereIn('user_id', $managedUsers->pluck('id'))->count();
            $this->totalTransactions = Transaction::whereIn('user_id', $managedUsers->pluck('id'))->count();
            
            $this->recentActivity = Transaction::with('user')
                ->whereIn('user_id', $managedUsers->pluck('id'))
                ->orderBy('created_at', 'desc')
                ->take(10)
                ->get();
        }
    }

    public function render()
    {
        return view('livewire.admin-dashboard');
    }
} 