<?php

namespace App\Http\Controllers\Modules\MasterData;

use App\Http\Controllers\Controller;
use App\Http\Traits\HasRoleViews;
use App\Models\ConversionProcess;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

/**
 * Unified ConversionProcess Controller
 *
 * Handles conversion process type management for all roles.
 * Views are automatically resolved based on the logged-in user's role.
 */
class ConversionProcessController extends Controller
{
    use HasRoleViews;

    /**
     * Display the conversion process management page
     */
    public function index()
    {
        return $this->roleView('master.conversion_processes');
    }

    /**
     * Get conversion process list for DataTable/AJAX
     */
    public function list(): JsonResponse
    {
        $processes = ConversionProcess::all();
        return response()->json(['data' => $processes]);
    }

    /**
     * Get a single conversion process for editing
     */
    public function show(int $id): JsonResponse
    {
        $process = ConversionProcess::find($id);

        if (!$process) {
            return response()->json(['error' => 'Process not found'], 404);
        }

        return response()->json($process);
    }

    /**
     * Store a newly created conversion process
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'process_name' => 'required|string|max:255|unique:conversion_processes,process_name',
        ]);

        ConversionProcess::create($validated);

        return response()->json([
            'success' => true,
            'message' => 'Conversion Process added successfully',
        ]);
    }

    /**
     * Update the specified conversion process
     */
    public function update(Request $request, int $id): JsonResponse
    {
        $process = ConversionProcess::find($id);

        if (!$process) {
            return response()->json(['error' => 'Process not found'], 404);
        }

        $validated = $request->validate([
            'process_name' => 'required|string|max:255|unique:conversion_processes,process_name,' . $id,
        ]);

        $process->update($validated);

        return response()->json([
            'success' => true,
            'message' => 'Conversion Process updated successfully',
        ]);
    }

    /**
     * Remove the specified conversion process
     */
    public function destroy(int $id): JsonResponse
    {
        $process = ConversionProcess::find($id);

        if (!$process) {
            return response()->json(['error' => 'Process not found'], 404);
        }

        $process->delete();

        return response()->json([
            'success' => true,
            'message' => 'Conversion Process deleted successfully',
        ]);
    }
}
