<?php

namespace App\Http\Controllers;

use App\Models\CartItem;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Http\Request;

class CustomerDashboardController extends Controller
{
    /**
     * Display the customer dashboard.
     */
    public function index(Request $request)
    {
        $user = $request->user();

        // Get customer statistics
        $stats = [
            'total_orders' => $user->orders()->count(),
            'pending_orders' => $user->orders()->where('status', 'pending')->count(),
            'delivered_orders' => $user->orders()->where('status', 'delivered')->count(),
            'total_spent' => $user->total_spent,
            'cart_items' => $user->cartItems()->count(),
        ];

        // Get recent orders
        $recentOrders = $user->orders()
            ->with('items.product')
            ->latest()
            ->take(5)
            ->get();

        // Get cart items
        $cartItems = $user->cartItems()
            ->with('product.primaryImage')
            ->take(3)
            ->get();

        // Calculate cart total
        $cartTotal = $cartItems->sum(function ($item) {
            return $item->total;
        });

        // Get featured products for recommendations
        $recommendedProducts = Product::where('is_active', true)
            ->where('stock_quantity', '>', 0)
            ->with('primaryImage')
            ->inRandomOrder()
            ->take(4)
            ->get();

        return view('dashboard', compact(
            'stats',
            'recentOrders',
            'cartItems',
            'cartTotal',
            'recommendedProducts'
        ));
    }
}
