<?php

namespace App\Http\Controllers;

use App\Models\LockerAllotment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;

class LockerAllotmentController extends Controller
{
    public function index()
    {
        $lockerAllotments = LockerAllotment::with(['lockerUnit', 'societyUnit', 'feeConfig', 'assignedBy'])->get();
        return response()->json([
            'status' => 'success',
            'message' => 'Locker allotments retrieved successfully',
            'data' => $lockerAllotments
        ], 200);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'LS_ID' => 'required|exists:locker_units,LS_ID',
            'Status' => 'required|string|in:A,I',
            'ActiveDate' => ['required', 'regex:/^\d{2}\/\d{2}\/\d{4}$/', function ($attribute, $value, $fail) {
                try {
                    Carbon::createFromFormat('d/m/Y', $value);
                } catch (\Exception $e) {
                    $fail('The active date must be a valid date in dd/mm/yyyy format.');
                }
            }],
            'ValidDate' => ['nullable', 'regex:/^\d{2}\/\d{2}\/\d{4}$/', function ($attribute, $value, $fail) {
                if ($value) {
                    try {
                        Carbon::createFromFormat('d/m/Y', $value);
                    } catch (\Exception $e) {
                        $fail('The valid date must be a valid date in dd/mm/yyyy format.');
                    }
                }
            }],
            'SU_ID' => 'required|exists:soc_units,SU_ID',
            'FC_Id' => 'required|exists:fees_config,FC_Id',
            'Asgn_By' => 'required|exists:users_master,U_Id',
        ], [
            'LS_ID.required' => 'The locker unit ID is required.',
            'LS_ID.exists' => 'The selected locker unit does not exist.',
            'Status.required' => 'The status is required.',
            'Status.in' => 'Status must be A (active) or I (inactive).',
            'ActiveDate.required' => 'The active date is required.',
            'SU_ID.required' => 'The society unit ID is required.',
            'SU_ID.exists' => 'The selected society unit does not exist.',
            'FC_Id.required' => 'The fee configuration ID is required.',
            'FC_Id.exists' => 'The selected fee configuration does not exist.',
            'Asgn_By.required' => 'The assigned by user ID is required.',
            'Asgn_By.exists' => 'The selected user does not exist.',
        ]);

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

        try {
            $data = $validator->validated();
            $lockerAllotment = LockerAllotment::create($data);
            $lockerAllotment->load(['lockerUnit', 'societyUnit', 'feeConfig', 'assignedBy']);
            return response()->json([
                'status' => 'success',
                'message' => 'Locker allotment created successfully',
                'data' => $lockerAllotment
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An unexpected error occurred while creating the locker allotment: ' . $e->getMessage()
            ], 500);
        }
    }

    public function show($id)
    {
        $lockerAllotment = LockerAllotment::with(['lockerUnit', 'societyUnit', 'feeConfig', 'assignedBy'])->find($id);
        if (!$lockerAllotment) {
            return response()->json([
                'status' => 'error',
                'message' => 'Locker allotment not found'
            ], 404);
        }

        return response()->json([
            'status' => 'success',
            'message' => 'Locker allotment retrieved successfully',
            'data' => $lockerAllotment
        ], 200);
    }

    public function update(Request $request, $id)
    {
        $lockerAllotment = LockerAllotment::find($id);
        if (!$lockerAllotment) {
            return response()->json([
                'status' => 'error',
                'message' => 'Locker allotment not found'
            ], 404);
        }

        $validator = Validator::make($request->all(), [
            'LS_ID' => 'required|exists:locker_units,LS_ID',
            'Status' => 'required|string|in:A,I',
            'ActiveDate' => ['required', 'regex:/^\d{2}\/\d{2}\/\d{4}$/', function ($attribute, $value, $fail) {
                try {
                    Carbon::createFromFormat('d/m/Y', $value);
                } catch (\Exception $e) {
                    $fail('The active date must be a valid date in dd/mm/yyyy format.');
                }
            }],
            'ValidDate' => ['nullable', 'regex:/^\d{2}\/\d{2}\/\d{4}$/', function ($attribute, $value, $fail) {
                if ($value) {
                    try {
                        Carbon::createFromFormat('d/m/Y', $value);
                    } catch (\Exception $e) {
                        $fail('The valid date must be a valid date in dd/mm/yyyy format.');
                    }
                }
            }],
            'SU_ID' => 'required|exists:soc_units,SU_ID',
            'FC_Id' => 'required|exists:fees_config,FC_Id',
            'Asgn_By' => 'required|exists:users_master,U_Id',
        ], [
            'LS_ID.required' => 'The locker unit ID is required.',
            'LS_ID.exists' => 'The selected locker unit does not exist.',
            'Status.required' => 'The status is required.',
            'Status.in' => 'Status must be A (active) or I (inactive).',
            'ActiveDate.required' => 'The active date is required.',
            'SU_ID.required' => 'The society unit ID is required.',
            'SU_ID.exists' => 'The selected society unit does not exist.',
            'FC_Id.required' => 'The fee configuration ID is required.',
            'FC_Id.exists' => 'The selected fee configuration does not exist.',
            'Asgn_By.required' => 'The assigned by user ID is required.',
            'Asgn_By.exists' => 'The selected user does not exist.',
        ]);

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

        try {
            $data = $validator->validated();
            $lockerAllotment->update($data);
            $lockerAllotment->load(['lockerUnit', 'societyUnit', 'feeConfig', 'assignedBy']);
            return response()->json([
                'status' => 'success',
                'message' => 'Locker allotment updated successfully',
                'data' => $lockerAllotment
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An unexpected error occurred while updating the locker allotment.'
            ], 500);
        }
    }

    public function destroy($id)
    {
        $lockerAllotment = LockerAllotment::find($id);
        if (!$lockerAllotment) {
            return response()->json([
                'status' => 'error',
                'message' => 'Locker allotment not found'
            ], 404);
        }

        try {
            $lockerAllotment->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Locker allotment deleted successfully'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An unexpected error occurred while deleting the locker allotment.'
            ], 500);
        }
    }
}
