<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Process;
use App\Models\ProductType;
use Illuminate\Http\Request;

class ProcessController extends Controller
{
    // Return the Blade view with necessary data
    public function index()
    {
        $productTypes = ProductType::select('id', 'name')->get();
        return view('admin.master.process', compact('productTypes'));
    }

    // Return process data for the DataTable (API)
    public function api()
    {
        $processes = Process::with('productType')->get();
        return response()->json(['data' => $processes]);
    }

    // Store a new process
    public function store(Request $request)
    {
        $request->validate([
            'product_type_id' => 'required|exists:product_types,id',
            'name' => 'required|string|max:255',
            'order' => 'required|integer'
        ]);

        Process::create($request->all());

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

    // Show a single process (used for editing)
    public function show($id)
    {
        $process = Process::findOrFail($id);
        return response()->json($process);
    }

    // Update an existing process
    public function update(Request $request, $id)
    {
        $request->validate([
            'product_type_id' => 'required|exists:product_types,id',
            'name' => 'required|string|max:255',
            'order' => 'required|integer'
        ]);

        $process = Process::findOrFail($id);
        $process->update($request->all());

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

    // Delete a process
    public function destroy($id)
    {
        $process = Process::findOrFail($id);
        $process->delete();

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