<?php

namespace App\Http\Controllers;

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

class UnitMemLinkController extends Controller
{
    public function index()
    {
        $unitMemLinks = UnitMemLink::with(['unit', 'user', 'society', 'relation'])->get();
        return response()->json([
            'status' => 'success',
            'message' => 'Unit member links retrieved successfully',
            'data' => $unitMemLinks
        ], 200);
    }

    public function show($id)
    {
        $unitMemLink = UnitMemLink::with(['unit', 'user', 'society', 'relation'])->find($id);
        if (!$unitMemLink) {
            return response()->json([
                'status' => 'error',
                'message' => 'Unit member link not found'
            ], 404);
        }

        return response()->json([
            'status' => 'success',
            'message' => 'Unit member link retrieved successfully',
            'data' => $unitMemLink
        ], 200);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'SocId' => 'nullable|exists:society_master,SocId',
            'SU_ID' => 'nullable|exists:soc_units,SU_ID',
            'U_Id' => 'nullable|exists:users_master,U_Id',
            'Status' => 'nullable|string|max:1|in:A,I',
            'Reg_Date' => ['nullable', 'regex:/^\d{2}\/\d{2}\/\d{4}$/', function ($attribute, $value, $fail) {
                try {
                    Carbon::createFromFormat('d/m/Y', $value);
                } catch (\Exception $e) {
                    $fail('The registration date must be a valid date in dd/mm/yyyy format.');
                }
            }],
            'EntryConfirm' => 'nullable|string|max:1|in:Y,N',
            'Spl_Category' => 'nullable|in:0,1',
            'Us_Admin' => 'nullable|in:0,1', // Added validation for Us_Admin
            'MemRel_Id' => 'nullable|exists:relation_master,MemRel_Id', // Added validation for MemRel_Id
            'PrivecyMode' => 'nullable|in:0,1', // Added validation for PrivecyMode
        ], [
            'SocId.exists' => 'The selected society does not exist.',
            'SU_ID.exists' => 'The selected unit does not exist.',
            'U_Id.exists' => 'The selected user does not exist.',
            'Status.in' => 'Status must be A (active) or I (inactive).',
            'EntryConfirm.in' => 'Entry confirm must be Y (confirmed) or N (not confirmed).',
            'Spl_Category.in' => 'Special category must be 0 (no special category) or 1 (in special category).',
            'Us_Admin.in' => 'Us_Admin must be 0 or 1.',
            'MemRel_Id.exists' => 'The selected relation does not exist.',
            'PrivecyMode.in' => 'PrivecyMode must be 0 or 1.',
        ]);

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

        try {
            $data = $validator->validated();
            $unitMemLink = UnitMemLink::create($data);
            $unitMemLink->load(['unit', 'user', 'society']);
            return response()->json([
                'status' => 'success',
                'message' => 'Unit member link created successfully',
                'data' => $unitMemLink
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An unexpected error occurred while creating the unit member link: ' . $e->getMessage()
            ], 500);
        }
    }


    public function update(Request $request, $id)
    {
        $unitMemLink = UnitMemLink::find($id);
        if (!$unitMemLink) {
            return response()->json([
                'status' => 'error',
                'message' => 'Unit member link not found'
            ], 404);
        }

        $validator = Validator::make($request->all(), [
            'SocId' => 'nullable|exists:society_master,SocId',
            'SU_ID' => 'nullable|exists:soc_units,SU_ID',
            'U_Id' => 'nullable|exists:users_master,U_Id',
            'Status' => 'nullable|string|max:1|in:A,I',
            'Reg_Date' => ['nullable', 'regex:/^\d{2}\/\d{2}\/\d{4}$/', function ($attribute, $value, $fail) {
                try {
                    Carbon::createFromFormat('d/m/Y', $value);
                } catch (\Exception $e) {
                    $fail('The registration date must be a valid date in dd/mm/yyyy format.');
                }
            }],
            'EntryConfirm' => 'nullable|string|max:1|in:Y,N',
            'Spl_Category' => 'nullable|in:0,1',
            'Us_Admin' => 'nullable|in:0,1', // Added validation for Us_Admin
            'MemRel_Id' => 'nullable|exists:relation_master,MemRel_Id', // Added validation for MemRel_Id
            'PrivecyMode' => 'nullable|in:0,1', // Added validation for PrivecyMode
        ], [
            'SocId.exists' => 'The selected society does not exist.',
            'SU_ID.exists' => 'The selected unit does not exist.',
            'U_Id.exists' => 'The selected user does not exist.',
            'Status.in' => 'Status must be A (active) or I (inactive).',
            'EntryConfirm.in' => 'Entry confirm must be Y (confirmed) or N (not confirmed).',
            'Spl_Category.in' => 'Special category must be 0 (no special category) or 1 (in special category).',
            'Us_Admin.in' => 'Us_Admin must be 0 or 1.',
            'MemRel_Id.exists' => 'The selected relation does not exist.',
            'PrivecyMode.in' => 'PrivecyMode must be 0 or 1.',
        ]);

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

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

    public function destroy($id)
    {
        $unitMemLink = UnitMemLink::find($id);
        if (!$unitMemLink) {
            return response()->json([
                'status' => 'error',
                'message' => 'Unit member link not found'
            ], 404);
        }

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