<?php

namespace App\Http\Controllers;

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

class ParkingMasterController extends Controller
{
    public function index()
    {
        $parkingMasters = ParkingMaster::with(['sociResoBook', 'parkingSlot', 'socUnit', 'assignedBy'])->get();
        return response()->json(['data' => $parkingMasters], 200);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'SCP_Desc' => 'required|string|max:100',
            'Status' => 'required|string|size:1',
            'ActiveDate' => 'required|date',
            'ValidDate' => 'required|date',
            'SR_Id' => 'nullable|exists:soci_reso_books,SR_Id',
            'PS_ID' => 'nullable|exists:parking_slots,PS_ID',
            'SU_ID' => 'nullable|exists:soc_units,SU_ID',
            'Asgn_By' => 'nullable|exists:users_master,U_Id',
        ]);

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

        $parkingMaster = ParkingMaster::create($request->all());
        return response()->json(['data' => $parkingMaster], 201);
    }

    public function show($id)
    {
        $parkingMaster = ParkingMaster::with(['sociResoBook', 'parkingSlot', 'socUnit', 'assignedBy'])->findOrFail($id);
        return response()->json(['data' => $parkingMaster], 200);
    }

    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'SCP_Desc' => 'sometimes|required|string|max:100',
            'Status' => 'sometimes|required|string|size:1',
            'ActiveDate' => 'sometimes|required|date',
            'ValidDate' => 'sometimes|required|date',
            'SR_Id' => 'nullable|exists:soci_reso_books,SR_Id',
            'PS_ID' => 'nullable|exists:parking_slots,PS_ID',
            'SU_ID' => 'nullable|exists:soc_units,SU_ID',
            'Asgn_By' => 'nullable|exists:users_master,U_Id',
        ]);

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

        $parkingMaster = ParkingMaster::findOrFail($id);
        $parkingMaster->update($request->all());
        return response()->json(['data' => $parkingMaster], 200);
    }

    public function destroy($id)
    {
        $parkingMaster = ParkingMaster::findOrFail($id);
        $parkingMaster->delete();
        return response()->json(['message' => 'Parking master deleted successfully'], 200);
    }
}
