<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Warehouse;
use Illuminate\Http\Request;

class WarehouseController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $query = Warehouse::where('status', 'active');
        
        // Filter by restaurant/branch for non-admin users
        if ($user && !$user->isAdmin()) {
            if ($user->isRestaurantOwner() && $user->restaurant_id) {
                $query->where('restaurant_id', $user->restaurant_id);
            } elseif ($user->isBranchManager() && $user->branch_id) {
                $query->where('id', $user->branch_id);
            } elseif ($user->branch_id) {
                $query->where('id', $user->branch_id);
            } elseif ($user->warehouse_id) {
                $query->where('id', $user->warehouse_id);
            }
        }
        
        // Filter by restaurant if provided
        if ($request->has('restaurant_id')) {
            $query->where('restaurant_id', $request->restaurant_id);
        }
        
        $warehouses = $query->orderBy('name')
            ->get(['id', 'name', 'code', 'logo', 'restaurant_id']);
        
        // Transform to include full logo URL
        $warehouses = $warehouses->map(function($warehouse) {
            if ($warehouse->logo) {
                $warehouse->logo_url = url($warehouse->logo);
            }
            return $warehouse;
        });
        
        return response()->json($warehouses);
    }
}
