<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\DutyPoint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class DutyPointController extends Controller
{
    public function index()
    {
        $dutyPoints = DutyPoint::all();
        return response()->json([
            'status' => 200,
            'data' => $dutyPoints
        ]);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'DP_Desc' => 'required|string|max:25'
        ]);

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

        $dutyPoint = DutyPoint::create([
            'DP_Desc' => $request->DP_Desc
        ]);

        return response()->json([
            'status' => 201,
            'message' => 'Duty Point Created Successfully',
            'data' => $dutyPoint
        ], 201);
    }

    public function show($id)
    {
        $dutyPoint = DutyPoint::find($id);
        if ($dutyPoint) {
            return response()->json([
                'status' => 200,
                'data' => $dutyPoint
            ]);
        }
        return response()->json([
            'status' => 404,
            'message' => 'Duty Point Not Found'
        ], 404);
    }

    public function update(Request $request, $id)
    {
        $dutyPoint = DutyPoint::find($id);
        if (!$dutyPoint) {
            return response()->json([
                'status' => 404,
                'message' => 'Duty Point Not Found'
            ], 404);
        }

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

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

        $dutyPoint->update([
            'DP_Desc' => $request->DP_Desc
        ]);

        return response()->json([
            'status' => 200,
            'message' => 'Duty Point Updated Successfully',
            'data' => $dutyPoint
        ]);
    }

    public function destroy($id)
    {
        $dutyPoint = DutyPoint::find($id);
        if ($dutyPoint) {
            $dutyPoint->delete();
            return response()->json([
                'status' => 200,
                'message' => 'Duty Point Deleted Successfully'
            ]);
        }
        return response()->json([
            'status' => 404,
            'message' => 'Duty Point Not Found'
        ], 404);
    }
}
