<?php

namespace App\Http\Controllers;

use App\Models\MemberRegistration;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class MemberRegistrationController extends Controller
{
    public function register(Request $request)
    {
        try {
            $validated = $request->validate([
                'membership_plan' => 'required|in:basic,standard,premium',
                'membership_price' => 'required|numeric|min:0',
                'full_name' => 'required|string|max:255',
                'email' => 'required|email|max:255|unique:member_registrations,email',
                'phone' => 'required|string|max:20|unique:member_registrations,phone',
                'address' => 'required|string|max:500',
                'payment_method' => 'required|in:credit_card,mpesa,bank_transfer',
            ]);

            // Generate unique membership ID
            $membershipId = 'MCG-' . Str::upper(Str::random(6));

            // Start transaction
            DB::beginTransaction();

            $registration = MemberRegistration::create([
                'membership_plan' => $validated['membership_plan'],
                'membership_price' => $validated['membership_price'],
                'full_name' => $validated['full_name'],
                'email' => $validated['email'],
                'phone' => $validated['phone'],
                'address' => $validated['address'],
                'payment_method' => $validated['payment_method'],
                'membership_id' => $membershipId,
            ]);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Registration successful! Welcome to McGregor Fitness!',
                'membership_id' => $membershipId,
                'plan_name' => ucfirst($validated['membership_plan']),
                'email' => $validated['email'],
                'price' => number_format($validated['membership_price'], 2),
                'next_steps' => 'Check your email for membership details and activation instructions.'
            ]);

        } catch (\Illuminate\Validation\ValidationException $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'An error occurred during registration: ' . $e->getMessage()
            ], 500);
        }
    }
}