<?php

namespace App\Http\Controllers\APIs;

use App\Http\Controllers\Controller;
use App\Http\Requests\ConferenceFormRequest;
use App\Models\Conference;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ConferenceController extends Controller
{
    // 🟢 Define constants for reusable strings
    private const ERROR_NOT_FOUND = 'Conference form not found';
    private const SUCCESS_SUBMIT = 'Form Submitted Successfully, Thank You!';
    private const SUCCESS_UPDATE = 'Conference form updated successfully!';
    private const SUCCESS_DELETE = 'Conference form deleted successfully!';
    private const ERROR_USER_EXIST = 'Email Already Used By Another Person or You!';

    // 🟢 GET ALL CONFERENCE FORMS
    public function index()
    {
        $conferences = Conference::all();

        if ($conferences->isEmpty()) {
            return response()->json(['message' => 'No conference forms found'], 404);
        }

        return response()->json($conferences, 200);
    }

    // 🟢 CREATE NEW CONFERENCE FORM
    public function register(ConferenceFormRequest $request)
{
    try {
        // 🟢 Check if email exists
        if (Conference::where('email', $request->email)->exists()) {
            $status = 409; // HTTP 409 Conflict
            $response = ['error' => self::ERROR_USER_EXIST];
        } else {
            // 🟢 Create new conference registration
            $conference = Conference::create($request->validated());
            $status = 201; // HTTP 201 Created
            $response = [
                'message' => self::SUCCESS_SUBMIT,
                'data' => $conference
            ];
        }
    } catch (QueryException $e) {
        // 🟢 Handle duplicate email error (MySQL 1062)
        $status = ($e->errorInfo[1] == 1062) ? 409 : 500;
        $response = ['error' => self::ERROR_USER_EXIST];
    } catch (\Exception $e) {
        // 🟢 Log unexpected errors
        Log::error('Conference Registration Error:', [
            'message' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);
        $status = 500; // HTTP 500 Internal Server Error
        $response = [
            'error' => 'Failed to create conference form',
            'message' => $e->getMessage()
        ];
    }

    // 🟢 Unified return statement
    return response()->json($response, $status);
}

    // 🟢 GET A SINGLE CONFERENCE FORM BY ID
    public function show($id)
    {
        $conference = Conference::find($id);

        if (!$conference) {
            return response()->json(['error' => self::ERROR_NOT_FOUND], 404);
        }

        return response()->json($conference, 200);
    }

    // 🟢 UPDATE CONFERENCE FORM
    public function update(ConferenceFormRequest $request, $id)
{
    try {
        // ✅ Log received request data
        \Log::info("🔍 Update request data: ", $request->all());

        // ✅ Find the conference record
        $conference = Conference::find($id);
        if (!$conference) {
            return response()->json(['error' => self::ERROR_NOT_FOUND], 404);
        }

        // ✅ Log before updating
        \Log::info("🔄 Before Update: ", $conference->toArray());

        // ✅ Perform the update
        $conference->update($request->validated());

        // ✅ Log after updating
        \Log::info("✅ After Update: ", $conference->toArray());

        return response()->json([
            'message' => self::SUCCESS_UPDATE,
            'data' => $conference
        ], 200);
    } catch (\Exception $e) {
        \Log::error("🚨 Update Failed: " . $e->getMessage());

        return response()->json([
            'error' => 'Failed to update conference form',
            'message' => $e->getMessage()
        ], 500);
    }
}


    // 🟢 DELETE CONFERENCE FORM
    public function destroy($id)
    {
        $conference = Conference::find($id);

        if (!$conference) {
            return response()->json(['error' => self::ERROR_NOT_FOUND], 404);
        }

        $conference->delete();

        return response()->json(['message' => self::SUCCESS_DELETE], 200);
    }
}
