<?php

namespace App\Http\Controllers;

use App\Models\VineyardRow;
use App\Models\VarietyVariation;
use App\Rules\LocationCoordinates;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class VineyardRowController extends Controller
{
    /**
     * Display a listing of vineyard rows.
     */
    public function index()
    {
        $rows = VineyardRow::with('varietyVariation.grapeVariety')->paginate(15);

        return view('vineyard-rows.index', compact('rows'));
    }

    /**
     * Show the form for creating a new vineyard row.
     */
    public function create()
    {
        $varietyVariations = VarietyVariation::with('grapeVariety')->get();

        return view('vineyard-rows.create', compact('varietyVariations'));
    }

    /**
     * Store a newly created vineyard row in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'variety_variation_id' => 'nullable|integer|exists:variety_variations,id',
            'vine_count' => 'required|integer|min:1',
            'planting_year' => 'required|integer|min:1900|max:' . date('Y'),
            'area' => 'nullable|numeric|min:0',
            'location' => ['nullable', 'string', 'max:255', new LocationCoordinates()],
            'status' => 'required|in:active,inactive,replanting,discarded',
            'notes' => 'nullable|string',
        ]);

        $row = VineyardRow::create($validated);

        return redirect()->route('vineyard-rows.show', $row)
            ->with('success', 'Vineyard row created successfully.');
    }

    /**
     * Display the specified vineyard row.
     */
    public function show(VineyardRow $vineyardRow)
    {
        $vineyardRow->load('varietyVariation.grapeVariety', 'harvests');

        return view('vineyard-rows.show', compact('vineyardRow'));
    }

    /**
     * Show the form for editing the specified vineyard row.
     */
    public function edit(VineyardRow $vineyardRow)
    {
        $varietyVariations = VarietyVariation::with('grapeVariety')->get();

        return view('vineyard-rows.edit', compact('vineyardRow', 'varietyVariations'));
    }

    /**
     * Update the specified vineyard row in storage.
     */
    public function update(Request $request, VineyardRow $vineyardRow)
    {
        $validated = $request->validate([
            'variety_variation_id' => 'nullable|integer|exists:variety_variations,id',
            'vine_count' => 'required|integer|min:1',
            'planting_year' => 'required|integer|min:1900|max:' . date('Y'),
            'area' => 'nullable|numeric|min:0',
            'location' => ['nullable', 'string', 'max:255', new LocationCoordinates()],
            'status' => 'required|in:active,inactive,replanting,discarded',
            'notes' => 'nullable|string',
        ]);

        $vineyardRow->update($validated);

        return redirect()->route('vineyard-rows.show', $vineyardRow)
            ->with('success', 'Vineyard row updated successfully.');
    }

    /**
     * Remove the specified vineyard row from storage.
     */
    public function destroy(Request $request, VineyardRow $vineyardRow)
    {
        $vineyardRow->delete();

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'deleted' => $vineyardRow->id,
            ]);
        }

        return redirect()->route('vineyard-rows.index')
            ->with('success', 'Vineyard row deleted successfully.');
    }

    /**
     * Bulk delete rows from the vineyard map.
     */
    public function destroyMany(Request $request)
    {
        $validated = $request->validate([
            'rows' => 'required|array|min:1',
            'rows.*' => 'required|exists:vineyard_rows,id',
        ]);

        DB::transaction(function () use ($validated) {
            VineyardRow::whereIn('id', $validated['rows'])->delete();
        });

        return response()->json([
            'success' => true,
            'deleted' => $validated['rows'],
        ]);
    }

    /**
     * Bulk update vine counts for one or more rows.
     */
    public function updateHeadCount(Request $request)
    {
        $validated = $request->validate([
            'rows' => 'required|array|min:1',
            'rows.*.id' => 'required|exists:vineyard_rows,id',
            'rows.*.vine_count' => 'required|integer|min:0',
            'rows.*.location' => ['nullable', 'string', 'max:255', new LocationCoordinates()],
        ]);

        DB::transaction(function () use ($validated) {
            foreach ($validated['rows'] as $payload) {
                $updates = ['vine_count' => $payload['vine_count']];

                if (array_key_exists('location', $payload) && ! blank($payload['location'])) {
                    $updates['location'] = $payload['location'];
                }

                VineyardRow::whereKey($payload['id'])->update($updates);
            }
        });

        return response()->json([
            'success' => true,
            'updated' => collect($validated['rows'])->pluck('id'),
        ]);
    }

    /**
     * Add new rows to the vineyard map.
     */
    public function addRows(Request $request)
    {
        $validated = $request->validate([
            'rows' => 'required|array|min:1',
            'rows.*.location' => ['required', 'string', 'max:255', new LocationCoordinates()],
            'rows.*.vine_count' => 'nullable|integer|min:0',
        ]);

        $created = DB::transaction(function () use ($validated) {
            return collect($validated['rows'])->map(function ($payload) {
                return VineyardRow::create([
                    'location' => $payload['location'],
                    'vine_count' => $payload['vine_count'] ?? 0,
                    'status' => 'inactive',
                    'variety_variation_id' => null,
                    'planting_year' => $payload['planting_year'] ?? now()->year,
                ])->getKey();
            });
        });

        return response()->json([
            'success' => true,
            'created' => $created,
        ], 201);
    }

    /**
     * Discard plants for provided rows.
     */
    public function discard(Request $request)
    {
        $validated = $request->validate([
            'rows' => 'required|array|min:1',
            'rows.*' => 'required|exists:vineyard_rows,id',
        ]);

        DB::transaction(function () use ($validated) {
            VineyardRow::whereIn('id', $validated['rows'])->update([
                // Mark as inactive and decouple from any assigned variation
                'status' => 'inactive',
                'variety_variation_id' => null,
            ]);
        });

        return response()->json([
            'success' => true,
            'discarded' => $validated['rows'],
        ]);
    }
}
