<?php

namespace App\Http\Controllers\User;

use App\Classes\GeniusMailer;
use App\Classes\GoogleAuthenticator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\AdminUserConversation;
use App\Models\Country;
use App\Models\Deposit;
use App\Models\Generalsetting;
use App\Models\Invest;
use App\Models\Order;
use App\Models\ReferralBonus;
use App\Models\Transaction;
use App\Models\User;
use App\Models\Withdraw;
use App\Traits\Payout;
use Auth;
use Brian2694\Toastr\Facades\Toastr;
use Carbon\Carbon;
use Illuminate\Support\Facades\Input;
use Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

use Illuminate\Support\Facades\Log;

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

    public function index()
    {
        $data['user'] = Auth::user();
        $data['transactions'] = Transaction::whereUserId(auth()->id())->orderBy('id','desc')->limit(5)->get();
        $data['total_invests'] = Invest::whereUserId(auth()->id())->whereStatus(1)->sum('amount');
        $data['total_payouts'] = Withdraw::whereUserId(auth()->id())->whereStatus('completed')->sum('amount');
        $data['total_deposits'] = Deposit::whereUserId(auth()->id())->whereStatus('complete')->sum('amount');
        $data['total_transactions'] = Transaction::whereUserId(auth()->id())->sum('amount');
        $data['total_tickets'] = AdminUserConversation::whereUserId(auth()->id())->count();
        $data['total_referral_bonus'] = ReferralBonus::wheretoUserId(auth()->id())->sum('amount');

        return view('user.dashboard',$data);
    }

    public function transaction(Request $request)
    {
        $user = Auth::user();
        $transactions = Transaction::whereUserId(auth()->id())
                                    ->when($request->trx_no,function($query) use ($request){
                                        return $query->where('txnid', $request->trx_no);
                                    })
                                    ->when($request->type,function($query) use ($request){
                                        if($request->type != 'all'){
                                            return $query->where('type',$request->type);
                                        }else{

                                        }
                                    })
                                    ->whereUserId(auth()->id())->orderBy('id','desc')->paginate(20);
        return view('user.transactions',compact('user','transactions'));
    }

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

    public function profileupdate(Request $request)
    {
        $request->validate([
            'photo' => 'mimes:jpeg,jpg,png,svg',
            'email' => 'unique:users,email,'.Auth::user()->id
        ]);

        $input = $request->all();
        $data = Auth::user();
        if ($file = $request->file('photo'))
        {
            $name = time().$file->getClientOriginalName();
            $file->move('assets/images/',$name);
            @unlink('assets/images/'.$data->photo);

            $input['photo'] = $name;

            $input['is_provider'] = 0;
        }

        $data->update($input);

        $gs = Generalsetting::first();
        
        // Commented out email sending
        /*
        if($gs->is_smtp == 1)
        {
            $data = [
                'to' => $data->email,
                'type' => "profile update",
                'cname' => $data->name,
                'oamount' => "",
                'aname' => "",
                'aemail' => "",
                'wtitle' => "",
            ];

            $mailer = new GeniusMailer();
            $mailer->sendAutoMail($data);
        }
        else
        {
           $to = $data->email;
           $subject = "Your profile has been update";
           $msg = "Hello ".$data->name."!\nYour profile has been updated successfully.\nThank you.";
           $headers = "From: ".$gs->from_name."<".$gs->from_email.">";
           mail($to,$subject,$msg,$headers);
        }
        */
        $msg = 'Successfully updated your profile';
        return redirect()->back()->with('success',$msg);
    }

    public function changePasswordForm()
    {
        return view('user.changepassword');
    }

    public function changePassword(Request $request)
    {
        $user = Auth::user();
        $gs = Generalsetting::first();
        
        
        if ($request->cpass){
            if (Hash::check($request->cpass, $user->password)){
                if ($request->newpass == $request->renewpass){
                    $input['password'] = Hash::make($request->newpass);
                }else{
                    return redirect()->back()->with('unsuccess','Confirm password does not match.');
                }
            }else{
                return redirect()->back()->with('unsuccess','Current password is incorrect.');
            }
        }
        $user->update($input);

        if($gs->is_smtp == 1)
        {
            
           $subject = "Your password has been changed";
           $msg = '<!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>Your Password Has Been 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 {
                            background-color: #003366;
                            padding: 20px;
                            text-align: center;
                            border-radius: 8px 8px 0 0;
                        }
                        .email-header img {
                            max-width: 200px;
                        }
                        .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: 6px 12px;
                            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">
                            <p>Dear <strong>'.$user->name.'</strong>,</p>
                            <p>This is a confirmation that your password has been changed successfully.</p>
                			<p>If you did not make this change, please contact our support team immediately to secure your account.</p>
                			<p style="margin-top: 30px;">Thank you,<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>';

            try {
                $mail = new PHPMailer(true);
        
                //Server settings
                $mail->isSMTP();
                $mail->Host       = $gs->smtp_host;
                $mail->SMTPAuth   = true;
                $mail->Username   = $gs->smtp_user;
                $mail->Password   = $gs->smtp_pass;
                $mail->SMTPSecure = $gs->smtp_encryption; // 'tls' or 'ssl'
                $mail->Port       = $gs->smtp_port;
        
                //Recipients
                $mail->setFrom($gs->from_email, $gs->from_name);
                $mail->addAddress($user->email, $user->name);
        
                //Content
                $mail->isHTML(true);
                $mail->Subject =  $subject;
                $mail->Body    = $msg;
        
                $mail->send();
            } catch (Exception $e) {
                // You can log or handle the error if needed
                // Log::error('PHPMailer Error: ' . $mail->ErrorInfo);
            }          
        }
        else
        {
           $to = $user->email;
           $subject = "Your password has been changed";
           $msg = "Hello ".$user->name."!\nYour password has been changed successfully.\nThank you.";
           $headers = "From: ".$gs->from_name."<".$gs->from_email.">";
           mail($to,$subject,$msg,$headers);
        }

        return redirect()->back()->with('success','Password Successfully Changed.');
    }

