<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\SubCategory;
use App\Models\Product;
use App\Models\Setting;
use App\Models\Order;
use App\Models\User;
use App\Models\Visit;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class AdminDashboardController extends Controller
{
    public function index()
    {
        $currencySymbol = Setting::where('key', 'currency_symbol')->value('value') ?? '$';

        $totalCategories = Category::count();
        $totalSubCategories = SubCategory::count();
        $totalProducts = Product::count();
        $activeProducts = Product::where('is_active', true)->count();
        $lowStockProducts = Product::where('stock', '<', 10)->count();
        
        // Real Data
        $totalRevenue = Order::where('payment_status', 'paid')->sum('total');
        $totalOrders = Order::count();
        $totalCustomers = User::count(); // All users in 'users' table are customers

        // Order & Payment Breakdown
        $pendingOrders = Order::where('status', 'pending')->count();
        $processingOrders = Order::where('status', 'processing')->count();
        $deliveredOrders = Order::where('status', 'delivered')->count();
        $cancelledOrders = Order::where('status', 'cancelled')->count();

        $pendingAmount = Order::where('payment_status', 'pending')->sum('total');
        $paidAmount = $totalRevenue;

        // Today Snapshot (Store Activity)
        $today = Carbon::today();
        $todayOrders = Order::whereDate('created_at', $today)->count();
        $todayRevenue = Order::where('payment_status', 'paid')
            ->whereDate('created_at', $today)
            ->sum('total');
        $todayNewCustomers = User::whereDate('created_at', $today)->count();

        // Visitor Metrics based on storefront visits
        $todayVisitors = Visit::whereDate('created_at', $today)->count();
        $totalVisitors = Visit::count();

        // Processing Snapshot
        $todayProcessing = Order::where('status', 'processing')
            ->whereDate('created_at', $today)
            ->count();

        // Last 7 Days Trend (used for charts)
        $fromDate = Carbon::today()->subDays(6);
        $rawDailyStats = Order::select(
                DB::raw('DATE(created_at) as date'),
                DB::raw('COUNT(*) as orders_count'),
                DB::raw('SUM(total) as revenue_sum')
            )
            ->whereDate('created_at', '>=', $fromDate)
            ->groupBy('date')
            ->orderBy('date')
            ->get()
            ->keyBy('date');

        $rawVisitStats = Visit::select(
                DB::raw('DATE(created_at) as date'),
                DB::raw('COUNT(*) as visits_count')
            )
            ->whereDate('created_at', '>=', $fromDate)
            ->groupBy('date')
            ->orderBy('date')
            ->get()
            ->keyBy('date');

        $chartLabels = [];
        $chartOrders = [];
        $chartRevenue = [];
        $chartVisits = [];
        $chartAvgOrder = [];

        for ($i = 6; $i >= 0; $i--) {
            $date = Carbon::today()->subDays($i);
            $key = $date->toDateString();

            $chartLabels[] = $date->format('d M');

            $ordersCount = isset($rawDailyStats[$key]) ? (int) $rawDailyStats[$key]->orders_count : 0;
            $revenueSum = isset($rawDailyStats[$key]) ? (float) $rawDailyStats[$key]->revenue_sum : 0.0;
            $visitsCount = isset($rawVisitStats[$key]) ? (int) $rawVisitStats[$key]->visits_count : 0;

            $chartOrders[] = $ordersCount;
            $chartRevenue[] = $revenueSum;
            $chartVisits[] = $visitsCount;
            $chartAvgOrder[] = $ordersCount > 0 ? round($revenueSum / $ordersCount, 2) : 0;
        }
        
        $last7Visitors = array_sum($chartVisits);
        $peakVisitors = !empty($chartVisits) ? max($chartVisits) : 0;
        $peakVisitorsLabel = $peakVisitors > 0
            ? ($chartLabels[array_search($peakVisitors, $chartVisits)] ?? 'N/A')
            : 'N/A';
        
        // Recent Orders
        $recentOrders = Order::with('user')->latest()->take(5)->get();

        return view('admin.dashboard', compact(
            'totalCategories',
            'totalSubCategories',
            'totalProducts',
            'activeProducts',
            'lowStockProducts',
            'totalRevenue',
            'totalOrders',
            'totalCustomers',
            'pendingOrders',
            'processingOrders',
            'deliveredOrders',
            'cancelledOrders',
            'pendingAmount',
            'paidAmount',
            'todayOrders',
            'todayRevenue',
            'todayNewCustomers',
            'todayVisitors',
            'totalVisitors',
            'last7Visitors',
            'peakVisitors',
            'peakVisitorsLabel',
            'todayProcessing',
            'chartLabels',
            'chartOrders',
            'chartRevenue',
            'chartVisits',
            'chartAvgOrder',
            'currencySymbol',
            'recentOrders'
        ));
    }
}
