<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Order;
use App\Models\Product;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

class AdminDashboardController extends Controller
{
    /**
     * Display the admin dashboard with real dynamic metrics.
     */
    public function index()
    {
        $totalProducts = Product::count();
        $activeProducts = Product::where('status', 'active')->count();
        $outOfStock = Product::where('stock', '<=', 0)->orWhere('status', 'sold_out')->count();
        $totalCategories = Category::count();
        
        $hasOrdersTable = Schema::hasTable('orders');
        
        $totalOrders = $hasOrdersTable ? Order::count() : 0;
        $revenue = $hasOrdersTable ? (float) Order::sum('total_amount') : 0.00;
        $dbCustomerCount = $hasOrdersTable ? Order::distinct('customer_phone')->count('customer_phone') : 0;
        $totalCustomers = max($dbCustomerCount, User::where('role', 'user')->count());

        $recentProducts = Product::with(['category', 'images'])
            ->latest()
            ->take(5)
            ->get();

        $recentOrders = $hasOrdersTable 
            ? Order::with('items')->latest()->take(5)->get() 
            : collect();

        return view('admin.dashboard', compact(
            'totalProducts',
            'activeProducts',
            'outOfStock',
            'totalCategories',
            'totalCustomers',
            'totalOrders',
            'revenue',
            'recentProducts',
            'recentOrders'
        ));
    }
}
