<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Twilio\Rest\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    // public function __construct()
    // {
    //     $this->middleware('guest');
    // }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'phone' => ['required', 'string', 'max:255','unique:users'],
            'address' => ['required', 'string'],
            'password' => ['required', 'string', 'min:5', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\Models\User
     */

      // Custom register redirection
    protected function registered(Request $request, $user)
    {
        return redirect()->route('verify.form')->with(['phone' => $user->phone]);
    }

    protected function create(array $data)
    {

        /* Get credentials from .env */
        $token = getenv("TWILIO_AUTH_TOKEN");
        $twilio_sid = getenv("TWILIO_SID");
        $twilio_verify_sid = getenv("TWILIO_VERIFY_SID");
        $twilio = new Client($twilio_sid, $token);
        $twilio->verify->v2->services($twilio_verify_sid)
            ->verifications
            ->create($data['phone'], "sms");
        $user  = User::create([
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'email' => $data['email'],
            'phone' => $data['phone'],
            'address' => $data['address'],
            'password' => Hash::make($data['password']),
        ]);
        return $user;
    }

    public function verifyuser(Request $request)
    {
        // dd("veift");
        $data = $request->validate([
            'verification_code' => ['required', 'numeric'],
            'phone' => ['required', 'string'],
        ]);
        /* Get credentials from .env */
        $token = getenv("TWILIO_AUTH_TOKEN");
        $twilio_sid = getenv("TWILIO_SID");
        $twilio_verify_sid = getenv("TWILIO_VERIFY_SID");
       
        try {

            $twilio = new Client($twilio_sid, $token);
            $verification = $twilio->verify->v2->services($twilio_verify_sid)
            ->verificationChecks
            ->create(['code' => $data['verification_code'], 'to' => $data['phone']]);
        
            if ($verification->valid) {
            
                $user = User::where('phone', $data['phone'])->first();
                $user->update(['isVerified' => true]);
    
                // Re-authenticate the user to refresh session
                Auth::login($user, true);
                
                return redirect()->route('home')->with(['message' => 'Phone number verified']);
            }
            return back()->with(['phone' => $data['phone'], 'error' => 'Invalid verification code entered!']);
        }
        catch (\Exception $e) {
            \Log::error("Twilio Error: " . $e->getMessage());
            return back()->with(['phone' => $data['phone'], 'error' => 'An error occurred while verifying the code. Please try again.']);
        }
    }

    public function resend_otp(Request $request)
    {   
        $data = $request->validate([
            'phone' => ['required', 'string'],
        ]);
        $number = $request->phone;
        $token = getenv("TWILIO_AUTH_TOKEN");
        $twilio_sid = getenv("TWILIO_SID");
        $twilio_verify_sid = getenv("TWILIO_VERIFY_SID");
        $twilio = new Client($twilio_sid, $token);
        $twilio->verify->v2->services($twilio_verify_sid)
            ->verifications
            ->create($data['phone'], "sms");
        return response()->json(['status' => 'OTP resent successfully.']); 
    }

    public function change_phone_number(Request $request)
    {
        $data = Validator::make($request->all(),[
            'phone'=>  ['required', 'string', 'unique:users'],
        ]);

        if ($data->fails()){
            return redirect('verify')->with('error',"Phone Number already exists");
        }
        else{
            $user = User::where('id', Auth()->User()->id)->first();

        $user->update([
            'phone' => $request->phone,
        ]);

        $number = $request->phone;
        $token = getenv("TWILIO_AUTH_TOKEN");
        $twilio_sid = getenv("TWILIO_SID");
        $twilio_verify_sid = getenv("TWILIO_VERIFY_SID");
        $twilio = new Client($twilio_sid, $token);
        $twilio->verify->v2->services($twilio_verify_sid)
            ->verifications
            ->create($request->phone, "sms");
        return redirect('verify')->with('message',"Phone Number Updated and Verification code is sent");

        }
    }
}
