<?php

namespace App\Http\Controllers\Backend;

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

class DashboardController extends Controller
{
    public function index()
    {
        // তারিখ রেঞ্জ
        $today      = Carbon::today();
        $monthStart = Carbon::now()->startOfMonth();

        // অর্ডার কাউন্ট
        $totalOrders = Order::count();
        $todayOrders = Order::whereDate('created_at', $today)->count();

        // সেলস এমাউন্ট
        $totalSalesAmount = Order::sum('total_price');
        $todaySalesAmount = Order::whereDate('created_at', $today)->sum('total_price');
        $thisMonthSales   = Order::where('created_at', '>=', $monthStart)->sum('total_price');

        // স্ট্যাটাস অনুযায়ী
        $completedOrders = Order::where('status', 'completed')->count();
        $pendingOrders   = Order::where('status', 'pending')->count();

        // প্রোডাক্ট / কাস্টমার
        $totalProducts  = Product::count();
        $totalCustomers = User::where('role', 'user')->count();

        // সাম্প্রতিক অর্ডার (join দিয়ে product name সহ)
        $recentOrders = DB::table('orders')
            ->leftJoin('order_details', 'orders.id', '=', 'order_details.order_id')
            ->leftJoin('products', 'order_details.product_id', '=', 'products.id')
            ->select(
                'orders.id',
                'orders.name',
                'orders.total_price',
                'orders.status',
                'orders.created_at',
                'products.name as product_name'
            )
            ->orderBy('orders.created_at', 'desc')
            ->limit(10)
            ->get();

        // Top selling products (sold_count field diye)
        $topSelling = Product::orderByDesc('sold_count')
            ->limit(5)
            ->get();

        return view('backend.admin.dashboard', compact(
            'totalOrders',
            'todayOrders',
            'totalSalesAmount',
            'todaySalesAmount',
            'thisMonthSales',
            'completedOrders',
            'pendingOrders',
            'totalProducts',
            'totalCustomers',
            'recentOrders',
            'topSelling'
        ));
    }
}
