<?php

namespace App\Http\Controllers\Api\Helpers;

trait RestaurantBranchFilterTrait
{
    /**
     * Apply restaurant and branch filtering to query based on user role
     */
    protected function applyRestaurantBranchFilter($query, $user, $request)
    {
        // Admin can see all data BUT must select restaurant and branch first
        if ($user && $user->isAdmin()) {
            // Admin MUST select both restaurant_id and branch_id to see orders
            // If not selected, return empty result
            if ($request->has('restaurant_id') && $request->restaurant_id && $request->has('branch_id') && $request->branch_id) {
                $query->where('restaurant_id', $request->restaurant_id);
                $query->where('branch_id', $request->branch_id);
            } else {
                // No restaurant/branch selected - return empty result (admin must select both)
                $query->whereRaw('1 = 0');
            }
            // Also support warehouse_id for backward compatibility (map to branch_id)
            if ($request->has('warehouse_id') && $request->warehouse_id && !$request->has('branch_id')) {
                $query->where('branch_id', $request->warehouse_id);
            }
            return $query;
        }

        // Inventory managers see all data for their restaurant
        if ($user && $user->isInventoryManager() && $user->restaurant_id) {
            $query->where('restaurant_id', $user->restaurant_id);
            
            // Filter by branch if selected or provided (optional for inventory managers)
            $branchId = $request->input('branch_id') 
                ?? session('selected_branch_id')
                ?? $request->header('X-Branch-Id');
            
            if ($branchId) {
                $query->where('branch_id', $branchId);
            }
            return $query;
        }

        // Restaurant owners see all data for their restaurant
        if ($user && $user->isRestaurantOwner() && $user->restaurant_id) {
            $query->where('restaurant_id', $user->restaurant_id);
            
            // Filter by branch if selected or provided - REQUIRED for proper filtering
            $branchId = $request->input('branch_id') 
                ?? session('selected_branch_id')
                ?? $request->header('X-Branch-Id');
            
            if ($branchId) {
                // Verify branch belongs to restaurant owner's restaurant
                $branch = \App\Models\Branch::find($branchId);
                if ($branch && $branch->restaurant_id === $user->restaurant_id) {
                    $query->where('branch_id', $branchId);
                } else {
                    // Branch doesn't belong to restaurant or doesn't exist - return empty result
                    $query->whereRaw('1 = 0');
                }
            } else {
                // No branch selected - return empty result (restaurant owner must select branch)
                $query->whereRaw('1 = 0');
            }
            return $query;
        }

        // Branch managers and branch cashiers see only their branch data
        if ($user && ($user->isBranchManager() || $user->isBranchCashier()) && $user->branch_id) {
            // Ensure branch relationship is loaded
            if (!$user->relationLoaded('branch')) {
                $user->load('branch');
            }
            
            $query->where('branch_id', $user->branch_id);
            if ($user->branch && $user->branch->restaurant_id) {
                $query->where('restaurant_id', $user->branch->restaurant_id);
            }
            return $query;
        }

        // Staff and other roles - use branch_id if available
        if ($user && $user->branch_id) {
            $query->where('branch_id', $user->branch_id);
            if ($user->branch && $user->branch->restaurant_id) {
                $query->where('restaurant_id', $user->branch->restaurant_id);
            }
        } else {
            // No access - return empty result
            $query->whereRaw('1 = 0');
        }

        return $query;
    }

    /**
     * Get restaurant_id and branch_id for creating/updating records
     * Priority: Request input > Session > User's direct relationship
     */
    protected function getRestaurantBranchContext($user, $request)
    {
        $context = [
            'restaurant_id' => null,
            'branch_id' => null,
        ];

        // Get restaurant_id from session first (set during login)
        $sessionRestaurantId = session('restaurant_id');
        $sessionBranchId = session('branch_id');

        // For admin: use request input or session
        if ($user->isAdmin()) {
            $context['restaurant_id'] = $request->input('restaurant_id') 
                ?? $sessionRestaurantId
                ?? null;
            $context['branch_id'] = $request->input('branch_id') 
                ?? $sessionBranchId
                ?? null;
            return $context;
        }

        // For inventory managers: use user's restaurant_id
        if ($user->isInventoryManager()) {
            $context['restaurant_id'] = $user->restaurant_id ?? null;
            $context['branch_id'] = $request->input('branch_id') 
                ?? session('selected_branch_id')
                ?? $sessionBranchId
                ?? $request->header('X-Branch-Id')
                ?? null;
        }
        // For restaurant owners: use session restaurant_id or user's restaurant_id
        elseif ($user->isRestaurantOwner()) {
            $context['restaurant_id'] = $sessionRestaurantId 
                ?? $user->restaurant_id
                ?? null;
            $context['branch_id'] = $request->input('branch_id') 
                ?? session('selected_branch_id')
                ?? $sessionBranchId
                ?? $request->header('X-Branch-Id')
                ?? null;
        } 
        // For branch managers, branch cashiers, and staff: get from session or user's branch
        elseif ($user->isBranchManager() || $user->isBranchCashier() || $user->branch_id) {
            // Priority: Session > User's branch_id
            $context['branch_id'] = $sessionBranchId 
                ?? $user->branch_id
                ?? null;
            
            // Get restaurant_id: Priority: Session > Branch relationship > User's restaurant_id
            $context['restaurant_id'] = $sessionRestaurantId;
            if (!$context['restaurant_id'] && $user->branch) {
                $context['restaurant_id'] = $user->branch->restaurant_id;
            }
            if (!$context['restaurant_id'] && $user->restaurant_id) {
                $context['restaurant_id'] = $user->restaurant_id;
            }
            
            // Ensure branch_id is set for branch managers, cashiers, and sub-users
            if (!$context['branch_id'] && $user->branch_id) {
                $context['branch_id'] = $user->branch_id;
            }
        } 
        // Backward compatibility with warehouse_id
        elseif ($user->warehouse_id) {
            $warehouse = \App\Models\Warehouse::find($user->warehouse_id);
            if ($warehouse) {
                $context['branch_id'] = $warehouse->id; // warehouse_id maps to branch_id
                if ($warehouse->restaurant_id) {
                    $context['restaurant_id'] = $warehouse->restaurant_id;
                }
            }
        }

        return $context;
    }

    /**
     * Get restaurant_id from session or user context
     * This is a helper method for controllers that need restaurant_id
     */
    protected function getRestaurantId($user, $request = null)
    {
        // Priority: Request input > Session > User's restaurant_id > User's branch restaurant_id
        if ($request && $request->has('restaurant_id') && $request->restaurant_id) {
            return $request->restaurant_id;
        }

        $sessionRestaurantId = session('restaurant_id');
        if ($sessionRestaurantId) {
            return $sessionRestaurantId;
        }

        if ($user->restaurant_id) {
            return $user->restaurant_id;
        }

        if ($user->branch_id && $user->branch) {
            return $user->branch->restaurant_id;
        }

        return null;
    }
}

