<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Farmer; // Use the correct model name
use Illuminate\Support\Facades\Validator;

class FarmController extends Controller
{
    /**
     * Store a newly created farm.
     */
 public function store(Request $request)
{
    // Validate incoming data
    $validator = Validator::make($request->all(), [
        'scheduled_id' => 'required|integer',
        'client_id' => 'required|integer',
        'areaSize' => 'required|numeric|min:0',
        'perimeter' => 'required',
        'PropartieLocation' => 'required|string',
        'coordinates' => 'required|json',
    ]);

    if ($validator->fails()) {
        return response()->json([
            'message' => 'Validation failed',
            'errors' => $validator->errors(),
        ], 422);
    }

    $clientId = $request->client_id;

    // Check if client already has a record in the first visits table
    $existingFirstVisit = \DB::table('scheduled_visitsReport')
        ->where('client_id', $clientId)
        ->first();

    if ($existingFirstVisit) {
        // Client already has a first visit → insert into the second visits table
        $insertedId = \DB::table('scheduledSecond_visitsReport')->insertGetId([
            'firstvisite' => $existingFirstVisit->id,
            'scheduled_id' => $request->scheduled_id,
            'client_id' => $clientId,
            'areaSize' => $request->areaSize,
            'perimeter' => $request->perimeter,
            'PropartieLocation' => $request->PropartieLocation,
            'coordinates' => $request->coordinates,
            'createdby' => auth()->id(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json([
            'message' => 'Second visit record saved successfully',
            'visit_type' => 'second',
            'record_id' => $insertedId,
        ], 201);

    } else {
        // No existing first visit → insert into first visits table
        $insertedId = \DB::table('scheduled_visitsReport')->insertGetId([
            'scheduled_id' => $request->scheduled_id,
            'client_id' => $clientId,
            'areaSize' => $request->areaSize,
            'perimeter' => $request->perimeter,
            'PropartieLocation' => $request->PropartieLocation,
            'coordinates' => $request->coordinates,
            'createdby' => auth()->id(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json([
            'message' => 'First visit record saved successfully',
            'visit_type' => 'first',
            'record_id' => $insertedId,
        ], 201);
    }
}

}