<?php

namespace App\Http\Controllers;

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

class SocietyCommitteeController extends Controller
{
    public function index()
    {
        $committees = SocietyCommittee::with(['society', 'designation', 'user', 'resolution', 'block'])->get();
        return response()->json([
            'status' => 'success',
            'message' => 'Society committees retrieved successfully',
            'data' => $committees
        ], 200);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'SocId' => 'nullable|exists:society_master,SocId',
            'MemDesi_ID' => 'nullable|exists:com_desi,MemDesi_ID',
            'U_Id' => 'nullable|exists:users_master,U_Id',
            'Desi_St_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 start date must be a valid date in dd/mm/yyyy format.');
                }
            }],
            'Desi_Ed_Date' => ['nullable', 'regex:/^\d{2}\/\d{2}\/\d{4}$/', function ($attribute, $value, $fail) use ($request) {
                try {
                    $endDate = Carbon::createFromFormat('d/m/Y', $value);
                    if ($request->Desi_St_Date) {
                        $startDate = Carbon::createFromFormat('d/m/Y', $request->Desi_St_Date);
                        if ($endDate->lte($startDate)) {
                            $fail('The end date must be after the start date.');
                        }
                    }
                } catch (\Exception $e) {
                    $fail('The end date must be a valid date in dd/mm/yyyy format.');
                }
            }],
            'Status' => 'nullable|string|max:1|in:A,I',
            'SR_Id' => 'nullable|exists:soci_reso_books,SR_Id',
            'Comt_Type' => 'nullable|string|max:1|in:M,S',
            'SB_Id' => 'nullable|exists:soc_block,SB_Id',
        ], [
            'SocId.exists' => 'The selected society does not exist.',
            'MemDesi_ID.exists' => 'The selected designation does not exist.',
            'U_Id.exists' => 'The selected user does not exist.',
            'Status.in' => 'Status must be A (active) or I (inactive).',
            'Comt_Type.in' => 'Committee type must be M (main) or S (sub-committee).',
            'SR_Id.exists' => 'The selected resolution does not exist.',
            'SB_Id.exists' => 'The selected block does not exist.',
        ]);

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

        try {
            $data = $validator->validated();

            if (isset($data['Desi_St_Date'])) {
                $data['Desi_St_Date'] = Carbon::createFromFormat('d/m/Y', $data['Desi_St_Date'])->format('Y-m-d');
            }
            if (isset($data['Desi_Ed_Date'])) {
                $data['Desi_Ed_Date'] = Carbon::createFromFormat('d/m/Y', $data['Desi_Ed_Date'])->format('Y-m-d');
            }

            $committee = SocietyCommittee::create($data);
            $committee->load(['society', 'designation', 'user', 'resolution', 'block']);
            return response()->json([
                'status' => 'success',
                'message' => 'Society committee created successfully',
                'data' => $committee
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An unexpected error occurred while creating the society committee.'
            ], 500);
        }
    }

    public function show($id)
    {
        $committee = SocietyCommittee::with(['society', 'designation', 'user', 'resolution', 'block'])->find($id);
        if (!$committee) {
            return response()->json([
                'status' => 'error',
                'message' => 'Society committee not found'
            ], 404);
        }

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

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

        $validator = Validator::make($request->all(), [
            'SocId' => 'nullable|exists:society_master,SocId',
            'MemDesi_ID' => 'nullable|exists:com_desi,MemDesi_ID',
            'U_Id' => 'nullable|exists:users_master,U_Id',
            'Desi_St_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 start date must be a valid date in dd/mm/yyyy format.');
                }
            }],
            'Desi_Ed_Date' => ['nullable', 'regex:/^\d{2}\/\d{2}\/\d{4}$/', function ($attribute, $value, $fail) use ($request, $committee) {
                try {
                    $endDate = Carbon::createFromFormat('d/m/Y', $value);
                    $startDateInput = $request->Desi_St_Date ?? $committee->getRawOriginal('Desi_St_Date');
                    if ($startDateInput) {
                        $startDate = is_string($startDateInput) && strpos($startDateInput, '/') !== false
                            ? Carbon::createFromFormat('d/m/Y', $startDateInput)
                            : Carbon::parse($startDateInput);
                        if ($endDate->lte($startDate)) {
                            $fail('The end date must be after the start date.');
                        }
                    }
                } catch (\Exception $e) {
                    $fail('The end date must be a valid date in dd/mm/yyyy format.');
                }
            }],
            'Status' => 'nullable|string|max:1|in:A,I',
            'SR_Id' => 'nullable|exists:soci_reso_books,SR_Id',
            'Comt_Type' => 'nullable|string|max:1|in:M,S',
            'SB_Id' => 'nullable|exists:soc_block,SB_Id',
        ], [
            'SocId.exists' => 'The selected society does not exist.',
            'MemDesi_ID.exists' => 'The selected designation does not exist.',
            'U_Id.exists' => 'The selected user does not exist.',
            'Status.in' => 'Status must be A (active) or I (inactive).',
            'Comt_Type.in' => 'Committee type must be M (main) or S (sub-committee).',
            'SR_Id.exists' => 'The selected resolution does not exist.',
            'SB_Id.exists' => 'The selected block does not exist.',
        ]);

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

        try {
            $data = $validator->validated();

            if (isset($data['Desi_St_Date'])) {
                $data['Desi_St_Date'] = Carbon::createFromFormat('d/m/Y', $data['Desi_St_Date'])->format('Y-m-d');
            }
            if (isset($data['Desi_Ed_Date'])) {
                $data['Desi_Ed_Date'] = Carbon::createFromFormat('d/m/Y', $data['Desi_Ed_Date'])->format('Y-m-d');
            }

            $committee->update($data);
            $committee->load(['society', 'designation', 'user', 'resolution', 'block']);
            return response()->json([
                'status' => 'success',
                'message' => 'Society committee updated successfully',
                'data' => $committee
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An unexpected error occurred while updating the society committee.'
            ], 500);
        }
    }

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

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