<?php

namespace App\Http\Controllers;

use App\Models\PayGradeMaster;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class PayGradeMasterController extends Controller
{
    /**
     * List with pagination
     */
    public function index(Request $request): JsonResponse
    {
        $data = PayGradeMaster::with('commission')
            ->orderBy('PGM_Id', 'desc')
            ->paginate(20);

        return response()->json([
            'success' => true,
            'data' => $data
        ]);
    }

    /**
     * All records (no pagination)
     */
    public function all(): JsonResponse
    {
        $data = PayGradeMaster::with('commission')
            ->orderBy('PGM_Id')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $data
        ]);
    }

    /**
     * Store
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'PC_Id' => 'required|exists:pay_comm_master,PC_Id',
            'GPay_Amount' => 'required|numeric'
        ]);

        $data = PayGradeMaster::create($request->all());

        return response()->json([
            'success' => true,
            'message' => 'Pay Grade created successfully',
            'data' => $data
        ]);
    }

    /**
     * Show
     */
    public function show($id): JsonResponse
    {
        $data = PayGradeMaster::with('commission')->findOrFail($id);

        return response()->json([
            'success' => true,
            'data' => $data
        ]);
    }

    /**
     * Update
     */
    public function update(Request $request, $id): JsonResponse
    {
        $data = PayGradeMaster::findOrFail($id);

        $request->validate([
            'PC_Id' => 'required|exists:pay_comm_master,PC_Id',
            'GPay_Amount' => 'required|numeric'
        ]);

        $data->update($request->all());

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

    /**
     * Delete (Soft delete)
     */
    public function destroy($id): JsonResponse
    {
        $data = PayGradeMaster::findOrFail($id);
        $data->delete();

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