<?php

namespace App\Http\Controllers;

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

class PollActionController extends Controller
{
    /**
     * Get all PollAction records.
     */
    public function index()
    {
        $pollActions = PollAction::with('pollBook')->get();
        return response()->json($pollActions);
    }

    /**
     * Get a specific PollAction record by PA_Id.
     */
    public function show($id)
    {
        $pollAction = PollAction::with('pollBook')->find($id);

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

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

    /**
     * Create a new PollAction record.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'PA_Desc'   => 'required|string|max:500',
            'Poll_Id'   => 'required|integer|exists:poll_book,Poll_Id',
            'PA_Sr'     => 'required|integer',
        ]);

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

        $pollAction = PollAction::create([
            'PA_Desc'   => $request->input('PA_Desc'),
            'Poll_Id'   => $request->input('Poll_Id'),
            'PA_Sr'     => $request->input('PA_Sr'),
        ]);

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

    /**
     * Update a PollAction record by PA_Id.
     */
    public function update(Request $request, $id)
    {
        $pollAction = PollAction::find($id);

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

        $validator = Validator::make($request->all(), [
            'PA_Desc'   => 'required|string|max:500',
            'Poll_Id'   => 'required|integer|exists:poll_book,Poll_Id',
            'PA_Sr'     => 'required|integer',
        ]);

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

        $pollAction->update([
            'PA_Desc'   => $request->input('PA_Desc'),
            'Poll_Id'   => $request->input('Poll_Id'),
            'PA_Sr'     => $request->input('PA_Sr'),
        ]);

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

    /**
     * Delete a PollAction record by PA_Id.
     */
    public function destroy($id)
    {
        $pollAction = PollAction::find($id);

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

        $pollAction->delete();
        return response()->json(['message' => 'Deleted successfully']);
    }
}
