<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Unit;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

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

    public function index(Request $request)
    {
        $query = Unit::with('restaurant');

        // Filter by restaurant
        $user = $request->user();
        
        // Default units are visible to all users
        // User-specific units are filtered by restaurant
        if (!$user->isAdmin() && $user->restaurant_id) {
            // Non-admin users (restaurant owners, inventory managers) see: default units + their restaurant's units
            $query->where(function($q) use ($user) {
                $q->where('is_default', true)
                  ->orWhere('restaurant_id', $user->restaurant_id);
            });
        } elseif ($request->has('restaurant_id') && $request->restaurant_id) {
            // Admin filtering by restaurant: show default + selected restaurant's units
            $query->where(function($q) use ($request) {
                $q->where('is_default', true)
                  ->orWhere('restaurant_id', $request->restaurant_id);
            });
        } else {
            // Admin without filter: show all units (default + all restaurant units)
            // No additional filter needed
    }

        // Filter by branch manager - they see only their branch's restaurant units
        if ($user->isBranchManager() && $user->branch_id) {
            $branch = \App\Models\Branch::find($user->branch_id);
            if ($branch && $branch->restaurant_id) {
                $query->where(function($q) use ($branch) {
                    $q->where('is_default', true)
                      ->orWhere('restaurant_id', $branch->restaurant_id);
                });
            }
        }

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

        // Search filter
        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', '%' . $search . '%')
                  ->orWhere('abbreviation', 'like', '%' . $search . '%')
                  ->orWhere('description', 'like', '%' . $search . '%');
            });
        }

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

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

    public function store(Request $request)
    {
        $user = $request->user();
        
        // Determine restaurant_id first
        $restaurantId = null;
        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);
            }
            $restaurantId = $request->restaurant_id;
        } elseif ($user->isInventoryManager() && $user->restaurant_id) {
            // Inventory manager: use their assigned restaurant_id
            $restaurantId = $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) {
                $restaurantId = $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) {
                $restaurantId = $user->restaurant_id;
            } else {
                return response()->json([
                    'error' => 'Your account is not assigned to a restaurant'
                ], 400);
            }
        }

        // Validate with unique check per restaurant (excluding default units)
        $validated = $request->validate([
            'name' => [
                'required',
                'max:255',
                Rule::unique('units', 'name')
                    ->where('restaurant_id', $restaurantId)
                    ->where('is_default', false),
            ],
            'abbreviation' => 'nullable|max:50',
            'description' => 'nullable|string',
            'status' => 'required|in:active,inactive',
        ]);

        $validated['restaurant_id'] = $restaurantId;
        $validated['is_default'] = false; // User-created units are never default

        $unit = Unit::create($validated);

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

    public function show(Unit $unit)
    {
        $unit->load('restaurant');
        return response()->json($unit);
    }

    public function update(Request $request, Unit $unit)
    {
        // Prevent editing default units
        if ($unit->is_default) {
            return response()->json([
                'error' => 'Default units cannot be modified'
            ], 403);
        }

        $user = $request->user();
        
        // Verify ownership
        if (!$user->isAdmin()) {
            $userRestaurantId = null;
            if ($user->isInventoryManager() && $user->restaurant_id) {
                $userRestaurantId = $user->restaurant_id;
            } elseif ($user->restaurant_id) {
                $userRestaurantId = $user->restaurant_id;
            }
            
            // Ensure proper type casting for comparison
            $unitRestaurantId = (int) $unit->restaurant_id;
            $userRestaurantIdInt = $userRestaurantId ? (int) $userRestaurantId : null;
            
            if ($unitRestaurantId !== $userRestaurantIdInt) {
                return response()->json([
                    'error' => 'You do not have permission to edit this unit'
                ], 403);
            }
        }

        $restaurantId = $unit->restaurant_id;

        $validated = $request->validate([
            'name' => [
                'required',
                'max:255',
                Rule::unique('units', 'name')
                    ->ignore($unit->id)
                    ->where('restaurant_id', $restaurantId)
                    ->where('is_default', false),
            ],
            'abbreviation' => 'nullable|max:50',
            'description' => 'nullable|string',
            'status' => 'required|in:active,inactive',
        ]);

        $unit->update($validated);

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

    public function destroy(Unit $unit)
    {
        // Prevent deleting default units
        if ($unit->is_default) {
            return response()->json([
                'error' => 'Default units cannot be deleted'
            ], 403);
        }

        $user = $request->user();
        
        // Verify ownership
        if (!$user->isAdmin()) {
            $userRestaurantId = null;
            if ($user->isInventoryManager() && $user->restaurant_id) {
                $userRestaurantId = $user->restaurant_id;
            } elseif ($user->restaurant_id) {
                $userRestaurantId = $user->restaurant_id;
            }
            
            // Ensure proper type casting for comparison
            $unitRestaurantId = (int) $unit->restaurant_id;
            $userRestaurantIdInt = $userRestaurantId ? (int) $userRestaurantId : null;
            
            if ($unitRestaurantId !== $userRestaurantIdInt) {
                return response()->json([
                    'error' => 'You do not have permission to delete this unit'
                ], 403);
            }
        }

        // Check if unit is being used
        $inUse = \App\Models\Inventory::where('item_unit', $unit->name)
            ->orWhere('item_unit', $unit->abbreviation)
            ->exists();

        if ($inUse) {
            return response()->json([
                'error' => 'This unit is currently in use and cannot be deleted'
            ], 400);
        }

        $unit->delete();

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