<?php

namespace App\Http\Controllers;

use App\Models\Pond;
use App\Models\ProductionCycle;
use App\Models\SpeciesConfig;
use App\Models\StockingRecord;
use Illuminate\Http\Request;

class ProductionCycleController extends Controller
{
    public function create(Pond $pond)
    {
        if ($pond->activeCycle) {
            return redirect()->route('ponds.show', $pond)
                ->with('error', 'This pond already has an active cycle. Close it before starting a new one.');
        }

        $species = SpeciesConfig::where('farm_id', 1)->where('is_active', true)->pluck('name');
        $nextCycleNumber = $pond->cycles()->max('cycle_number') + 1;

        return view('cycles.create', compact('pond', 'species', 'nextCycleNumber'));
    }

    public function store(Request $request, Pond $pond)
    {
        if ($pond->activeCycle) {
            return redirect()->route('ponds.show', $pond)
                ->with('error', 'Pond already has an active cycle.');
        }

        $validated = $request->validate([
            'stocking_date' => ['required', 'date', 'before_or_equal:today'],
            'species' => ['required', 'array', 'min:1'],
            'species.*.name' => ['required', 'string', 'max:100'],
            'species.*.quantity' => ['required', 'integer', 'min:1'],
            'species.*.avg_weight_g' => ['required', 'numeric', 'min:0.1'],
            'species.*.cost_per_fingerling' => ['required', 'numeric', 'min:0'],
            'species.*.transport_cost' => ['nullable', 'numeric', 'min:0'],
            'species.*.supplier_name' => ['required', 'string', 'max:100'],
            'species.*.supplier_contact' => ['nullable', 'string', 'max:100'],
            'species.*.strain_variety' => ['nullable', 'string', 'max:100'],
            'species.*.notes' => ['nullable', 'string'],
            'target_weight_g' => ['nullable', 'numeric', 'min:1'],
        ]);

        $cycle = ProductionCycle::create([
            'farm_id' => 1,
            'pond_id' => $pond->id,
            'cycle_number' => $pond->cycles()->max('cycle_number') + 1,
            'start_date' => $validated['stocking_date'],
            'status' => 'open',
        ]);

        foreach ($validated['species'] as $sr) {
            StockingRecord::create([
                'pond_id' => $pond->id,
                'cycle_id' => $cycle->id,
                'stocking_date' => $validated['stocking_date'],
                'species' => $sr['name'],
                'strain_variety' => $sr['strain_variety'] ?? null,
                'quantity' => $sr['quantity'],
                'avg_weight_g' => $sr['avg_weight_g'],
                'supplier_name' => $sr['supplier_name'],
                'supplier_contact' => $sr['supplier_contact'] ?? null,
                'cost_per_fingerling' => $sr['cost_per_fingerling'],
                'transport_cost' => $sr['transport_cost'] ?? 0,
                'notes' => $sr['notes'] ?? null,
                'logged_by' => auth()->id(),
            ]);
        }

        $pond->update(['status' => 'active']);

        return redirect()->route('cycles.show', [$pond, $cycle])
            ->with('success', 'Production cycle started. Good luck!');
    }

    public function show(Pond $pond, ProductionCycle $cycle)
    {
        $cycle->load([
            'stockingRecords',
            'samplingRecords' => fn ($q) => $q->latest('sample_date'),
            'mortalityLogs' => fn ($q) => $q->latest('log_date'),
            'treatmentLogs' => fn ($q) => $q->latest('treatment_date'),
            'harvestRecord.salesRecords',
            'feedingLogs' => fn ($q) => $q->latest('feed_date')->limit(20),
        ]);

        $feedByBrand = $cycle->feedingLogs()
            ->selectRaw('feed_brand, feed_type, SUM(quantity_kg) as total_kg')
            ->groupBy('feed_brand', 'feed_type')
            ->orderByDesc('total_kg')
            ->get();

        $fcr = null;
        $latestSampling = $cycle->samplingRecords->first();
        if ($latestSampling && $cycle->total_fed_kg > 0) {
            $weightGained = (float) $latestSampling->estimated_biomass_kg
                - $cycle->stockingRecords->sum('total_weight_kg');
            $fcr = $weightGained > 0 ? round($cycle->total_fed_kg / $weightGained, 2) : null;
        }

        return view('cycles.show', compact('pond', 'cycle', 'feedByBrand', 'fcr', 'latestSampling'));
    }

    public function close(Request $request, Pond $pond, ProductionCycle $cycle)
    {
        if ($cycle->status !== 'open') {
            return back()->with('error', 'Cycle is already closed.');
        }
        if (! $cycle->harvestRecord) {
            return back()->with('error', 'A harvest record must exist before closing the cycle.');
        }

        $cycle->update([
            'status' => 'closed',
            'end_date' => now()->toDateString(),
        ]);
        $pond->update(['status' => 'fallow']);

        return redirect()->route('cycles.show', [$pond, $cycle])
            ->with('success', 'Production cycle closed. Pond is now fallow.');
    }
}