/*
    public function showTwoFactorForm()
    {
        $gnl = Generalsetting::first();
        $ga = new GoogleAuthenticator();
        $user = auth()->user();
        $secret = $ga->createSecret();
        $qrCodeUrl = $ga->getQRCodeGoogleUrl($user->name . '@' . $gnl->title, $secret);
        $prevcode = $user->tsc;
        $prevqr = $ga->getQRCodeGoogleUrl($user->name . '@' . $gnl->title, $prevcode);

        return view('user.twofactor.index', compact('secret', 'qrCodeUrl', 'prevcode', 'prevqr'));
    }

    public function createTwoFactor(Request $request)
    {
        $user = auth()->user();

        $this->validate($request, [
            'key' => 'required',
            'code' => 'required',
        ]);

        $ga = new GoogleAuthenticator();
        $secret = $request->key;
        $oneCode = $ga->getCode($secret);

        if ($oneCode == $request->code) {
            $user->go = $request->key;
            $user->twofa = 1;
            $user->save();

            return redirect()->back()->with('success','Two factor authentication activated');
        } else {
            return redirect()->back()->with('error','Something went wrong!');
        }
    }


    public function disableTwoFactor(Request $request)
    {

        $this->validate($request, [
            'code' => 'required',
        ]);

        $user = auth()->user();
        $ga = new GoogleAuthenticator();

        $secret = $user->go;
        $oneCode = $ga->getCode($secret);
        $userCode = $request->code;

        if ($oneCode == $userCode) {

            $user->go = null;
            $user->twofa = 0;

            $user->save();

            return redirect()->back()->with('success','Two factor authentication disabled');
        } else {
            return redirect()->back()->with('error','Something went wrong!');
        }
    }

*/

public function showTwoFactorForm()
{
    $gnl = Generalsetting::first();
    $ga = new GoogleAuthenticator();
    $user = auth()->user();

    // Only create and store secret in session if it's not already there
    if (!session()->has('2fa_secret')) {
        session(['2fa_secret' => $ga->createSecret()]);
    }

    $secret = session('2fa_secret');
    $qrCodeUrl = $ga->getQRCodeGoogleUrl($user->name . '@' . $gnl->title, $secret);

    return view('user.twofactor.index', compact('secret', 'qrCodeUrl'));
}

public function createTwoFactor(Request $request)
{
    $this->validate($request, [
        'code' => 'required|digits:6',
    ]);

    $secret = session('2fa_secret');
    if (!$secret) {
        return back()->with('error', 'Session expired. Please try again.');
    }

    $ga = new GoogleAuthenticator();
    $oneCode = $ga->getCode($secret);

    //Log::info('2FA expected code: ' . $oneCode);
    //Log::info('2FA user entered code: ' . $request->code);

    if ($oneCode == $request->code) {
        $user = auth()->user();
        $user->go = $secret;
        $user->twofa = 1;
        $user->save();

        // Remove secret from session
        session()->forget('2fa_secret');

        return redirect()->back()->with('success','Two factor authentication activated');
    }

    return redirect()->back()->with('error','Invalid code. Please try again.');
}

public function disableTwoFactor(Request $request)
{
    $this->validate($request, [
        'code' => 'required|digits:6',
    ]);

    $user = auth()->user();
    $ga = new GoogleAuthenticator();

    $secret = $user->go;

    if (!$secret) {
        return back()->with('error', 'No 2FA secret found.');
    }

    $expectedCode = $ga->getCode($secret);
    \Log::info('Disabling 2FA - expected: ' . $expectedCode . ', user entered: ' . $request->code);

    if ($expectedCode == $request->code) {
        $user->go = null;
        $user->twofa = 0;
        $user->save();

        return redirect()->back()->with('success', 'Two factor authentication disabled');
    }

    return redirect()->back()->with('error', 'Invalid code. Please try again.');
}

    public function username($email){
       if($data = User::where('email',$email)->first()){
           return $data->name;
       }else{
           return false;
       }
    }

    public function affilate_code()
    {
        $user = Auth::guard('web')->user();
        return view('user.affilate_code',compact('user'));
    }


}
