<?php

namespace App\Http\Controllers\UserAuth;

use App\Http\Controllers\Controller;
use App\Mail\ResetMail;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;

use App\Services\WhmcsServices;
use Illuminate\Support\Facades\DB;

class ForgotPasswordController extends Controller
{
    protected WhmcsServices $whmcsServices;

    public function __construct(WhmcsServices $whmcsServices)
    {
        $this->whmcsServices = $whmcsServices;
    }


    public function create(Request $request)
    {
        return view('auth.forgot-password', ['request' => $request]);
    }

    public function store(Request $request)
    {
        $this->validate($request , [
            'email' => 'required',
             'g-recaptcha-response' => 'required|recaptchav3:password_email,0.9'
        ]); 

        $user = User::where('email' , $request->email)->first();
        $token = str()->random(60);
        $url = config('app.url')."/Servlet/PasswordReset.py/".$token.'?email='.$request->email;
        
        if($user != null){
            // Store token in password_resets table
            $this->updateOrInsertPasswordReset($request->email, $token, $url);
            return $this->redirection(true);
        }else{
            $response = $this->whmcsServices->getClientByEmail($request->email);
            if($response['result'] == 'error'){
                return $this->redirection(false);
            }
            $createdUser = $this->insertUser($request, $response);
            if($createdUser){
                // Store token in password_resets table
                $this->updateOrInsertPasswordReset($request->email, $token, $url);
                return $this->redirection(true);
            }
        }
    }







    protected function redirection($status){
        if($status){
            return redirect('/Servlet/forgotPassword.py')->with('success_message' , 'Please check your email for instructions on how to reset your password. If you don’t see the email in your inbox, be sure to check your spam or junk folder as well.');
        }else{
            return redirect('/Servlet/forgotPassword.py')->with('error_message' , 'No account was found associated with that email address. Please check for any errors or try a different email.');
        }
    }

    protected function sendResetMail($email, $url){
        Mail::send(new ResetMail($email , $url));
    }

    protected function updateOrInsertPasswordReset($email, $token, $url){
        DB::table('password_resets')->updateOrInsert(
            ['email' => $email],
            [
                'token' => Hash::make($token),
                'created_at' => Carbon::now()
            ] 
        );

        $this->sendResetMail($email, $url);
    }


    protected function insertUser($request, $data) {
        $dates = Carbon::now()->format('Y-m-d');
        $date = explode('-', $dates);
        $year = $date[0];
        $month = $date[1];
        $day = $date[2];
        $user = User::create([
            'name' => $data['firstname'],
            'lastname' => $data['lastname'],
            'email' => $request->email,
            'country' => $data['country'],
            'address' => $data['address1'],
            'city' => $data['city'],
            'state' => $data['state'],
            'post_code' => $data['postcode'],
            'phone_number' => $data['phonenumber'],
            'company' => $data['companyname'],
            'google2fa_secret' => '0',
            'googlef2_status' => '0',
            'google_date' => '0',
            'password' => Hash::make('$2y$10$UiBz1XHpJ8WoHiBdEir9ZuzsPfEf/d/J6x3ttxMpj4EF583yg1a8m'),
            'otp' => md5('$2y$10$UiBz1XHpJ8WoHiBdEir9ZuzsPfEf/d/J6x3ttxMpj4EF583yg1a8m'),
            'role' => 'User',
            'ip_address' => $request->ip(),
            'register_year' => $year,
            'register_month' => $month,
            'register_day' => $day
        ]);
        return $user;
    }


}
