<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Session;
use App\Helper\Helper;

class PhoneVerificationController extends Controller
{
    
public function submitPhone(Request $request)
{
     $rawPhone = preg_replace('/\D/', '', $request->phone);
    $body = [
        'phone'        => $rawPhone,
        'country_code' => $request->country_code,
    ];

    $url = env('API_URL').'submit-phone';
    $response = Helper::PostApi($url, $body);

    if ($response) {
       if (!empty($response->success) && $response->success == 1) {
    session([
        'verify_phone' => [
            'phone'           => $response->data->phone,
            'phone_hash'      => Hash::make($response->data->raw_phone),
            'phone_encrypted' => Crypt::encryptString($response->data->raw_phone),
            'otp'             => Hash::make($response->data->otp),
            'country_code'    =>$request->country_code
        ],
        'phone_modal' => 'verify_phone',
    ]);

    return back()->with('success', $response->message);
} else {
    session(['phone_modal' => 'enter_phone']);   // reopen enter modal
    return back()->withErrors(['error' => $response->message ?? 'Something went wrong']);
}

    }

    return back()->withErrors(['error' => 'Unable to connect to server.']);
}

    public function editPhone()
    {
        session()->forget(['verify_phone', 'phone_modal']);
        return redirect()->back()->with('phone_modal', 'enter_phone');
    }

    public function resendOtp()
    {
        $sessionData = session('verify_phone');

        if (!$sessionData || !isset($sessionData['phone_encrypted'], $sessionData['phone'])) {
            return back()->withErrors(['error' => 'No phone number found to resend OTP.']);
        }

        // Decrypt raw phone to resend OTP
        try {
            $rawPhone = Crypt::decryptString($sessionData['phone_encrypted']);
        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to verify phone number for resending OTP.']);
        }
 $body = [
        'user_id' => Session::get('id'),
        'phone'        => $rawPhone,
                'country_code' => $sessionData['country_code'],

    ];
            $url = env('API_URL').'submit-phone';

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



        if ($result->success) {
            // Update OTP hash in session with new OTP hash
            session()->put('verify_phone.otp', Hash::make($result->data->otp));
            return back()->with('success', 'OTP resent successfully to ' . $sessionData['phone']);
        }

        return back()->withErrors(['error' => 'Failed to resend OTP. Please try again.']);
    }

public function verifyPhone(Request $request)
{
    $code = $request->input('digit1') .
            $request->input('digit2') .
            $request->input('digit3') .
            $request->input('digit4') .
            $request->input('digit5') .
            $request->input('digit6');

    // Validate code format
    if (!preg_match('/^\d{6}$/', $code)) {
        session()->flash('phone_modal', 'verify_phone');
        return back()->withErrors(['code' => 'OTP must be a 6-digit number.']);
    }

    $sessionData = session('verify_phone');

    if (
        !$sessionData ||
        !isset($sessionData['otp'], $sessionData['phone_hash'], $sessionData['phone_encrypted'], $sessionData['phone'])
    ) {
        return back()->withErrors(['code' => 'No verification process found.']);
    }

    // Build payload for backend API
    $payload = [
        'code'            => $code,
        'phone'           => $sessionData['phone'],
        'phone_hash'      => $sessionData['phone_hash'],
        'phone_encrypted' => $sessionData['phone_encrypted'],
        'otp'             => $sessionData['otp'],
        'user_id'         => Session::get('id'),
    ];

    $url = env('API_URL') . '/verify-phone';
    $response = Helper::PostApi($url, $payload);

    if ($response) {
        // Cast response into object (if not already)
        $data = (object) $response;

        if (!empty($data->success)) {
            // Clear session on success
            session()->forget(['verify_phone', 'phone_modal']);
            return back()->with('success', $data->message ?? 'Phone verified successfully.');
        } else {
            session()->flash('phone_modal', 'verify_phone');
            return back()->withErrors(['code' => $data->message ?? 'Verification failed.']);
        }
    }

    return back()->withErrors(['code' => 'Unable to connect to server.']);
}



    public function closeModal()
    {
        session()->forget(['verify_phone', 'phone_modal']);
        return response()->json(['status' => 'success']);
    }
}
