<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Mail\RegistrationOtpMail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Models\User; 
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class RegisterController extends Controller
{
   
    public function registration_post(Request $request)
    {
        Log::info('Received request for registration.', $request->all());
        $validator = Validator::make($request->all(), [
            'referral_id'      => 'nullable|exists:users,user_id',
            'name'             => 'required|string|max:255',
            'email'            => 'required|email|unique:users,email',
            'phone_number'     => 'required|unique:users,phone_number',
            'password'         => 'required',
            'confirm_password' => 'required|same:password',
        ]);
    
        if ($validator->fails()) {
            Log::error('Validation errors:', $validator->errors()->toArray());
            return response()->json([
                'status'  => 'error',
                'message' => 'Validation errors',
                'code'    => 422,
                'data'  => $validator->errors()
            ], 422);
        }
    
     
        do {
            $UserID = 'ADZ' . rand(1000, 9999);
        } while (User::where('user_id', $UserID)->exists());

        $user               = new User();
        $user->user_id      = $UserID;
        $user->name         = $request->name;
        $user->referral_id  = $request->referral_id;
        $user->email        = $request->email;
        $user->phone_number = $request->phone_number;
        $user->password     = Hash::make($request->password);
        $user->save();
    
        Log::info('User registered successfully:', $user->toArray());
    
        return response()->json([
            'status'  => 'success',
            'message' => 'User registered successfully!',
            'code'    => 200,
        ], 200);
    }
    


} 