<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\InputsActivitiesCostsSeed;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class InputsActivitiesCostsSeedController extends Controller
{
public function index()
{
    $seeds = InputsActivitiesCostsSeed::with('creator')->latest()->paginate(45);
    return response()->json([
        'status' => 1,
        'rows' => $seeds
    ]);
}

  public function seedtofertilize()
    {
        $seeds = InputsActivitiesCostsSeed::with('creator')
        ->whereNotExists(function ($query) {
            $query->select(DB::raw(1))
                  ->from('orders')
                  ->whereColumn('orders.seed_id', 'inputsActivitiesCostsSeeds.id')
                  ->whereExists(function ($subQuery) {
                      $subQuery->select(DB::raw(1))
                          ->from('order_items')
                          ->whereColumn('order_items.order_id', 'orders.id')
                          ->where('order_items.category_id', 0);
                  });
        })
        ->latest()
        ->paginate(45);

    return response()->json([
        'status' => 1,
        'rows' => $seeds
    ]);
    }

  public function seedsphytosataire()
{
    $seeds = InputsActivitiesCostsSeed::with('creator')
        ->whereNotExists(function ($query) {
            $query->select(DB::raw(1))
                  ->from('orders')
                  ->whereColumn('orders.seed_id', 'inputsActivitiesCostsSeeds.id')
                  ->whereExists(function ($subQuery) {
                      $subQuery->select(DB::raw(1))
                          ->from('order_items')
                          ->whereColumn('order_items.order_id', 'orders.id')
                          ->where('order_items.category_id', 1);
                  });
        })
        ->latest()
        ->paginate(45);

    return response()->json([
        'status' => 1,
        'rows' => $seeds
    ]);
}


public function store(Request $request)
{
    $rules = [
        'seeds_name'   => 'required|string|max:150',
        'seeds_source' => 'nullable|string|max:1000',
        'description'  => 'nullable|string|max:2000', 
        'harvestDurationMonths' => 'required|integer|min:1|max:60',
        'status'       => 'nullable|string|in:active,inactive', 
    ];

    $messages = [
        'seeds_name.required' => 'The seed name is required.',
        'seeds_name.max'      => 'The seed name may not be greater than 150 characters.',
        'seeds_source.max'    => 'The seed source may not be greater than 1000 characters.',
        'description.max'     => 'The description may not be greater than 2000 characters.',
        'harvestDurationMonths.required' => 'Harvest duration is required.',
        'harvestDurationMonths.integer'  => 'Harvest duration must be an integer.',
        'harvestDurationMonths.min'      => 'Harvest duration must be at least 1 month.',
        'harvestDurationMonths.max'      => 'Harvest duration may not exceed 60 months.',
        'status.in'           => 'Status must be either active or inactive.',
    ];

    $validator = Validator::make($request->all(), $rules, $messages);

    if ($validator->fails()) {
        return response()->json([
            'status' => 0,
            'error'  => $validator->errors()
        ], 400);
    }

    // Check for duplicate seeds_name (case-insensitive by default)
    $exists = InputsActivitiesCostsSeed::where('seeds_name', $request->seeds_name)->exists();

    if ($exists) {
        return response()->json([
            'status' => 0,
            'error'  => ['seeds_name' => ['The seed name already exists.']]
        ], 409); // HTTP 409 Conflict
    }

    $seed = new InputsActivitiesCostsSeed();
    $seed->seeds_name   = $request->input('seeds_name');
    $seed->seeds_source = $request->input('seeds_source');
    $seed->description  = $request->input('description', '');
    $seed->harvestDurationMonths = $request->input('harvestDurationMonths');
    $seed->status       = $request->input('status', 'active');
    $seed->created_by   = $request->user()->id;
    $seed->save();

    $seed->load('creator'); // optional eager load if needed

    return response()->json([
        'status' => 1,
        'row'    => $seed
    ], 201);
}

public function update(Request $request, $id)
{
    $rules = [
        'seeds_name'   => 'required|string|max:150',
        'seeds_source' => 'nullable|string|max:1000',
        'description'  => 'nullable|string|max:2000',
        'harvestDurationMonths' => 'required|integer|min:1|max:60', // Fixed: max:60 instead of max:2
        'status'       => 'nullable|string|in:active,inactive',
    ];

    $messages = [
        'seeds_name.required' => 'The seed name is required.',
        'seeds_name.max'      => 'The seed name may not be greater than 150 characters.',
        'seeds_source.max'    => 'The seed source may not be greater than 1000 characters.',
        'description.max'     => 'The description may not be greater than 2000 characters.',
        'harvestDurationMonths.required' => 'Harvest duration is required.',
        'harvestDurationMonths.integer'  => 'Harvest duration must be an integer.',
        'harvestDurationMonths.min'      => 'Harvest duration must be at least 1 month.',
        'harvestDurationMonths.max'      => 'Harvest duration may not exceed 60 months.',
        'status.in'           => 'Status must be either active or inactive.',
    ];

    $validator = Validator::make($request->all(), $rules, $messages);

    if ($validator->fails()) {
        return response()->json([
            'status' => 0,
            'error'  => $validator->errors()
        ], 400);
    }

    $seed = InputsActivitiesCostsSeed::find($id);

    if (!$seed) {
        return response()->json([
            'status'  => 0,
            'message' => 'Seed not found.'
        ], 404);
    }

    // Check for duplicate seeds_name (excluding current record)
    $exists = InputsActivitiesCostsSeed::where('seeds_name', $request->seeds_name)
                                       ->where('id', '!=', $id)
                                       ->exists();

    if ($exists) {
        return response()->json([
            'status' => 0,
            'error'  => ['seeds_name' => ['The seed name already exists.']]
        ], 409);
    }

    $seed->seeds_name   = $request->input('seeds_name');
    $seed->seeds_source = $request->input('seeds_source');
    $seed->description  = $request->input('description', '');
    $seed->harvestDurationMonths = $request->input('harvestDurationMonths'); // Added this line
    $seed->status       = $request->input('status', 'active');
    $seed->updated_by   = $request->user()->id;
    $seed->save();

    // Optionally eager load updater info
    $seed->load('creator');

    return response()->json([
        'status' => 1,
        'row'    => $seed
    ], 200);
}
}
