<?php

namespace App\Http\Controllers\Api;

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

class DashboardController extends Controller
{
    public function stats()
    {
        $totalRevenue = Order::where('payment_status', 'paid')->sum('total');
        $todayRevenue = Order::whereDate('created_at', today())->where('payment_status', 'paid')->sum('total');
        $monthRevenue = Order::whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->where('payment_status', 'paid')->sum('total');

        // Last 7 days revenue chart
        $revenueChart = [];
        for ($i = 6; $i >= 0; $i--) {
            $date = now()->subDays($i);
            $revenueChart[] = [
                'date' => $date->format('M d'),
                'revenue' => (float) Order::whereDate('created_at', $date->toDateString())
                    ->where('payment_status', 'paid')->sum('total'),
                'orders' => Order::whereDate('created_at', $date->toDateString())->count(),
            ];
        }

        // Top products
        $topProducts = DB::table('order_items')
            ->select('product_name', DB::raw('SUM(quantity) as total_sold'), DB::raw('SUM(total) as revenue'))
            ->groupBy('product_name')
            ->orderByDesc('total_sold')
            ->limit(5)
            ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'stats' => [
                    'total_revenue' => $totalRevenue,
                    'today_revenue' => $todayRevenue,
                    'month_revenue' => $monthRevenue,
                    'total_orders' => Order::count(),
                    'pending_orders' => Order::where('status', 'pending')->count(),
                    'total_customers' => User::where('role', 'customer')->count(),
                    'total_products' => Product::where('is_active', true)->count(),
                    'low_stock_products' => Product::where('stock', '<=', 5)->where('is_active', true)->count(),
                ],
                'revenue_chart' => $revenueChart,
                'top_products' => $topProducts,
                'recent_orders' => Order::with('user')->latest()->take(5)->get(),
            ],
        ]);
    }
}
