<?php

namespace App\Http\Controllers;

use App\Models\Pond;
use App\Models\WaterChangeLog;
use Illuminate\Http\Request;

class WaterChangeController extends Controller
{
    public function create(Request $request)
    {
        $ponds = Pond::where('status', '!=', 'decommissioned')
            ->orderBy('pond_code')
            ->get();
        $selectedPondId = $request->integer('pond_id') ?: null;

        return view('water-changes.create', compact('ponds', 'selectedPondId'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'pond_id' => 'required|exists:ponds,id',
            'change_date' => 'required|date|before_or_equal:today',
            'change_type' => 'required|in:partial,full',
            'percentage_changed' => 'nullable|numeric|min:1|max:100',
            'volume_changed_litres' => 'nullable|numeric|min:0',
            'reason' => 'nullable|string|max:255',
            'notes' => 'nullable|string|max:2000',
        ]);

        $pond = Pond::findOrFail($validated['pond_id']);

        WaterChangeLog::create(array_merge($validated, [
            'farm_id' => 1,
            'cycle_id' => $pond->activeCycle?->id,
            'logged_by' => auth()->id(),
        ]));

        return redirect()->route('ponds.show', [$pond, '#tab-water'])
            ->with('success', 'Water change logged successfully.');
    }

    public function destroy(WaterChangeLog $waterChangeLog)
    {
        $pond = $waterChangeLog->pond;
        $waterChangeLog->delete();

        return back()->with('success', 'Water change record deleted.');
    }
}
