<?php

namespace App\Http\Controllers\Filament;

use App\Http\Controllers\Controller;
use App\Models\OrdenProduccion;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class OrdenProduccionController extends Controller
{
    public function changeState(Request $request, OrdenProduccion $orden)
    {
        $data = $request->validate([
            'state' => ['required', 'in:en_corte,en_confeccion,en_tintoreria,en_acabados,finalizada'],
        ]);

        try {
            $orden->update(['estado' => $data['state']]);
            return response()->json(['ok' => true, 'state' => $data['state']]);
        } catch (ValidationException $e) {
            return response()->json(['ok' => false, 'message' => $e->getMessage()], 422);
        } catch (\Exception $e) {
            return response()->json(['ok' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function advance(Request $request, OrdenProduccion $orden)
    {
        try {
            $orden->avanzarEstado();
            return response()->json(['ok' => true, 'state' => $orden->estado]);
        } catch (ValidationException $e) {
            return response()->json(['ok' => false, 'message' => $e->getMessage()], 422);
        } catch (\Exception $e) {
            return response()->json(['ok' => false, 'message' => $e->getMessage()], 500);
        }
    }
}
