<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\LabPricingRequest;
use App\Models\Lab;
use App\Models\LabTestPrice;
use App\Models\TestCatalog;

class LabPricingController extends Controller
{
    public function edit(Lab $lab)
    {
        $tests = TestCatalog::query()->where('is_active', true)->orderBy('name')->get();

        $overrides = LabTestPrice::query()
            ->where('lab_id', $lab->id)
            ->get()
            ->keyBy('test_id');

        return view('admin.lab_pricing.edit', compact('lab','tests','overrides'));
    }

    public function update(LabPricingRequest $request, Lab $lab)
    {
        $prices = $request->validated()['prices'];

        foreach ($prices as $testId => $price) {
            // If empty string/null => remove override and fallback to default
            if ($price === null || $price === '') {
                LabTestPrice::where('lab_id', $lab->id)->where('test_id', $testId)->delete();
                continue;
            }

            LabTestPrice::updateOrCreate(
                ['lab_id' => $lab->id, 'test_id' => $testId],
                ['price' => (int)$price]
            );
        }

        return redirect()->route('admin.labs.pricing.edit', $lab)->with('success', 'Lab pricing saved.');
    }
}
