<?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 register_send_otp(Request $request)
{
    Log::info('hi');
    $validator = Validator::make($request->all(), [
        'name'           => 'required|string|max:255',
        'email'          => 'required|email|unique:users,email',
        'phone_number'   => 'required|string|max:10',
        'address'        => 'required|string|max:255',
        'role'           => 'required|string|in:user,admin',
        'password'       => 'required|string|min:8|confirmed', 
    ]);

    if ($validator->fails()) {
        Log::error('Validation errors:', $validator->errors()->toArray());
        return response()->json([
            'status'  => 'error',
            'data'    => null,
            'message' => 'Validation errors',
            'code'    => 422,
            'errors'  => $validator->errors()
        ], 422);
    }

    do {
        $letters = Str::random(2);
        $numbers = str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $randomId = strtoupper($letters . $numbers);
    } while (User::where('user_id', $randomId)->exists());

    $otp = rand(100000, 999999);

    $user                 = new User();
    $user->name           = $request->name;
    $user->email          = $request->email;
    $user->phone_number   = $request->phone_number;
    $user->address        = $request->address;
    $user->role           = $request->role;
    $user->password       = Hash::make($request->password);
    $user->otp            = Crypt::encryptString($otp);
    $user->user_id        = $randomId;
    $user->otp_expires_at = Carbon::now()->addMinutes(10);
    $user->otp_verified   = 0;
    $user->is_verified    = 0;
    $user->save();
    if (!$user->save()) {
        Log::error('Failed to save user:', $user->toArray());
        return response()->json([
            'status'  => 'error',
            'message' => 'Failed to register user.',
            'code'    => 500
        ], 500);
    }

    Mail::to($user->email)->send(new RegistrationOtpMail($otp));

    return response()->json([
        'status'  => 'success',
        'message' => 'User registered successfully,
                      Please verify your email with the OTP sent.',
        'code'    => 200,
    ], 200);
}


public function register_verify_otp(Request $request)
{
    Log::info('Verify OTP Request:', $request->all());

    $validator = Validator::make($request->all(), [
        'email'    => 'required|email',
        'otp'      => 'required|integer',
    ]);

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

    $user = User::where('email', $request->email)->first();

    if (!$user) {
        return response()->json([
            'status'  => 'error',
            'message' => 'User not found.',
            'code'    => 404
        ], 404);
    }

    try {
        $decryptedOtp = Crypt::decryptString($user->otp);
        Log::info('Decrypted OTP:', ['otp' => $decryptedOtp]);
    } catch (\Exception $e) {
        return response()->json([
            'status'  => 'error',
            'message' => 'Invalid OTP encryption.',
            'code'    => 400
        ], 400);
    }

    if ((int)$decryptedOtp !== (int)$request->otp) {
        return response()->json([
            'status'  => 'error',
            'message' => 'Invalid OTP.',
            'code'    => 400
        ], 400);
    }

    if ($user->otp_expires_at < Carbon::now()) {
        return response()->json([
            'status'  => 'error',
            'message' => 'OTP expired.',
            'code'    => 400
        ], 400);
    }

    $user->otp_verified = 1;
    $user->is_verified  = 1;
    $user->save();

    return response()->json([
        'status'  => 'success',
        'message' => 'OTP verified successfully and registered!',
    ], 200);
}

}