<?php

namespace App\Http\Controllers;

use App\Models\CompAction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CompActionController extends Controller
{
    /**
     * Get all CompAction records.
     */
    public function index()
    {
        $compActions = CompAction::all();  // Get all records
        return response()->json($compActions);
    }

    /**
     * Get a specific CompAction record by CA_ID.
     */
    public function show($id)
    {
        $compAction = CompAction::find($id);

        if (!$compAction) {
            return response()->json(['message' => 'Record not found'], 404);
        }

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

    /**
     * Create a new CompAction record.
     */
    public function store(Request $request)
    {
        // Validate request data
        $validator = Validator::make($request->all(), [
            'CA_Desc' => 'required|string|max:255',
            'Ca_Flag' => 'required|string|max:1',
        ]);

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

        // Create a new record
        $compAction = CompAction::create([
            'CA_Desc' => $request->input('CA_Desc'),
            'Ca_Flag' => $request->input('Ca_Flag'),
        ]);

        return response()->json($compAction, 201);
    }

    /**
     * Update a CompAction record by CA_ID.
     */
    public function update(Request $request, $id)
    {
        $compAction = CompAction::find($id);

        if (!$compAction) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        // Validate request data
        $validator = Validator::make($request->all(), [
            'CA_Desc' => 'required|string|max:255',
            'Ca_Flag' => 'required|string|max:1',
        ]);

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

        // Update the record
        $compAction->update([
            'CA_Desc' => $request->input('CA_Desc'),
            'Ca_Flag' => $request->input('Ca_Flag'),
        ]);

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

    /**
     * Delete a CompAction record by CA_ID.
     */
    public function destroy($id)
    {
        $compAction = CompAction::find($id);

        if (!$compAction) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        $compAction->delete();  // Delete the record
        return response()->json(['message' => 'Deleted successfully']);
    }
}
