<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Customer;
use App\Models\AuctionVehicle;
use App\Models\Bid;
use App\Models\Vehicle;
use App\Models\Order;
use App\Models\Payment;
use App\Models\Lead;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function index()
    {
        $totalCustomers = Customer::count();
        $activeAuctions = AuctionVehicle::active()->count();
        $todayBids = Bid::whereDate('created_at', Carbon::today())->count();
        $pendingBids = Bid::where('status', 'pending')->count();
        $wonAuctions = Bid::where('status', 'won')->count();
        $lostAuctions = Bid::where('status', 'lost')->count();
        
        $readyStockCount = Vehicle::available()->count();
        $soldVehiclesCount = Vehicle::where('status', 'sold')->count();
        $totalOrders = Order::count();
        $totalRevenueBdt = Order::sum('total_amount_bdt');
        $totalPaidBdt = Order::sum('paid_amount_bdt');
        $pendingPaymentsBdt = Order::sum('due_amount_bdt');

        $newLeadsCount = Lead::where('status', 'new')->count();

        // Recent pending bids requiring attention
        $pendingBidsList = Bid::with('user', 'auctionVehicle.auctionHouse')
            ->where('status', 'pending')
            ->orderBy('created_at', 'desc')
            ->take(6)
            ->get();

        // Recent active import orders
        $recentOrders = Order::with('user', 'auctionVehicle', 'vehicle')
            ->orderBy('created_at', 'desc')
            ->take(5)
            ->get();

        // Chart Data: Monthly Bids (Last 6 Months)
        $chartMonths = ['May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct'];
        $chartBids = [8, 14, 19, 23, 31, 20];
        $chartOrders = [2, 3, 5, 4, 7, 6];

        return view('admin.dashboard', compact(
            'totalCustomers',
            'activeAuctions',
            'todayBids',
            'pendingBids',
            'wonAuctions',
            'lostAuctions',
            'readyStockCount',
            'soldVehiclesCount',
            'totalOrders',
            'totalRevenueBdt',
            'totalPaidBdt',
            'pendingPaymentsBdt',
            'newLeadsCount',
            'pendingBidsList',
            'recentOrders',
            'chartMonths',
            'chartBids',
            'chartOrders'
        ));
    }
}
