<?php

namespace App\Http\Controllers;

use App\Models\LockerUnit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class LockerUnitController extends Controller
{
    public function index()
    {
        $lockerUnits = LockerUnit::with('lockerType')->get();
        return response()->json([
            'status' => 'success',
            'message' => 'Locker units retrieved successfully',
            'data' => $lockerUnits
        ], 200);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'Lk_Id' => 'required|exists:locker_types,Lk_Id',
            'LS_No' => 'required|integer|min:1|max:9999',
        ], [
            'Lk_Id.required' => 'The locker type ID is required.',
            'Lk_Id.exists' => 'The selected locker type does not exist.',
            'LS_No.required' => 'The number of locker units is required.',
            'LS_No.integer' => 'The number of locker units must be an integer.',
            'LS_No.min' => 'The number of locker units must be at least 1.',
            'LS_No.max' => 'The number of locker units cannot exceed 9999.',
        ]);

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

        try {
            DB::beginTransaction();
            $data = $validator->validated();
            $lkId = $data['Lk_Id'];
            $count = $data['LS_No'];

            // Find the highest existing LS_No for this Lk_Id
            $lastLocker = LockerUnit::where('Lk_Id', $lkId)
                ->orderByRaw('CAST(SUBSTRING(LS_No, 2) AS UNSIGNED) DESC')
                ->first();
            $startNumber = $lastLocker ? (int)substr($lastLocker->LS_No, 1) + 1 : 1;

            $lockerUnits = [];
            for ($i = 0; $i < $count; $i++) {
                $number = $startNumber + $i;
                if ($number > 9999) {
                    DB::rollBack();
                    return response()->json([
                        'status' => 'error',
                        'message' => 'Cannot generate more locker numbers; maximum limit (L9999) reached.'
                    ], 422);
                }
                $lsNo = 'L' . str_pad($number, 3, '0', STR_PAD_LEFT);
                $lockerUnits[] = LockerUnit::create([
                    'Lk_Id' => $lkId,
                    'LS_No' => $lsNo,
                ]);
            }

            DB::commit();
            LockerUnit::whereIn('LS_ID', array_column($lockerUnits, 'LS_ID'))->with('lockerType')->get();
            return response()->json([
                'status' => 'success',
                'message' => "$count locker unit(s) created successfully",
                'data' => $lockerUnits
            ], 201);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'status' => 'error',
                'message' => 'An unexpected error occurred while creating the locker units: ' . $e->getMessage()
            ], 500);
        }
    }

    public function show($id)
    {
        $lockerUnit = LockerUnit::with('lockerType')->find($id);
        if (!$lockerUnit) {
            return response()->json([
                'status' => 'error',
                'message' => 'Locker unit not found'
            ], 404);
        }

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

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

        $validator = Validator::make($request->all(), [
            'Lk_Id' => 'required|exists:locker_types,Lk_Id',
            'LS_No' => 'required|string|max:5|regex:/^L[0-9]{3,4}$/',
        ], [
            'Lk_Id.required' => 'The locker type ID is required.',
            'Lk_Id.exists' => 'The selected locker type does not exist.',
            'LS_No.required' => 'The locker number is required.',
            'LS_No.string' => 'The locker number must be a string.',
            'LS_No.max' => 'The locker number may not be greater than 5 characters.',
            'LS_No.regex' => 'The locker number must start with L followed by 3 or 4 digits (e.g., L001 or L0001).',
        ]);

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

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

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

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