<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Item;
use App\Models\InventoryCategory;
use Illuminate\Http\Request;

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

    public function index(Request $request)
    {
        $query = Item::with('category');

        // Filter by restaurant
        $user = $request->user();
        if ($user->isAdmin()) {
            // Admin: filter by selected restaurant
            if ($request->has('restaurant_id') && $request->restaurant_id) {
                $query->where('restaurant_id', $request->restaurant_id);
            } else {
                // Admin must select restaurant - return empty if not selected
                return response()->json([
                    'data' => [],
                    'current_page' => 1,
                    'last_page' => 1,
                    'per_page' => $request->get('per_page', 50),
                    'total' => 0,
                ]);
            }
        } elseif ($user->isInventoryManager() && $user->restaurant_id) {
            // Inventory manager: filter by their restaurant
            $query->where('restaurant_id', $user->restaurant_id);
        } elseif ($user->isBranchManager() && $user->branch_id) {
            // Branch manager: get restaurant_id from their branch
            $branch = \App\Models\Branch::find($user->branch_id);
            if ($branch && $branch->restaurant_id) {
                $query->where('restaurant_id', $branch->restaurant_id);
            }
        } elseif ($user->restaurant_id) {
            // Restaurant owner and other users
            $query->where('restaurant_id', $user->restaurant_id);
        }

        // Filter by category
        if ($request->has('category_id')) {
            $query->where('category_id', $request->category_id);
        }

        // Filter by status
        if ($request->has('status')) {
            $query->where('status', $request->status);
        } else {
            $query->where(function($q) {
                $q->whereNull('status')->orWhere('status', 'active');
            });
        }

        // Search by name
        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where('name', 'like', '%' . $search . '%');
        }

        $items = $query->orderBy('name')->paginate($request->get('per_page', 50));

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|max:255',
            'category_id' => 'required|exists:inventory_categories,id',
            'status' => 'nullable|in:active,inactive',
            'restaurant_id' => 'nullable|exists:restaurants,id',
        ]);

        $user = $request->user();
        
        // Set restaurant_id based on user role
        if ($user->isAdmin()) {
            // Admin must provide restaurant_id
            if (!$request->has('restaurant_id') || !$request->restaurant_id) {
                return response()->json([
                    'error' => 'Restaurant selection is required'
                ], 400);
            }
            $validated['restaurant_id'] = $request->restaurant_id;
        } elseif ($user->isInventoryManager() && $user->restaurant_id) {
            // Inventory manager: use their assigned restaurant_id
            $validated['restaurant_id'] = $user->restaurant_id;
        } elseif ($user->isBranchManager() && $user->branch_id) {
            // Branch manager: get restaurant_id from their branch automatically
            $branch = \App\Models\Branch::find($user->branch_id);
            if ($branch && $branch->restaurant_id) {
                $validated['restaurant_id'] = $branch->restaurant_id;
            } else {
                return response()->json([
                    'error' => 'Your branch is not assigned to a restaurant'
                ], 400);
            }
        } else {
            // Restaurant owner and other users use their assigned restaurant_id
            if ($user->restaurant_id) {
                $validated['restaurant_id'] = $user->restaurant_id;
            } else {
                return response()->json([
                    'error' => 'Your account is not assigned to a restaurant'
                ], 400);
            }
        }

        // Check if item already exists in same category and restaurant
        $existingItem = Item::where('name', $validated['name'])
            ->where('category_id', $validated['category_id'])
            ->where('restaurant_id', $validated['restaurant_id'])
            ->first();

        if ($existingItem) {
            return response()->json([
                'error' => 'Item already exists in this category'
            ], 422);
        }

        $validated['status'] = $validated['status'] ?? 'active';
        $item = Item::create($validated);
        $item->load('category');

        return response()->json($item, 201);
    }

    public function show(Item $item)
    {
        $item->load('category');
        return response()->json($item);
    }

    public function update(Request $request, Item $item)
    {
        $user = $request->user();
        
        // Refresh to ensure latest data
        $item->refresh();
        
        // Verify access for non-admin users
        if (!$user->isAdmin()) {
            // For inventory manager, verify item belongs to their restaurant
            if ($user->isInventoryManager()) {
                $itemRestaurantId = $item->restaurant_id ? (int) $item->restaurant_id : null;
                $userRestaurantId = $user->restaurant_id ? (int) $user->restaurant_id : null;
                if ($itemRestaurantId !== $userRestaurantId) {
                    return response()->json(['error' => 'Unauthorized. You can only update items from your own restaurant.'], 403);
                }
            }
            // For branch manager, verify item belongs to their restaurant
            if ($user->isBranchManager() && $user->branch_id) {
                $branch = \App\Models\Branch::find($user->branch_id);
                if ($branch && $branch->restaurant_id) {
                    $itemRestaurantId = $item->restaurant_id ? (int) $item->restaurant_id : null;
                    $branchRestaurantId = (int) $branch->restaurant_id;
                    if ($itemRestaurantId !== $branchRestaurantId) {
                        return response()->json(['error' => 'Unauthorized. You can only update items from your own restaurant.'], 403);
                    }
                }
            }
            // For restaurant owner, verify item belongs to their restaurant
            if ($user->isRestaurantOwner()) {
                $itemRestaurantId = $item->restaurant_id ? (int) $item->restaurant_id : null;
                $userRestaurantId = $user->restaurant_id ? (int) $user->restaurant_id : null;
                if ($itemRestaurantId !== $userRestaurantId) {
                    return response()->json(['error' => 'Unauthorized. You can only update items from your own restaurant.'], 403);
                }
            }
        }
        
        $validated = $request->validate([
            'name' => 'required|max:255',
            'category_id' => 'required|exists:inventory_categories,id',
            'status' => 'nullable|in:active,inactive',
            'restaurant_id' => 'nullable|exists:restaurants,id',
        ]);
        
        // Set restaurant_id based on user role
        if ($user->isAdmin()) {
            // Admin can update restaurant_id if provided
            if ($request->has('restaurant_id') && $request->restaurant_id) {
                $validated['restaurant_id'] = $request->restaurant_id;
            } else {
                // Keep existing restaurant_id if not provided
                unset($validated['restaurant_id']);
            }
        } elseif ($user->isInventoryManager() && $user->restaurant_id) {
            // Inventory manager: use their assigned restaurant_id
            $validated['restaurant_id'] = $user->restaurant_id;
        } elseif ($user->isBranchManager() && $user->branch_id) {
            // Branch manager: get restaurant_id from their branch automatically
            $branch = \App\Models\Branch::find($user->branch_id);
            if ($branch && $branch->restaurant_id) {
                $validated['restaurant_id'] = $branch->restaurant_id;
            }
        } else {
            // Non-admin users cannot change restaurant_id
            if ($user->restaurant_id) {
                $validated['restaurant_id'] = $user->restaurant_id;
            }
        }

        $restaurantId = $validated['restaurant_id'] ?? $item->restaurant_id;

        // Check if item name already exists in same category and restaurant
        $existingItem = Item::where('name', $validated['name'])
            ->where('category_id', $validated['category_id'])
            ->where('restaurant_id', $restaurantId)
            ->where('id', '!=', $item->id)
            ->first();

        if ($existingItem) {
            return response()->json([
                'error' => 'Item already exists in this category'
            ], 422);
        }

        $validated['status'] = $validated['status'] ?? $item->status;
        $item->update($validated);
        $item->load('category');

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

    public function destroy(Item $item)
    {
        $user = request()->user();
        
        // Refresh to ensure latest data
        $item->refresh();
        
        // Verify access for non-admin users
        if (!$user->isAdmin()) {
            // For inventory manager, verify item belongs to their restaurant
            if ($user->isInventoryManager()) {
                $itemRestaurantId = $item->restaurant_id ? (int) $item->restaurant_id : null;
                $userRestaurantId = $user->restaurant_id ? (int) $user->restaurant_id : null;
                if ($itemRestaurantId !== $userRestaurantId) {
                    return response()->json(['error' => 'Unauthorized. You can only delete items from your own restaurant.'], 403);
                }
            }
            // For branch manager, verify item belongs to their restaurant
            if ($user->isBranchManager() && $user->branch_id) {
                $branch = \App\Models\Branch::find($user->branch_id);
                if ($branch && $branch->restaurant_id) {
                    $itemRestaurantId = $item->restaurant_id ? (int) $item->restaurant_id : null;
                    $branchRestaurantId = (int) $branch->restaurant_id;
                    if ($itemRestaurantId !== $branchRestaurantId) {
                        return response()->json(['error' => 'Unauthorized. You can only delete items from your own restaurant.'], 403);
                    }
                }
            }
            // For restaurant owner, verify item belongs to their restaurant
            if ($user->isRestaurantOwner()) {
                $itemRestaurantId = $item->restaurant_id ? (int) $item->restaurant_id : null;
                $userRestaurantId = $user->restaurant_id ? (int) $user->restaurant_id : null;
                if ($itemRestaurantId !== $userRestaurantId) {
                    return response()->json(['error' => 'Unauthorized. You can only delete items from your own restaurant.'], 403);
                }
            }
        }
        
        // Check if item is being used in inventories
        $inventoriesCount = \App\Models\Inventory::where('item_id', $item->id)->count();
        
        if ($inventoriesCount > 0) {
            return response()->json([
                'error' => 'Cannot delete item. It is being used by ' . $inventoriesCount . ' inventory item(s).'
            ], 400);
        }

        $item->delete();

        return response()->json(['message' => 'Item deleted successfully']);
    }
}

