<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Restaurant;
use App\Models\Branch;
use App\Models\Inventory;
use App\Models\Item;
use App\Models\StockOut;
use App\Models\PosOrder;
use Illuminate\Http\Request;

class AdminDashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }

    public function getStats(Request $request)
    {
        $user = $request->user();
        $restaurantId = $request->input('restaurant_id');
        $branchId = $request->input('branch_id');

        $stats = [];

        // Admin/Super Admin stats
        if ($user->isAdmin()) {
            // Total Restaurants
            $restaurantsQuery = Restaurant::query();
            $stats['total_restaurants'] = $restaurantsQuery->count();

            // Total Branches
            $branchesQuery = Branch::query();
            if ($restaurantId) {
                $branchesQuery->where('restaurant_id', $restaurantId);
            }
            $stats['total_branches'] = $branchesQuery->count();

            // Total Inventories
            $inventoriesQuery = Inventory::query();
            if ($restaurantId) {
                $inventoriesQuery->where('restaurant_id', $restaurantId);
            }
            if ($branchId) {
                $inventoriesQuery->where('branch_id', $branchId);
            }
            $stats['total_inventories'] = $inventoriesQuery->count();

            // Total Orders
            $ordersQuery = PosOrder::query();
            if ($restaurantId) {
                $ordersQuery->where('restaurant_id', $restaurantId);
            }
            if ($branchId) {
                $ordersQuery->where('branch_id', $branchId);
            }
            $stats['total_orders'] = $ordersQuery->count();
        }
        // Restaurant Owner stats
        elseif ($user->isRestaurantOwner() && $user->restaurant_id) {
            // Total Branches (their restaurant's branches)
            $stats['total_branches'] = Branch::where('restaurant_id', $user->restaurant_id)
                ->when($branchId, function ($query) use ($branchId) {
                    return $query->where('id', $branchId);
                })
                ->count();

            // Total Inventory
            $inventoriesQuery = Inventory::where('restaurant_id', $user->restaurant_id);
            if ($branchId) {
                $inventoriesQuery->where('branch_id', $branchId);
            }
            $stats['total_inventories'] = $inventoriesQuery->count();

            // Base query for orders
            $ordersQuery = PosOrder::where('restaurant_id', $user->restaurant_id)->whereNull('deleted_at');
            if ($branchId) {
                $ordersQuery->where('branch_id', $branchId);
            }
            $stats['total_orders'] = $ordersQuery->count();

            // Paid and Unpaid Orders
            $stats['paid_orders'] = PosOrder::where('restaurant_id', $user->restaurant_id)
                ->whereNull('deleted_at')
                ->when($branchId, function ($query) use ($branchId) {
                    return $query->where('branch_id', $branchId);
                })
                ->where('status', 'paid')
                ->count();
            $stats['unpaid_orders'] = PosOrder::where('restaurant_id', $user->restaurant_id)
                ->whereNull('deleted_at')
                ->when($branchId, function ($query) use ($branchId) {
                    return $query->where('branch_id', $branchId);
                })
                ->where('status', '!=', 'paid')
                ->count();

            // Order Status Breakdown
            $stats['orders_by_status'] = [
                'pending' => PosOrder::where('restaurant_id', $user->restaurant_id)->whereNull('deleted_at')->when($branchId, fn($q) => $q->where('branch_id', $branchId))->where('status', 'pending')->count(),
                'confirmed' => PosOrder::where('restaurant_id', $user->restaurant_id)->whereNull('deleted_at')->when($branchId, fn($q) => $q->where('branch_id', $branchId))->where('status', 'confirmed')->count(),
                'preparing' => PosOrder::where('restaurant_id', $user->restaurant_id)->whereNull('deleted_at')->when($branchId, fn($q) => $q->where('branch_id', $branchId))->where('status', 'preparing')->count(),
                'ready' => PosOrder::where('restaurant_id', $user->restaurant_id)->whereNull('deleted_at')->when($branchId, fn($q) => $q->where('branch_id', $branchId))->where('status', 'ready')->count(),
                'completed' => PosOrder::where('restaurant_id', $user->restaurant_id)->whereNull('deleted_at')->when($branchId, fn($q) => $q->where('branch_id', $branchId))->where('status', 'completed')->count(),
                'paid' => PosOrder::where('restaurant_id', $user->restaurant_id)->whereNull('deleted_at')->when($branchId, fn($q) => $q->where('branch_id', $branchId))->where('status', 'paid')->count(),
                'cancelled' => PosOrder::where('restaurant_id', $user->restaurant_id)->whereNull('deleted_at')->when($branchId, fn($q) => $q->where('branch_id', $branchId))->where('status', 'cancelled')->count(),
            ];

            // Order Type Breakdown
            $stats['orders_by_type'] = [
                'dine_in' => PosOrder::where('restaurant_id', $user->restaurant_id)->whereNull('deleted_at')->when($branchId, fn($q) => $q->where('branch_id', $branchId))->where('order_type', 'dine_in')->count(),
                'take_away' => PosOrder::where('restaurant_id', $user->restaurant_id)->whereNull('deleted_at')->when($branchId, fn($q) => $q->where('branch_id', $branchId))->where('order_type', 'take_away')->count(),
                'delivery' => PosOrder::where('restaurant_id', $user->restaurant_id)->whereNull('deleted_at')->when($branchId, fn($q) => $q->where('branch_id', $branchId))->where('order_type', 'delivery')->count(),
                'service' => PosOrder::where('restaurant_id', $user->restaurant_id)->whereNull('deleted_at')->when($branchId, fn($q) => $q->where('branch_id', $branchId))->where('order_type', 'service')->count(),
            ];

            // Total Inventory Transfers
            $branchIds = Branch::where('restaurant_id', $user->restaurant_id)->pluck('id');
            $transfersQuery = StockOut::whereIn('branch_id', $branchIds);
            if ($branchId) {
                $transfersQuery->where('branch_id', $branchId);
            }
            $stats['total_transfers'] = $transfersQuery->count();
        }
        // Branch User (Branch Manager, Staff, Cashier) stats
        elseif ($user->branch_id) {
            // Base query for orders (their branch)
            $baseQuery = PosOrder::where('branch_id', $user->branch_id)->whereNull('deleted_at');
            
            // Total Orders (their branch)
            $stats['total_orders'] = $baseQuery->count();

            // Paid and Unpaid Orders
            $stats['paid_orders'] = PosOrder::where('branch_id', $user->branch_id)
                ->whereNull('deleted_at')
                ->where('status', 'paid')
                ->count();
            $stats['unpaid_orders'] = PosOrder::where('branch_id', $user->branch_id)
                ->whereNull('deleted_at')
                ->where('status', '!=', 'paid')
                ->count();

            // Order Status Breakdown
            $stats['orders_by_status'] = [
                'pending' => PosOrder::where('branch_id', $user->branch_id)->whereNull('deleted_at')->where('status', 'pending')->count(),
                'confirmed' => PosOrder::where('branch_id', $user->branch_id)->whereNull('deleted_at')->where('status', 'confirmed')->count(),
                'preparing' => PosOrder::where('branch_id', $user->branch_id)->whereNull('deleted_at')->where('status', 'preparing')->count(),
                'ready' => PosOrder::where('branch_id', $user->branch_id)->whereNull('deleted_at')->where('status', 'ready')->count(),
                'completed' => PosOrder::where('branch_id', $user->branch_id)->whereNull('deleted_at')->where('status', 'completed')->count(),
                'paid' => PosOrder::where('branch_id', $user->branch_id)->whereNull('deleted_at')->where('status', 'paid')->count(),
                'cancelled' => PosOrder::where('branch_id', $user->branch_id)->whereNull('deleted_at')->where('status', 'cancelled')->count(),
            ];

            // Order Type Breakdown
            $stats['orders_by_type'] = [
                'dine_in' => PosOrder::where('branch_id', $user->branch_id)->whereNull('deleted_at')->where('order_type', 'dine_in')->count(),
                'take_away' => PosOrder::where('branch_id', $user->branch_id)->whereNull('deleted_at')->where('order_type', 'take_away')->count(),
                'delivery' => PosOrder::where('branch_id', $user->branch_id)->whereNull('deleted_at')->where('order_type', 'delivery')->count(),
                'service' => PosOrder::where('branch_id', $user->branch_id)->whereNull('deleted_at')->where('order_type', 'service')->count(),
            ];

            // Total Inventory (their branch)
            $stats['total_inventories'] = Inventory::where('branch_id', $user->branch_id)->count();

            // Total Transfers (their branch)
            $stats['total_transfers'] = StockOut::where('branch_id', $user->branch_id)->count();
        }

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

    public function getRecentOrders(Request $request)
    {
        $user = $request->user();
        $limit = $request->input('limit', 10);
        $restaurantId = $request->input('restaurant_id');
        $branchId = $request->input('branch_id');

        $query = PosOrder::with(['table.floor', 'tables.floor', 'waiter', 'branch', 'restaurant'])
            ->whereNull('deleted_at')
            ->orderBy('created_at', 'desc');

        // Apply filters based on user role
        if ($user->isAdmin()) {
            if ($restaurantId) {
                $query->where('restaurant_id', $restaurantId);
            }
            if ($branchId) {
                $query->where('branch_id', $branchId);
            }
        } elseif ($user->isRestaurantOwner() && $user->restaurant_id) {
            $query->where('restaurant_id', $user->restaurant_id);
            if ($branchId) {
                $query->where('branch_id', $branchId);
            }
        } elseif ($user->branch_id) {
            $query->where('branch_id', $user->branch_id);
        } else {
            return response()->json(['data' => []]);
        }

        $orders = $query->limit($limit)->get();

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

