<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\Reel;
use App\Models\Shop;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $isSuperAdmin = $user?->hasRole('super-admin');

        $accessibleShopsQuery = Shop::query();
        if (! $isSuperAdmin) {
            $accessibleShopsQuery->where('created_by', $user?->id)
                ->orWhereHas('users', function ($q) use ($user) {
                    $q->where('users.id', $user?->id);
                });
        }

        $accessibleShops = $accessibleShopsQuery
            ->select('id', 'name')
            ->get();

        $accessibleShopIds = $accessibleShops->pluck('id');
        $accessibleShopNames = $accessibleShops->pluck('name');

        $hasShopAccess = $isSuperAdmin || $accessibleShopIds->isNotEmpty() || $accessibleShopNames->isNotEmpty();

        $productsQuery = Product::query();
        if (! $isSuperAdmin) {
            $productsQuery->whereIn('shop_id', $accessibleShopIds);
        }

        $scopedItemsQuery = OrderItem::query();
        if (! $isSuperAdmin) {
            $scopedItemsQuery->where(function ($q) use ($accessibleShopIds, $accessibleShopNames) {
                $q->whereHas('product', function ($productQuery) use ($accessibleShopIds) {
                    $productQuery->whereIn('shop_id', $accessibleShopIds);
                })->orWhereIn('shop_name', $accessibleShopNames);
            });
        }

        $orderIds = $hasShopAccess
            ? (clone $scopedItemsQuery)->pluck('order_id')->unique()->values()
            : collect();

        $ordersQuery = Order::query();
        if (! $isSuperAdmin) {
            $ordersQuery->whereIn('id', $orderIds);
        }

        $statusCounts = $hasShopAccess
            ? (clone $ordersQuery)
            ->select('status', DB::raw('count(*) as total'))
            ->groupBy('status')
            ->pluck('total', 'status')
            : collect();

        $stats = [
            'shops' => $isSuperAdmin ? (int) Shop::count() : (int) $accessibleShops->count(),
            'products' => $hasShopAccess ? (int) (clone $productsQuery)->count() : 0,
            'orders' => $hasShopAccess ? (int) (clone $ordersQuery)->count() : 0,
            'gross_sales' => $hasShopAccess ? (float) ((clone $scopedItemsQuery)->sum('line_total') ?? 0) : 0,
            'pending_orders' => (int) ($statusCounts['pending'] ?? 0),
            'completed_orders' => (int) ($statusCounts['completed'] ?? 0),
            'cancelled_orders' => (int) ($statusCounts['cancelled'] ?? 0),
            'low_stock_products' => $hasShopAccess ? (int) (clone $productsQuery)->where('stock', '>', 0)->where('stock', '<=', 5)->count() : 0,
            'out_of_stock_products' => $hasShopAccess ? (int) (clone $productsQuery)->where('stock', '<=', 0)->count() : 0,
        ];

        if ($isSuperAdmin) {
            $reelScope = Reel::query();
        } else {
            $reelScope = Reel::query()->where(function ($q) use ($accessibleShopIds, $user) {
                $q->whereIn('shop_id', $accessibleShopIds)
                    ->orWhere('created_by', $user?->id);
            });
        }

        $stats['reels'] = $hasShopAccess ? (int) (clone $reelScope)->count() : 0;
        $stats['active_reels'] = $hasShopAccess ? (int) (clone $reelScope)->where('is_active', true)->count() : 0;

        $recentOrders = $hasShopAccess
            ? (clone $ordersQuery)
            ->select('id', 'order_number', 'customer_name', 'status', 'total_amount', 'created_at')
            ->latest('created_at')
            ->limit(8)
            ->get()
            : collect();

        $topShops = collect();
        if ($hasShopAccess) {
            $topShopsQuery = DB::table('order_items')
                ->leftJoin('products', 'order_items.product_id', '=', 'products.id')
                ->select(
                    DB::raw("COALESCE(order_items.shop_name, 'Unknown') as shop_name"),
                    DB::raw('SUM(order_items.line_total) as revenue'),
                    DB::raw('SUM(order_items.quantity) as qty_sold')
                )
                ->groupBy('shop_name')
                ->orderByDesc('revenue')
                ->limit(5);

            if (! $isSuperAdmin) {
                $topShopsQuery->where(function ($q) use ($accessibleShopIds, $accessibleShopNames) {
                    $q->whereIn('products.shop_id', $accessibleShopIds)
                        ->orWhereIn('order_items.shop_name', $accessibleShopNames);
                });
            }

            $topShops = $topShopsQuery->get();
        }

        $startMonth = Carbon::now()->startOfMonth()->subMonths(5);
        $monthLabels = [];
        $monthKeyToLabel = [];

        for ($i = 0; $i < 6; $i++) {
            $month = (clone $startMonth)->addMonths($i);
            $key = $month->format('Y-m');
            $label = $month->format('M Y');
            $monthLabels[] = $label;
            $monthKeyToLabel[$key] = $label;
        }

        $monthlyRevenueRaw = collect();
        if ($hasShopAccess) {
            $monthlyRevenueQuery = DB::table('order_items')
                ->join('orders', 'order_items.order_id', '=', 'orders.id')
                ->leftJoin('products', 'order_items.product_id', '=', 'products.id')
                ->where('orders.created_at', '>=', $startMonth)
                ->select(
                    DB::raw("DATE_FORMAT(orders.created_at, '%Y-%m') as month_key"),
                    DB::raw('SUM(order_items.line_total) as revenue')
                )
                ->groupBy('month_key')
                ->orderBy('month_key');

            if (! $isSuperAdmin) {
                $monthlyRevenueQuery->where(function ($q) use ($accessibleShopIds, $accessibleShopNames) {
                    $q->whereIn('products.shop_id', $accessibleShopIds)
                        ->orWhereIn('order_items.shop_name', $accessibleShopNames);
                });
            }

            $monthlyRevenueRaw = $monthlyRevenueQuery
                ->pluck('revenue', 'month_key')
                ->map(fn($value) => (float) $value);
        }

        $monthlyRevenueSeries = [];
        foreach (array_keys($monthKeyToLabel) as $monthKey) {
            $monthlyRevenueSeries[] = (float) ($monthlyRevenueRaw[$monthKey] ?? 0);
        }

        $orderStatusSeries = [
            (int) ($statusCounts['pending'] ?? 0),
            (int) ($statusCounts['completed'] ?? 0),
            (int) ($statusCounts['cancelled'] ?? 0),
        ];

        return view('backend.dashboard', [
            'stats' => $stats,
            'topShops' => $topShops,
            'recentOrders' => $recentOrders,
            'monthLabels' => $monthLabels,
            'monthlyRevenueSeries' => $monthlyRevenueSeries,
            'orderStatusSeries' => $orderStatusSeries,
            'accessibleShops' => $accessibleShops,
            'isSuperAdmin' => $isSuperAdmin,
        ]);
    }
}
