<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev (MKJUEL)
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\Category;
use App\Models\Country;
use App\Models\PaymentGateway;
use App\Models\Currency;
use Inertia\Inertia;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        $year = $request->query('year', date('Y'));
        
        // Find all years where an order was placed for the dropdown
        $availableYears = Order::selectRaw('EXTRACT(YEAR FROM created_at) as year')
            ->distinct()
            ->orderBy('year', 'desc')
            ->pluck('year')
            ->toArray();

        if (empty($availableYears) || !in_array(date('Y'), $availableYears)) {
            array_unshift($availableYears, date('Y'));
        }

        // --- Quick Stats ---
        $totalUsers = User::count();
        $totalStores = User::whereIn('role', ['seller', 'admin'])->count(); 
        
        $totalProducts = Product::count();
        $totalOrders = Order::count();
        $refundRequests = Order::where('is_refund_requested', true)->whereNotIn('status', ['refunded', 'cancelled'])->count();
        $totalCategories = Category::count();
        $activeCountries = Country::where('is_active', true)->count();
        $activeGateways = PaymentGateway::where('is_active', true)->count();

        // --- Calculate Base Sold Volume (Converted to System Base USD) ---
        $currencies = Currency::pluck('exchange_rate', 'code')->toArray();
        
        $allCompletedOrders = Order::whereNotIn('status', ['cancelled', 'pending', 'refunded'])->get(['total_amount', 'currency']);
        $totalSoldBase = 0;
        foreach($allCompletedOrders as $o) {
            $rate = $currencies[$o->currency] ?? 1;
            $totalSoldBase += ($o->total_amount / $rate);
        }

        // --- Growth Metrics ---
        $currentMonthOrders = Order::whereNotIn('status', ['cancelled', 'pending', 'refunded'])
            ->whereMonth('created_at', date('m'))->whereYear('created_at', date('Y'))->get(['total_amount', 'currency']);
        
        $lastMonthOrders = Order::whereNotIn('status', ['cancelled', 'pending', 'refunded'])
            ->whereMonth('created_at', now()->subMonth()->format('m'))->whereYear('created_at', now()->subMonth()->format('Y'))->get(['total_amount', 'currency']);
        
        $currSold = 0; foreach($currentMonthOrders as $o) { $rate = $currencies[$o->currency] ?? 1; $currSold += ($o->total_amount / $rate); }
        $lastSold = 0; foreach($lastMonthOrders as $o) { $rate = $currencies[$o->currency] ?? 1; $lastSold += ($o->total_amount / $rate); }
        
        $soldGrowth = $lastSold > 0 ? (($currSold - $lastSold) / $lastSold) * 100 : ($currSold > 0 ? 100 : 0);
        
        $currSales = $currentMonthOrders->count();
        $lastSales = $lastMonthOrders->count();
        $salesGrowth = $lastSales > 0 ? (($currSales - $lastSales) / $lastSales) * 100 : ($currSales > 0 ? 100 : 0);

        // --- Monthly Graph Data ---
        $yearlyOrders = Order::whereNotIn('status', ['cancelled', 'pending', 'refunded'])
            ->whereYear('created_at', $year)
            ->get(['total_amount', 'currency', 'created_at']);

        $monthlyData = array_fill(1, 12, 0);
        foreach($yearlyOrders as $o) {
            $rate = $currencies[$o->currency] ?? 1;
            $month = (int) Carbon::parse($o->created_at)->format('n');
            $monthlyData[$month] += ($o->total_amount / $rate);
        }

        $monthlySalesData = [];
        $months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        for ($i = 1; $i <= 12; $i++) {
            $monthlySalesData[] = [
                'month' => $months[$i-1],
                'amount' => round($monthlyData[$i], 2)
            ];
        }

        // --- RECENTLY SOLD ---
        $recentSales = OrderItem::with(['order.buyer:id,name', 'product.images'])
            ->whereHas('order', function($q) {
                $q->whereNotIn('status', ['cancelled', 'pending']); 
            })
            ->latest()
            ->take(5)
            ->get()
            ->map(function ($item) {
                $mainImg = $item->product ? $item->product->images->firstWhere('is_main', true) : null;
                $img = $mainImg ? $mainImg->path : ($item->product && $item->product->images->first() ? $item->product->images->first()->path : null);

                return [
                    'id' => $item->id,
                    'product_id' => $item->product_id,
                    'title' => $item->product ? $item->product->title : 'Deleted Product',
                    'slug' => $item->product ? $item->product->slug : null,
                    'image_path' => $img,
                    'qty' => $item->quantity,
                    // Keep native currency for the individual order row display
                    'price' => $item->unit_price,
                    'currency' => $item->order ? $item->order->currency : 'USD',
                    'buyer' => $item->order && $item->order->buyer ? $item->order->buyer->name : 'Unknown Buyer',
                    'time' => $item->created_at->diffForHumans()
                ];
            });

        // --- TOP PRODUCTS ---
        $topProducts = Product::with(['images', 'seller:id,company_name,name'])
            ->withSum(['orderItems as total_sold' => function($q) {
                $q->whereHas('order', function($query) {
                    $query->whereNotIn('status', ['cancelled', 'refunded', 'pending']);
                });
            }], 'quantity')
            ->orderByDesc('total_sold')
            ->take(5)
            ->get()
            ->map(function ($product) {
                $mainImg = $product->images->firstWhere('is_main', true);
                $img = $mainImg ? $mainImg->path : ($product->images->first() ? $product->images->first()->path : null);
                return [
                    'id' => $product->id,
                    'title' => $product->title,
                    'slug' => $product->slug,
                    'image_path' => $img,
                    'total_sold' => (int) $product->total_sold,
                    'seller' => $product->seller ? ($product->seller->company_name ?? $product->seller->name) : 'Unknown',
                ];
            });

        return Inertia::render('cp/Dashboard', [
            'stats' => [
                'total_sold_volume' => round($totalSoldBase, 2),
                'sold_growth' => round($soldGrowth, 1),
                'total_orders' => $totalOrders,
                'sales_growth' => round($salesGrowth, 1),
                'total_users' => $totalUsers,
                'total_stores' => $totalStores, 
                'total_products' => $totalProducts,
                'refund_requests' => $refundRequests,
                'total_categories' => $totalCategories,
                'active_countries' => $activeCountries,
                'active_gateways' => $activeGateways,
            ],
            'monthlySalesData' => $monthlySalesData,
            'recentSales' => $recentSales,
            'topProducts' => $topProducts,
            'filters' => ['year' => $year],
            'availableYears' => $availableYears
        ]);
    }
}