<?php

namespace App\Http\Controllers;

use App\Models\InventoryBalance;
use App\Models\Location;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\View\View;

class StoreLocatorController extends Controller
{
    public function index(): View
    {
        $stores = Location::query()
            ->stores()
            ->active()
            ->orderBy('priority')
            ->get();

        return view('stores.index', compact('stores'));
    }

    public function availability(Request $request, Product $product)
    {
        $rows = InventoryBalance::query()
            ->with('location')
            ->where('product_id', $product->id)
            ->whereHas('location', fn ($q) => $q->active()->fulfillsOnline())
            ->get()
            ->map(fn (InventoryBalance $b) => [
                'location_id' => $b->location_id,
                'name' => $b->location->name,
                'city' => $b->location->city,
                'type' => $b->location->type,
                'available' => $b->available(),
                'allows_pickup' => $b->location->allows_pickup,
                'fulfills_online' => $b->location->fulfills_online,
            ])
            ->filter(fn ($row) => $row['available'] > 0)
            ->values();

        return response()->json([
            'success' => true,
            'online_available' => $product->onlineAvailableStock(),
            'data' => $rows,
        ]);
    }
}
