<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Generalsetting;
use App\Models\User;
use App\Classes\GeniusMailer;
use App\Models\BankPlan;
use App\Models\Country;
use App\Models\Notification;
use App\Models\ReferralBonus;
use App\Models\Transaction;
use App\Models\UserSubscription;
use Auth;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Input;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Illuminate\Support\Str;
use Validator;
use Session;


use Illuminate\Http\JsonResponse;

class RegisterController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest');
    }

    public function showRegisterForm(){
        $data['countries'] = Country::where('status',1)->get();
        return view('user.register',$data);
    }

    public function register(Request $request)
    {
        $value = session('captcha_string');
        if ($request->codes != $value){
            return response()->json(array('errors' => [ 0 => 'Please enter Correct Capcha Code.' ]));
        }

        /* $rules = [
            'username' => 'required|alpha_dash|min:5|unique:users',
            'email' => 'required|email|max:255|unique:users',
            'phone' => 'required|min:6',
            'password' => 'required|confirmed'
        ]; */
$rules = [
    'name' => 'required|string|min:2|max:50|regex:/^[a-zA-Z\s\-]+$/',
    'username' => 'required|alpha_dash|min:5|max:30|unique:users,username',
    'email' => 'required|email|max:255|unique:users,email',
    'phone' => 'required|min:6|max:20|regex:/^[0-9\-\+\(\)\s]+$/',
    'password' => 'required|string|min:8|confirmed',
];

$messages = [
    'password.required' => 'Password is required.',
    'password.string' => 'Password must be a valid string.',
    'password.min' => 'Password must be at least 8 characters.',
    'password.confirmed' => 'Password confirmation does not match.',
    
    'username.required' => 'Username is required.',
    'username.alpha_dash' => 'Username may only contain letters, numbers, dashes and underscores.',
    'username.min' => 'Username must be at least 5 characters.',
    'username.max' => 'Username must not exceed 30 characters.',
    'username.unique' => 'This username is already taken.',

    'email.required' => 'Email is required.',
    'email.email' => 'Please enter a valid email address.',
    'email.max' => 'Email must not exceed 255 characters.',
    'email.unique' => 'This email is already registered.',

    'phone.required' => 'Phone number is required.',
    'phone.min' => 'Phone number must be at least 6 digits.',
    'phone.max' => 'Phone number must not exceed 20 digits.',
    'phone.regex' => 'Phone number format is invalid. Allowed characters: digits, spaces, dashes, parentheses, and plus sign.',


];

$validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
          return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
        }

        $gs = Generalsetting::findOrFail(1);

        $user = new User;
        $input = $request->all();

        $input['password'] = bcrypt($request['password']);
        $token = md5(time().$request->name.$request->email);
        $input['verification_link'] = $token;
        $input['affilate_code'] = md5($request->name.$request->email);
        $user->fill($input)->save();

        if($gs->is_verification_email == 1)
        {
            //$verificationLink = "<a href=".url('user/register/verify/'.$token).">Simply click here to verify. </a>";
            $verificationLink = "<a href=".url('user/register/verify/'.$token)." class='email-button'>Verify Email </a>";
            $to = $request->email;
            $subject = 'Verify your email address.';
            //$msg = "Dear Customer,<br> We noticed that you need to verify your email address.".$verificationLink;
            $msg = '<!DOCTYPE html>
                    <html lang="en">
                    <head>
                        <meta charset="UTF-8">
                        <meta name="viewport" content="width=device-width, initial-scale=1.0">
                        <title>Password Changed</title>
                      <style>
                        body {
                            margin: 0;
                            padding: 0;
                            font-family: "Arial", sans-serif;
                            background-color: #f7f7f7;
                        }
                        .email-wrapper {
                            width: 100%;
                            background-color: #f7f7f7;
                            padding: 20px 0;
                        }
                        .email-content {
                            width: 100%;
                            max-width: 600px;
                            background-color: #ffffff;
                            border-radius: 8px;
                            margin: 0 auto;
                            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                        }
                        .email-header {
                            text-align: center;
                            background-color: #002952;
                            padding: 20px;
                            text-align: center;
                            border-radius: 8px 8px 0 0;
                        }
                        .email-header img {
                            max-width: 238px;
                        }
                        .email-header span {
                            font-size: 18px; 
                            font-weight: 600; 
                            color: #0F78F2;
                            display: block;						   
                        }		
                        .email-body {
                            padding: 20px;
                            font-size: 16px;
                            line-height: 1.5;
                            color: #333;
                        }
                        .email-body h3 {
                            color: #0A5CBC;
                        }
                    
                        .email-button {
                            display: inline-block;
                            background-color: #003366;
                            color: #ffffff !important;
                            padding: 12px 24px;
                            margin: 15px 0;
                            font-size: 16px;
                            border-radius: 5px;
                            text-decoration: none;
                            font-weight: bold;
                        }
                        .email-footer {
                            background-color: #1f1f1f;
                            color: #ffffff;
                            text-align: center;
                            padding: 10px;
                            border-radius: 0 0 8px 8px;
                            font-size: 14px;
                        }
                        .email-footer a {
                            color: #0F78F2;
                            text-decoration: none;
                        }
                      </style>
                    </head>
                    <body>
                      <div class="email-wrapper">
                        <div class="email-content">
                          <div class="email-header">
                            <!-- Optional Logo -->
                    		<img src="https://fluxeassets.com/imgx/etemp.png" alt="Fluxe Assets Logo">
                            <span>Guiding You Toward Financial Growth</span>
                          </div>
                          <div class="email-body">
                            <h3>Dear '.$request->name.',</h3>
                    		<p>Thank you for signing up. To complete your registration, please verify your email address by clicking the button below:</p>
                    <p style="text-align: center;">'.$verificationLink.'</p>
                    		<p>If you did not create an account, you can safely ignore this email.</p>
                    		<p>Thanks,<br>The Fluxe Assets Team</p>
                          </div>
                          <div class="email-footer">
                            <p>Copyright &copy; 2025 <a href="https://fluxeassets.com">Fluxe Assets</a>. All rights reserved.</p>
                          </div>
                        </div>
                      </div>
                    </body>
                    </html>';

            if($gs->is_smtp == 1)
            {

                $mail = new PHPMailer(true);

                try {
                    $mail->isSMTP();
                    $mail->Host       = $gs->smtp_host;
                    $mail->SMTPAuth   = true;
                    $mail->Username   = $gs->smtp_user;
                    $mail->Password   = $gs->smtp_pass;
                    if ($gs->smtp_encryption == 'ssl') {
                        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                    } else {
                        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                    }
                    $mail->Port       = $gs->smtp_port;
                    $mail->CharSet = 'UTF-8';
                    $mail->setFrom($gs->from_email, $gs->from_name);
                    $mail->addAddress($user->email, $user->name);
                    $mail->addReplyTo($gs->from_email, $gs->from_name);
                    $mail->isHTML(true);
                    $mail->Subject = $subject;
                    $mail->Body    = $msg;
                    $mail->send();
                } catch (Exception $e) {

                }
            }
            else
            {
                $headers = "From: ".$gs->from_name."<".$gs->from_email.">";
                mail($to,$subject,$msg,$headers);
            }
            return response()->json('We need to verify your email address. We have sent an email to '.$to.' to verify your email address. Please click link in that email to continue.');
        }
        else {

            if (Session::has('affilate'))
            {
                $referral = User::findOrFail(Session::get('affilate'));
                $user->referral_id = $referral->id;
                $user->update();
            }

            if($gs->is_affilate == 1){
                if(Session::has('affilate')){

                    $mainUser = User::findOrFail(Session::get('affilate'));
                    $mainUser->balance += $gs->affilate_user;
                    $mainUser->update();

                    $user->balance += $gs->affilate_new_user;
                    $user->update();

                    $bonus = new ReferralBonus();
                    $bonus->from_user_id = $user->id;
                    $bonus->to_user_id = $mainUser->id;
                    $bonus->amount = $gs->affilate_user;
                    $bonus->type = 'Register';
                    $bonus->save();

                    $newbonus = new ReferralBonus();
                    $newbonus->from_user_id = $mainUser->id;
                    $newbonus->to_user_id = $user->id;
                    $newbonus->amount = $gs->affilate_new_user;
                    $newbonus->type = 'Register';
                    $newbonus->save();

                    $mainUserTrans = new Transaction();
                    $mainUserTrans->email = $mainUser->email;
                    $mainUserTrans->amount = $gs->affilate_user;
                    $mainUserTrans->type = "Referral Bonus";
                    $mainUserTrans->profit = "plus";
                    $mainUserTrans->txnid = Str::random(12);
                    $mainUserTrans->user_id =$mainUser->id;
                    $mainUserTrans->save();

                    $newUserTrans = new Transaction();
                    $newUserTrans->email = $user->email;
                    $newUserTrans->amount = $gs->affilate_new_user;
                    $newUserTrans->type = "Referral Bonus";
                    $newUserTrans->profit = "plus";
                    $newUserTrans->txnid = Str::random(12);
                    $newUserTrans->user_id =$user->id;
                    $newUserTrans->save();
                }
            }

            $user->email_verified = 'Yes';
            $user->update();

            if($gs->is_smtp == 1)
            {

                        $subject = 'Welcome to Fluxe Assets';
                        $msg = '<!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <meta name="viewport" content="width=device-width, initial-scale=1.0">
                            <title>Welcome to Fluxe Assets</title>
                            <style>
                                body {
                                    margin: 0;
                                    padding: 0;
                                    font-family: "Arial", sans-serif;
                                    background-color: #f7f7f7;
                                }
                                .email-wrapper {
                                    width: 100%;
                                    background-color: #f7f7f7;
                                    padding: 20px 0;
                                }
                                .email-content {
                                    width: 100%;
                                    max-width: 600px;
                                    background-color: #ffffff;
                                    border-radius: 8px;
                                    margin: 0 auto;
                                    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                                }
                                .email-header {
                                    background-color: #003366;
                                    padding: 20px;
                                    text-align: center;
                                    border-radius: 8px 8px 0 0;
                                }
                                .email-header img {
                                    max-width: 220px;
                                }
                                .email-header span {
                                    font-size: 18px;
                                    font-weight: 600;
                                    color: #00BFFF;
                                    display: block;
                                    margin-top: 10px;
                                }
                                .email-body {
                                    padding: 16px 30px;
                                    font-size: 16px;
                                    line-height: 1.5;
                                    color: #333;
                                }
                                .email-body h3 {
                                    color: #003366;
                                    margin-bottom: 15px;
                                }
                                .email-body p {
                                    margin-bottom: 20px;
                                }
                                .email-button {
                                    display: inline-block;
                                    background-color: #003366;
                                    color: #ffffff !important;
                                    padding: 12px 24px;
                                    font-size: 16px;
                                    border-radius: 5px;
                                    text-decoration: none;
                                }
                                .email-footer {
                                    background-color: #1f1f1f;
                                    color: #ffffff;
                                    text-align: center;
                                    padding: 12px;
                                    border-radius: 0 0 8px 8px;
                                    font-size: 14px;
                                }
                                .email-footer a {
                                    color: #00BFFF;
                                    text-decoration: none;
                                }
                            </style>
                        </head>
                        <body>
                        
                        <div class="email-wrapper">
                            <div class="email-content">
                                <div class="email-header">
                                    <img src="https://fluxeassets.com/imgx/etemp.png" alt="Fluxe Assets Logo">
                                    <span>Guiding You Toward Financial Growth</span>
                                </div>
                                <div class="email-body">
                                    <h3>Welcome to Fluxe Assets</h3>
                                    <p>Dear <strong>'.$user->name.'</strong>,</p>
                                    <p>Thank you for registering with us. We are thrilled to have you onboard as part of our investment community.</p>
                                    <p>At Fluxe Assets, we are committed to helping you make smart financial decisions and grow your wealth through expert guidance and cutting-edge tools.</p>
                                    <p>Your account is now active. Explore personalized investment options, track your portfolio, and stay informed with real-time insights.</p>
                                    <p>Need help? <a href="https://fluxeassets.com/contact" style="font-weight: 600;">We are here for you</a>.
                                        </p>
                                    <p style="margin-top: 30px;">Sincerely,<br>The Fluxe Assets Team</p>
                                </div>
                                <div class="email-footer">
                                    <p>Copyright &copy; 2025 <a href="https://fluxeassets.com">Fluxe Assets</a>. All rights reserved.</p>
                                </div>
                            </div>
                        </div>
                        
                        </body>
                        </html>';
                        
                        $mail = new PHPMailer(true);
        
                        try {
                            $mail->isSMTP();
                            $mail->Host       = $gs->smtp_host;
                            $mail->SMTPAuth   = true;
                            $mail->Username   = $gs->smtp_user;
                            $mail->Password   = $gs->smtp_pass;
                            if ($gs->smtp_encryption == 'ssl') {
                                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                            } else {
                                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                            }
                            $mail->Port       = $gs->smtp_port;
                            $mail->CharSet = 'UTF-8';
                            $mail->setFrom($gs->from_email, $gs->from_name);
                            $mail->addAddress($user->email, $user->name);
                            $mail->addReplyTo($gs->from_email, $gs->from_name);
                            $mail->isHTML(true);
                            $mail->Subject = $subject;
                            $mail->Body    = $msg;
                            $mail->send();
                        } catch (Exception $e) {
                            Log::error('Welcome email failed: ' . $mail->ErrorInfo);
                        }

            }
            else
            {
               $to = $user->email;
               $subject = "Welcome to our website";
               $msg = "Hello ".$user->name."!\nYour registration successfully completed.\nThank you.";
               $headers = "From: ".$gs->from_name."<".$gs->from_email.">";
               mail($to,$subject,$msg,$headers);
            }

            $notification = new Notification;
            $notification->user_id = $user->id;
            $notification->save();
            Auth::guard('web')->login($user);

            return response()->json(1);
        }

    } 


    public function token($token)
    {
            $gs = Generalsetting::findOrFail(1);
            if($gs->is_verification_email == 1)
            {
                $user = User::where('verification_link','=',$token)->first();
                if(isset($user))
                {
                    $user->email_verified = 'Yes';
                    $user->update();

                            if (Session::has('affilate'))
                            {
                                $referral = User::findOrFail(Session::get('affilate'));
                                $user->referral_id = $referral->id;
                                $user->update();
                            }

                            if($gs->is_affilate == 1 && Session::has('affilate')){
                                $mainUser = $referral;
                                $mainUser->balance += $gs->affilate_user;
                                $mainUser->update();

                                $user->balance += $gs->affilate_new_user;
                                $user->update();
                            }


                    $notification = new Notification;
                    $notification->user_id = $user->id;
                    $notification->save();

                    if($gs->is_smtp == 1)
                    {

                        $subject = 'Welcome to Fluxe Assets';
                        $msg = '<!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <meta name="viewport" content="width=device-width, initial-scale=1.0">
                            <title>Welcome to Fluxe Assets</title>
                            <style>
                                body {
                                    margin: 0;
                                    padding: 0;
                                    font-family: "Arial", sans-serif;
                                    background-color: #f7f7f7;
                                }
                                .email-wrapper {
                                    width: 100%;
                                    background-color: #f7f7f7;
                                    padding: 20px 0;
                                }
                                .email-content {
                                    width: 100%;
                                    max-width: 600px;
                                    background-color: #ffffff;
                                    border-radius: 8px;
                                    margin: 0 auto;
                                    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                                }
                                .email-header {
                                    background-color: #003366;
                                    padding: 20px;
                                    text-align: center;
                                    border-radius: 8px 8px 0 0;
                                }
                                .email-header img {
                                    max-width: 220px;
                                }
                                .email-header span {
                                    font-size: 18px;
                                    font-weight: 600;
                                    color: #00BFFF;
                                    display: block;
                                    margin-top: 10px;
                                }
                                .email-body {
                                    padding: 16px 30px;
                                    font-size: 16px;
                                    line-height: 1.5;
                                    color: #333;
                                }
                                .email-body h3 {
                                    color: #003366;
                                    margin-bottom: 15px;
                                }
                                .email-body p {
                                    margin-bottom: 20px;
                                }
                                .email-button {
                                    display: inline-block;
                                    background-color: #003366;
                                    color: #ffffff !important;
                                    padding: 12px 24px;
                                    font-size: 16px;
                                    border-radius: 5px;
                                    text-decoration: none;
                                }
                                .email-footer {
                                    background-color: #1f1f1f;
                                    color: #ffffff;
                                    text-align: center;
                                    padding: 12px;
                                    border-radius: 0 0 8px 8px;
                                    font-size: 14px;
                                }
                                .email-footer a {
                                    color: #00BFFF;
                                    text-decoration: none;
                                }
                            </style>
                        </head>
                        <body>
                        
                        <div class="email-wrapper">
                            <div class="email-content">
                                <div class="email-header">
                                    <img src="https://fluxeassets.com/imgx/etemp.png" alt="Fluxe Assets Logo">
                                    <span>Guiding You Toward Financial Growth</span>
                                </div>
                                <div class="email-body">
                                    <h3>Welcome to Fluxe Assets</h3>
                                    <p>Dear <strong>'.$user->name.'</strong>,</p>
                                    <p>Thank you for registering with us. We are thrilled to have you onboard as part of our investment community.</p>
                                    <p>At Fluxe Assets, we are committed to helping you make smart financial decisions and grow your wealth through expert guidance and cutting-edge tools.</p>
                                    <p>Your account is now active. Explore personalized investment options, track your portfolio, and stay informed with real-time insights.</p>
                                    <p>Need help? <a href="https://fluxeassets.com/contact" style="font-weight: 600;">We are here for you</a>.
                                        </p>
                                    <p style="margin-top: 30px;">Sincerely,<br>The Fluxe Assets Team</p>
                                </div>
                                <div class="email-footer">
                                    <p>Copyright &copy; 2025 <a href="https://fluxeassets.com">Fluxe Assets</a>. All rights reserved.</p>
                                </div>
                            </div>
                        </div>
                        
                        </body>
                        </html>';
                        
                        $mail = new PHPMailer(true);
        
                        try {
                            $mail->isSMTP();
                            $mail->Host       = $gs->smtp_host;
                            $mail->SMTPAuth   = true;
                            $mail->Username   = $gs->smtp_user;
                            $mail->Password   = $gs->smtp_pass;
                            if ($gs->smtp_encryption == 'ssl') {
                                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                            } else {
                                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                            }
                            $mail->Port       = $gs->smtp_port;
                            $mail->CharSet = 'UTF-8';
                            $mail->setFrom($gs->from_email, $gs->from_name);
                            $mail->addAddress($user->email, $user->name);
                            $mail->addReplyTo($gs->from_email, $gs->from_name);
                            $mail->isHTML(true);
                            $mail->Subject = $subject;
                            $mail->Body    = $msg;
                            $mail->send();
                        } catch (Exception $e) {
                            Log::error('Welcome email failed: ' . $mail->ErrorInfo);
                        }

                    }
                    else
                    {
                       $to = $user->email;
                       $subject = "Welcome to Fluxe Assets";
                       $msg = "Hello ".$user->name."!\nYour registration successfully completed.\nThank you.";
                       $headers = "From: ".$gs->from_name."<".$gs->from_email.">";
                       mail($to,$subject,$msg,$headers);
                    }

                    Auth::guard('web')->login($user);
                    return redirect()->route('user.dashboard')->with('success','Email Verified Successfully');
                }
            }
            else {
                return redirect()->back();
            }
    }
}
