<?php

namespace App\Http\Controllers;

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

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

    /**
     * Get a specific PollCategory record by Pc_ID.
     */
    public function show($id)
    {
        $pollCategory = PollCategory::find($id);

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

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

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

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

        $pollCategory = PollCategory::create([
            'Pc_Desc' => $request->input('Pc_Desc'),
        ]);

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

    /**
     * Update a PollCategory record by Pc_ID.
     */
    public function update(Request $request, $id)
    {
        $pollCategory = PollCategory::find($id);

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

        $validator = Validator::make($request->all(), [
            'Pc_Desc' => 'required|string|max:255',
        ]);

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

        $pollCategory->update([
            'Pc_Desc' => $request->input('Pc_Desc'),
        ]);

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

    /**
     * Delete a PollCategory record by Pc_ID.
     */
    public function destroy($id)
    {
        $pollCategory = PollCategory::find($id);

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

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