<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\BranchFloor;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\Helpers\RestaurantBranchFilterTrait;

class BranchFloorController extends Controller
{
    use RestaurantBranchFilterTrait;

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $user = $request->user();
        
        // Allow admin, restaurant_owner, and branch_manager to view floors
        if (!$user || !in_array($user->role, ['admin', 'restaurant_owner', 'branch_manager'])) {
            return response()->json(['message' => 'Unauthorized. Only admins, restaurant owners, and branch managers can view floors.'], 403);
        }

        $query = BranchFloor::with(['branch', 'restaurant']);

        // Apply restaurant and branch filtering
        $this->applyRestaurantBranchFilter($query, $user, $request);

        // Optional search
        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('code', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

        // Optional status filter
        if ($request->has('status') && $request->status) {
            $query->where('status', $request->status);
        }

        // Order by display_order, then name
        $floors = $query->orderBy('display_order')->orderBy('name')->get();

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $user = $request->user();
        
        // Allow admin, restaurant_owner, and branch_manager to create floors
        if (!$user || !in_array($user->role, ['admin', 'restaurant_owner', 'branch_manager'])) {
            return response()->json(['message' => 'Unauthorized. Only admins, restaurant owners, and branch managers can create floors.'], 403);
        }

        // Get restaurant and branch context
        $context = $this->getRestaurantBranchContext($user, $request);
        
        $branchId = $context['branch_id'] ?? $request->input('branch_id') ?? $user->branch_id ?? null;
        $restaurantId = $context['restaurant_id'] ?? $request->input('restaurant_id') ?? $user->restaurant_id ?? null;

        // Ensure branch_id is set for admin and restaurant owner
        if ($user->isAdmin() || $user->isRestaurantOwner()) {
            if (!$branchId) {
                return response()->json(['message' => 'Branch is required. Please select a branch.'], 422);
            }
            if (!$restaurantId) {
                return response()->json(['message' => 'Restaurant is required. Please select a restaurant.'], 422);
            }
        }

        // For branch manager, use their branch_id and restaurant_id
        if ($user->isBranchManager()) {
            if (!$branchId) {
                $branchId = $user->branch_id;
            }
            if (!$restaurantId && $user->restaurant_id) {
                $restaurantId = $user->restaurant_id;
            } elseif (!$restaurantId && $branchId) {
                // Get restaurant_id from branch
                $branch = \App\Models\Branch::find($branchId);
                if ($branch) {
                    $restaurantId = $branch->restaurant_id;
                }
            }
        }

        if (!$branchId) {
            return response()->json(['message' => 'Branch is required. Please ensure you are assigned to a branch.'], 422);
        }

        if (!$restaurantId) {
            return response()->json(['message' => 'Restaurant is required.'], 422);
        }

        // Verify branch belongs to restaurant
        $branch = \App\Models\Branch::find($branchId);
        if (!$branch || $branch->restaurant_id != $restaurantId) {
            return response()->json(['message' => 'Branch does not belong to the specified restaurant.'], 422);
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'nullable|string|max:10',
            'display_order' => 'nullable|integer|min:0',
            'status' => 'required|string|in:active,inactive',
            'description' => 'nullable|string',
            'branch_id' => 'nullable|exists:branches,id',
            'restaurant_id' => 'nullable|exists:restaurants,id',
        ]);

        // Ensure restaurant_id and branch_id are set
        $validated['restaurant_id'] = $restaurantId;
        $validated['branch_id'] = $branchId;
        $validated['display_order'] = $validated['display_order'] ?? 0;

        $floor = BranchFloor::create($validated);

        return response()->json($floor->load(['branch', 'restaurant']), 201);
    }

    /**
     * Display the specified resource.
     */
    public function show(BranchFloor $branchFloor)
    {
        $user = request()->user();
        
        // Allow admin, restaurant_owner, and branch_manager to view floors
        if (!$user || !in_array($user->role, ['admin', 'restaurant_owner', 'branch_manager'])) {
            return response()->json(['message' => 'Unauthorized. Only admins, restaurant owners, and branch managers can view floors.'], 403);
        }

        // Check access: branch manager can only view their branch's floors
        if ($user->isBranchManager()) {
            if (!$user->branch_id || $branchFloor->branch_id != $user->branch_id) {
                return response()->json(['message' => 'Unauthorized. You can only view floors in your branch.'], 403);
            }
        }

        // Check access: restaurant owner can only view their restaurant's floors
        if ($user->isRestaurantOwner()) {
            if (!$user->restaurant_id || $branchFloor->restaurant_id != $user->restaurant_id) {
                return response()->json(['message' => 'Unauthorized. You can only view floors in your restaurant.'], 403);
            }
        }

        return response()->json($branchFloor->load(['branch', 'restaurant', 'tables']));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, BranchFloor $branchFloor)
    {
        $user = $request->user();
        
        // Allow admin, restaurant_owner, and branch_manager to update floors
        if (!$user || !in_array($user->role, ['admin', 'restaurant_owner', 'branch_manager'])) {
            return response()->json(['message' => 'Unauthorized. Only admins, restaurant owners, and branch managers can update floors.'], 403);
        }

        // Refresh to ensure latest data
        $branchFloor->refresh();

        // Check access: branch manager can only update their branch's floors
        if ($user->isBranchManager()) {
            if (!$user->branch_id || $branchFloor->branch_id != $user->branch_id) {
                return response()->json(['message' => 'Unauthorized. You can only update floors in your branch.'], 403);
            }
        }

        // Check access: restaurant owner can only update their restaurant's floors
        if ($user->isRestaurantOwner()) {
            if (!$user->restaurant_id || $branchFloor->restaurant_id != $user->restaurant_id) {
                return response()->json(['message' => 'Unauthorized. You can only update floors in your restaurant.'], 403);
            }
        }

        $validated = $request->validate([
            'name' => 'sometimes|required|string|max:255',
            'code' => 'nullable|string|max:10',
            'display_order' => 'nullable|integer|min:0',
            'status' => 'sometimes|required|string|in:active,inactive',
            'description' => 'nullable|string',
        ]);

        $branchFloor->update($validated);

        return response()->json($branchFloor->load(['branch', 'restaurant']));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(BranchFloor $branchFloor)
    {
        $user = request()->user();
        
        // Allow admin, restaurant_owner, and branch_manager to delete floors
        if (!$user || !in_array($user->role, ['admin', 'restaurant_owner', 'branch_manager'])) {
            return response()->json(['message' => 'Unauthorized. Only admins, restaurant owners, and branch managers can delete floors.'], 403);
        }

        // Refresh to ensure latest data
        $branchFloor->refresh();

        // Check access: branch manager can only delete their branch's floors
        if ($user->isBranchManager()) {
            if (!$user->branch_id || $branchFloor->branch_id != $user->branch_id) {
                return response()->json(['message' => 'Unauthorized. You can only delete floors in your branch.'], 403);
            }
        }

        // Check access: restaurant owner can only delete their restaurant's floors
        if ($user->isRestaurantOwner()) {
            if (!$user->restaurant_id || $branchFloor->restaurant_id != $user->restaurant_id) {
                return response()->json(['message' => 'Unauthorized. You can only delete floors in your restaurant.'], 403);
            }
        }

        // Check if floor has tables
        if ($branchFloor->tables()->count() > 0) {
            return response()->json(['message' => 'Cannot delete floor. It has tables assigned to it. Please reassign or delete the tables first.'], 422);
        }

        $branchFloor->delete();

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