<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Sale;
use App\Models\Purchase;
use App\Models\Invoice;
use App\Models\Category;
use App\Models\Supplier;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $user = Auth::user();
        $isAdmin = $user->role && $user->role->slug === 'admin';
        
        $today = now()->toDateString();
        $startOfMonth = now()->startOfMonth()->toDateString();
        $endOfMonth = now()->endOfMonth()->toDateString();

        $totalProducts = Product::count();
        $totalCategories = Category::count();
        $totalSuppliers = Supplier::count();
        $lowStockProducts = Product::whereRaw('stock <= min_stock')->count();
        
        // Filter sales by user if not admin
        $salesQuery = Sale::where('status', 'completed');
        $purchasesQuery = Purchase::where('status', 'completed');
        
        if (!$isAdmin) {
            $salesQuery->where('user_id', $user->id);
            $purchasesQuery->where('user_id', $user->id);
        }
        
        $totalSales = $salesQuery->count();
        $totalPurchases = $purchasesQuery->count();
        $totalRevenue = $salesQuery->sum('total');
        $totalExpenses = $purchasesQuery->sum('total');
        $totalInvoices = $isAdmin ? Invoice::count() : Invoice::where('user_id', $user->id)->count();

        $recentSales = Sale::with('user')
            ->where('status', 'completed')
            ->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        $recentPurchases = Purchase::with('supplier', 'user')
            ->where('status', 'completed')
            ->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        $stats = [
            'totalProducts' => $totalProducts,
            'totalCategories' => $totalCategories,
            'totalSuppliers' => $totalSuppliers,
            'lowStockProducts' => $lowStockProducts,
            'totalSales' => $totalSales,
            'totalPurchases' => $totalPurchases,
            'totalRevenue' => $totalRevenue,
            'totalExpenses' => $totalExpenses,
            'totalInvoices' => $totalInvoices,
            'recentSales' => $recentSales,
            'recentPurchases' => $recentPurchases,
            'is_admin' => $isAdmin,
            'products' => [
                'total' => $totalProducts,
                'active' => Product::where('is_active', true)->count(),
                'low_stock' => $lowStockProducts,
                'out_of_stock' => Product::where('stock', 0)->count(),
            ],
            'categories' => [
                'total' => $totalCategories,
                'active' => Category::where('is_active', true)->count(),
            ],
            'suppliers' => [
                'total' => $totalSuppliers,
                'active' => Supplier::where('is_active', true)->count(),
            ],
            'sales' => [
                'today_count' => Sale::where('sale_date', $today)->where('status', 'completed')->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))->count(),
                'today_total' => Sale::where('sale_date', $today)->where('status', 'completed')->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))->sum('total'),
                'month_count' => Sale::whereBetween('sale_date', [$startOfMonth, $endOfMonth])->where('status', 'completed')->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))->count(),
                'month_total' => Sale::whereBetween('sale_date', [$startOfMonth, $endOfMonth])->where('status', 'completed')->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))->sum('total'),
                'total_count' => $totalSales,
                'total_total' => $totalRevenue,
            ],
            'purchases' => [
                'today_count' => Purchase::where('purchase_date', $today)->where('status', 'completed')->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))->count(),
                'today_total' => Purchase::where('purchase_date', $today)->where('status', 'completed')->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))->sum('total'),
                'month_count' => Purchase::whereBetween('purchase_date', [$startOfMonth, $endOfMonth])->where('status', 'completed')->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))->count(),
                'month_total' => Purchase::whereBetween('purchase_date', [$startOfMonth, $endOfMonth])->where('status', 'completed')->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))->sum('total'),
                'total_count' => $totalPurchases,
                'total_total' => $totalExpenses,
            ],
            'invoices' => [
                'today_count' => Invoice::where('issue_date', $today)->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))->count(),
                'month_count' => Invoice::whereBetween('issue_date', [$startOfMonth, $endOfMonth])->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))->count(),
                'paid_count' => Invoice::where('status', 'paid')->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))->count(),
                'pending_count' => Invoice::whereIn('status', ['draft', 'issued'])->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))->count(),
                'total' => $totalInvoices,
            ],
            'inventory' => [
                'total_value' => Product::selectRaw('SUM(stock * purchase_price) as total')->value('total') ?? 0,
                'total_sale_value' => Product::selectRaw('SUM(stock * sale_price) as total')->value('total') ?? 0,
            ],
            'profit' => [
                'month' => Sale::whereBetween('sale_date', [$startOfMonth, $endOfMonth])->where('status', 'completed')->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))->sum('total') 
                           - Purchase::whereBetween('purchase_date', [$startOfMonth, $endOfMonth])->where('status', 'completed')->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))->sum('total'),
                'total' => $totalRevenue - $totalExpenses,
            ],
        ];

        return response()->json($stats);
    }

    public function recentSales(Request $request): JsonResponse
    {
        $user = Auth::user();
        $isAdmin = $user->role && $user->role->slug === 'admin';
        $limit = $request->get('limit', 10);
        
        $sales = Sale::with('user')
            ->where('status', 'completed')
            ->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get();

        return response()->json($sales);
    }

    public function recentPurchases(Request $request): JsonResponse
    {
        $user = Auth::user();
        $isAdmin = $user->role && $user->role->slug === 'admin';
        $limit = $request->get('limit', 10);
        
        $purchases = Purchase::with('supplier', 'user')
            ->where('status', 'completed')
            ->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get();

        return response()->json($purchases);
    }

    public function topProducts(Request $request): JsonResponse
    {
        $limit = $request->get('limit', 10);
        
        $products = Product::with('category')
            ->select('products.*', DB::raw('(SELECT SUM(quantity) FROM sale_items JOIN sales ON sale_items.sale_id = sales.id WHERE sale_items.product_id = products.id AND sales.status = "completed") as total_sold'))
            ->orderByDesc('total_sold')
            ->limit($limit)
            ->get();

        return response()->json($products);
    }

    public function lowStockProducts(Request $request): JsonResponse
    {
        $limit = $request->get('limit', 10);
        
        $products = Product::with('category')
            ->whereRaw('stock <= min_stock')
            ->orderBy('stock')
            ->limit($limit)
            ->get();

        return response()->json($products);
    }

    public function salesChart(Request $request): JsonResponse
    {
        $user = Auth::user();
        $isAdmin = $user->role && $user->role->slug === 'admin';
        $days = $request->get('days', 30);
        $startDate = now()->subDays($days)->toDateString();
        
        $sales = Sale::where('sale_date', '>=', $startDate)
            ->where('status', 'completed')
            ->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))
            ->select(
                'sale_date',
                DB::raw('COUNT(*) as count'),
                DB::raw('SUM(total) as total')
            )
            ->groupBy('sale_date')
            ->orderBy('sale_date')
            ->get();

        return response()->json($sales);
    }

    public function purchasesChart(Request $request): JsonResponse
    {
        $user = Auth::user();
        $isAdmin = $user->role && $user->role->slug === 'admin';
        $days = $request->get('days', 30);
        $startDate = now()->subDays($days)->toDateString();
        
        $purchases = Purchase::where('purchase_date', '>=', $startDate)
            ->where('status', 'completed')
            ->when(!$isAdmin, fn($q) => $q->where('user_id', $user->id))
            ->select(
                'purchase_date',
                DB::raw('COUNT(*) as count'),
                DB::raw('SUM(total) as total')
            )
            ->groupBy('purchase_date')
            ->orderBy('purchase_date')
            ->get();

        return response()->json($purchases);
    }
}
