<?php

namespace App\Http\Controllers;

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

class PBUnitController extends Controller
{
    public function index()
    {
        $pbUnits = PBUnit::with('pbType')->get();
        return response()->json([
            'status' => 'success',
            'message' => 'Postbox units retrieved successfully',
            'data' => $pbUnits
        ], 200);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'PBT_ID' => 'required|exists:pb_types,PBT_ID',
            'PB_NO' => 'required|integer|min:1|max:999',
        ], [
            'PBT_ID.required' => 'The postbox type ID is required.',
            'PBT_ID.exists' => 'The selected postbox type does not exist.',
            'PB_NO.required' => 'The number of postbox units is required.',
            'PB_NO.integer' => 'The number of postbox units must be an integer.',
            'PB_NO.min' => 'The number of postbox units must be at least 1.',
            'PB_NO.max' => 'The number of postbox units may not exceed 999.',
        ]);

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

        try {
            $data = $validator->validated();
            $pbtId = $data['PBT_ID'];
            $count = $data['PB_NO'];

            // Get the last PB_NO for this PBT_ID
            $lastUnit = PBUnit::where('PBT_ID', $pbtId)->orderBy('PB_NO', 'desc')->first();
            $startNumber = $lastUnit ? (int)substr($lastUnit->PB_NO, 2) + 1 : 1;

            $units = [];
            for ($i = 0; $i < $count; $i++) {
                $number = $startNumber + $i;
                $pbNo = 'PB' . str_pad($number, 3, '0', STR_PAD_LEFT);
                $units[] = [
                    'PBT_ID' => $pbtId,
                    'PB_NO' => $pbNo,
                    'created_at' => now(),
                    'updated_at' => now(),
                ];
            }

            DB::table('pb_units')->insert($units);
            $createdUnits = PBUnit::where('PBT_ID', $pbtId)
                ->whereIn('PB_NO', array_column($units, 'PB_NO'))
                ->with('pbType')
                ->get();

            return response()->json([
                'status' => 'success',
                'message' => "Created $count postbox unit(s) successfully",
                'data' => $createdUnits
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An unexpected error occurred while creating the postbox units: ' . $e->getMessage()
            ], 500);
        }
    }

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

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

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

        $validator = Validator::make($request->all(), [
            'PBT_ID' => 'required|exists:pb_types,PBT_ID',
            'PB_NO' => 'required|string|max:5',
        ], [
            'PBT_ID.required' => 'The postbox type ID is required.',
            'PBT_ID.exists' => 'The selected postbox type does not exist.',
            'PB_NO.required' => 'The postbox number is required.',
            'PB_NO.string' => 'The postbox number must be a string.',
            'PB_NO.max' => 'The postbox number may not exceed 5 characters.',
        ]);

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

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

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

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