<?php
namespace App\Http\Controllers\API\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Product;
use App\Models\User;
use App\Models\Vendor;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdminAnalyticsController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        return response()->json([
            'revenue'       => $this->revenueData($request),
            'orders'        => $this->ordersData($request),
            'top_vendors'   => $this->topVendorsData(),
            'top_products'  => $this->topProductsData(),
        ]);
    }

    public function revenue(Request $request): JsonResponse
    {
        $period = $request->get('period', 'monthly');
        $months = $request->get('months', 12);

        $data = Order::where('payment_status', 'paid')
            ->where('created_at', '>=', now()->subMonths($months))
            ->select(
                DB::raw('DATE_FORMAT(created_at, "%Y-%m") as period'),
                DB::raw('SUM(total) as revenue'),
                DB::raw('SUM(commission_amount) as commission'),
                DB::raw('COUNT(*) as orders_count')
            )
            ->groupBy('period')
            ->orderBy('period')
            ->get();

        return response()->json(['data' => $data]);
    }

    public function orders(Request $request): JsonResponse
    {
        $statusBreakdown = Order::select('status', DB::raw('COUNT(*) as count'))
            ->groupBy('status')
            ->get();

        $daily = Order::where('created_at', '>=', now()->subDays(30))
            ->select(
                DB::raw('DATE(created_at) as date'),
                DB::raw('COUNT(*) as count'),
                DB::raw('SUM(total) as revenue')
            )
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        return response()->json(['status_breakdown' => $statusBreakdown, 'daily' => $daily]);
    }

    public function topVendors(): JsonResponse
    {
        $vendors = Vendor::with('user:id,name')
            ->select('vendors.*', DB::raw('(SELECT COUNT(*) FROM orders WHERE vendor_id = vendors.id AND payment_status = "paid") as order_count'))
            ->orderByDesc('total_earnings')
            ->limit(10)
            ->get();

        return response()->json(['data' => $vendors]);
    }

    public function topProducts(): JsonResponse
    {
        $products = Product::with('vendor:id,store_name')
            ->orderByDesc('sales_count')
            ->limit(10)
            ->get(['id', 'name', 'price', 'sales_count', 'average_rating', 'thumbnail', 'vendor_id']);

        return response()->json(['data' => $products]);
    }

    public function customers(): JsonResponse
    {
        $total = User::role('customer')->count();
        $newThisMonth = User::role('customer')->where('created_at', '>=', now()->startOfMonth())->count();
        $active = User::role('customer')->whereHas('orders', fn($q) => $q->where('created_at', '>=', now()->subDays(30)))->count();

        $growth = User::role('customer')
            ->where('created_at', '>=', now()->subMonths(6))
            ->select(DB::raw('DATE_FORMAT(created_at, "%Y-%m") as month'), DB::raw('COUNT(*) as count'))
            ->groupBy('month')
            ->orderBy('month')
            ->get();

        return response()->json([
            'total' => $total, 'new_this_month' => $newThisMonth,
            'active_30d' => $active, 'growth' => $growth,
        ]);
    }

    public function monthlyGrowth(): JsonResponse
    {
        $vendorGrowth = Vendor::where('created_at', '>=', now()->subMonths(12))
            ->select(DB::raw('DATE_FORMAT(created_at, "%Y-%m") as month'), DB::raw('COUNT(*) as count'))
            ->groupBy('month')->orderBy('month')->get();

        $customerGrowth = User::role('customer')->where('created_at', '>=', now()->subMonths(12))
            ->select(DB::raw('DATE_FORMAT(created_at, "%Y-%m") as month'), DB::raw('COUNT(*) as count'))
            ->groupBy('month')->orderBy('month')->get();

        $revenueGrowth = Order::where('payment_status', 'paid')->where('created_at', '>=', now()->subMonths(12))
            ->select(DB::raw('DATE_FORMAT(created_at, "%Y-%m") as month'), DB::raw('SUM(total) as revenue'))
            ->groupBy('month')->orderBy('month')->get();

        return response()->json([
            'vendor_growth' => $vendorGrowth,
            'customer_growth' => $customerGrowth,
            'revenue_growth' => $revenueGrowth,
        ]);
    }

    private function revenueData(Request $request): array
    {
        return Order::where('payment_status', 'paid')->select(
            DB::raw('SUM(total) as total'),
            DB::raw('SUM(commission_amount) as commission')
        )->first()->toArray();
    }

    private function ordersData(Request $request): array
    {
        return ['total' => Order::count(), 'pending' => Order::where('status', 'pending')->count()];
    }

    private function topVendorsData(): array
    {
        return Vendor::orderByDesc('total_earnings')->limit(5)->get(['id', 'store_name', 'total_earnings'])->toArray();
    }

    private function topProductsData(): array
    {
        return Product::orderByDesc('sales_count')->limit(5)->get(['id', 'name', 'sales_count'])->toArray();
    }
}
