<?php

namespace App\Http\Controllers;

use App\Helper\Helper;
use Illuminate\Support\MessageBag;
use Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class ProfileController extends Controller
{
public function updateGoogleAuthenticator(Request $request)
{
    $url = env('API_URL') . '/profile/update-google-auth';

    $body = [
        'client_id' => Session::get('parentId'),
        'id'        => Session::get('id'),   // better to always take from session instead of trusting request
        'token'     => Session::get('tokenId'),
        'allow_google_authenticator' => $request->allow_google_authenticator
    ];

    try {
        $response = Helper::PostApi($url, $body);
        Log::info('reached google aauth',['response'=>$response]);
         //echo "<pre>";print_r($response);die;
                //Session::put('qrCode', $response->qr_code);
                Session::put('qrCode', !empty($response->qr_code) ? $response->qr_code : null);


        if (isset($response->success) && $response->success) {
            return response()->json($response);   // ✅ Always return JSON
        } else {
            return response()->json([
                'success' => false,
                'message' => $response->message ?? 'Failed to update Google Authenticator.'
            ], 400);
        }
    } catch (\Throwable $ex) {
        return response()->json([
            'success' => false,
            'message' => $ex->getMessage()
        ], 500);
    }
}

  public function verifyGoogleAuthenticator(Request $request)
{
    
    $url = env('API_URL') . 'profile/verify-google-auth';

    // Build OTP from frontend inputs
    $body = [
        'client_id' => Session::get('parentId'),
        'id'        => Session::get('id'),
        'token'     => Session::get('tokenId'),
        'digit1'    => $request->digit1,
        'digit2'    => $request->digit2,
        'digit3'    => $request->digit3,
        'digit4'    => $request->digit4,
        'digit5'    => $request->digit5,
        'digit6'    => $request->digit6,
    ];

    try {
        $response = Helper::PostApi($url, $body);

        if (isset($response->success) && $response->success) {
            return response()->json($response);   // ✅ Always return backend JSON
        } else {
            return response()->json([
                'success' => false,
                'message' => $response->message ?? 'Failed to verify Google Authenticator.'
            ], 400);
        }
    } catch (\Throwable $ex) {
        return response()->json([
            'success' => false,
            'message' => $ex->getMessage()
        ], 500);
    }
}
  public function updateTwoFactor(Request $request)
    {
          $request->validate([
            'id' => 'required',
            'allow_two_factor_status' => 'required|in:0,1',
        ]);
    $url = env('API_URL') . 'profile/update-two-factor';
     $body = [
        'client_id' => Session::get('parentId'),
        'id'        => Session::get('id'),   // better to always take from session instead of trusting request
        'token'     => Session::get('tokenId'),
        'allow_two_factor_status' => $request->allow_two_factor_status
    ];
      
         try {
        $response = Helper::PostApi($url, $body);
         //echo "<pre>";print_r($response);die;

        if (isset($response->success) && $response->success) {
            return response()->json($response);   // ✅ Always return JSON
        } else {
            return response()->json([
                'success' => false,
                'message' => $response->message ?? 'Failed to update status.'
            ], 400);
        }
    } catch (\Throwable $ex) {
        return response()->json([
            'success' => false,
            'message' => $ex->getMessage()
        ], 500);
    }
    }

    public function changeEmail(Request $request)
{
    $url = env('API_URL') . 'profile/change-email';
    $body = [
        'client_id' => Session::get('parentId'),
        'id'        => Session::get('id'),   // always from session
        'token'     => Session::get('tokenId'),
        'new_email' => $request->new_email
    ];
  
    try {
        $response = Helper::PostApi($url, $body);
         //echo "<pre>";print_r($response);die;

        if (isset($response->success) && $response->success) {
            // ✅ Store session values for OTP verification
            Session::put('email_change', [  // ✅ store hash
                'otp'        => $response->otp ?? null,   // assuming backend sends OTP in response
                'new_email'  => $request->new_email,
                'expires_at' => now()->addMinutes(5)->timestamp,
            ]);

            return back()->with([
                // 'success' => true,
                'message' => $response->message ?? 'OTP sent successfully.',
                'modal' => 'verify_otp'  // you can use this in JS
            ]);
        } else {
            return back()->with([
                // 'success' => false,
                'message' => $response->message ?? 'Failed to update email.'
            ], 400);
        }
    } catch (\Throwable $ex) {
        return back()->with([
            'success' => false,
            'message' => $ex->getMessage()
        ], 500);
    }
}


 public function verifyOtp(Request $request)
{
    $validator = Validator::make($request->all(), [
        'otp' => ['required', 'digits:6'],
    ]);

    if ($validator->fails()) {
        return back()->withErrors($validator)->with('modal', 'verify_otp');
    }

    $url = env('API_URL') . 'profile/verify-otp';
    $body = [
        'client_id' => Session::get('parentId'),
        'id'        => Session::get('id'),
        'token'     => Session::get('tokenId'),
        'email_change' => Session::get('email_change'), // ✅ use Session::get directly
        'otp'       => $request->otp,
    ];
//dd($body);

    try {
        $response = Helper::PostApi($url, $body);
         //echo "<pre>";print_r($response);die;

        if (isset($response->success) && $response->success) {
            // ✅ clear session
            $request->session()->forget('email_change');
            return redirect()->back()->with('success', $response->message);
        } else {
            return back()->withErrors(['otp' => $response->message ?? 'OTP verification failed'])
                         ->with('modal', $response->modal ?? 'verify_otp');
        }
    } catch (\Throwable $ex) {
        return back()->withErrors(['otp' => 'Server error: '.$ex->getMessage()])
                     ->with('modal', 'verify_otp');
    }
}

}
