<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Restaurant;
use App\Models\Order;
use App\Models\User;
use App\Models\DeliveryBoy;
use App\Models\Delivery;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class AdminController extends Controller
{
    public function dashboard()
    {
        $totalOrders = Order::count();
        $todayOrders = Order::whereDate('created_at', today())->count();
        $totalRevenue = Order::where('payment_status', 'paid')->sum('total') ?? 0;
        $totalRestaurants = Restaurant::count();
        $activeDeliveryBoys = DeliveryBoy::where('status', 'available')->count();
        
        return response()->json([
            'success' => true,
            'data' => [
                'stats' => [
                    'total_orders' => $totalOrders,
                    'today_orders' => $todayOrders,
                    'total_revenue' => $totalRevenue,
                    'total_restaurants' => $totalRestaurants,
                    'active_delivery_boys' => $activeDeliveryBoys,
                ]
            ]
        ]);
    }

    public function getAnalytics(Request $request)
    {
        $days = $request->get('days', 7);
        $startDate = Carbon::now()->subDays($days);
        
        $dailyOrders = Order::select(
            DB::raw('DATE(created_at) as date'),
            DB::raw('COUNT(*) as orders')
        )
        ->where('created_at', '>=', $startDate)
        ->groupBy(DB::raw('DATE(created_at)'))
        ->orderBy('date')
        ->get();
        
        return response()->json([
            'success' => true,
            'data' => [
                'daily_orders' => $dailyOrders,
                'period' => $days
            ]
        ]);
    }
    
    public function systemHealth()
    {
        $pendingOrders = Order::where('status', 'pending')->count();
        
        return response()->json([
            'success' => true,
            'data' => [
                'pending_orders' => $pendingOrders,
                'status' => 'healthy'
            ]
        ]);
    }
}