<?php

namespace App\Http\Controllers\User;

use App\Models\Generalsetting;
use App\Models\User;
use Illuminate\Http\Request;
use App\Classes\GeniusMailer;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Str;
use Validator;

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

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

    public function showForgotForm()
    {
      return view('user.forgot');
    }

   /* public function forgot(Request $request)
    {
      $gs = Generalsetting::findOrFail(1);
      $input =  $request->all();

      if (User::where('email', '=', $request->email)->count() > 0) {
   
        $admin = User::where('email', '=', $request->email)->firstOrFail();
        $autopass = Str::random(8);
        $input['password'] = bcrypt($autopass);
        $admin->update($input);
        $subject = "Reset Password Request";
        $msg = "Your New Password is : ".$autopass;

        if($gs->is_smtp == 1)
        {
            $data = [
              'to' => $request->email,
              'subject' => $subject,
              'body' => $msg,
            ];

            $mailer = new GeniusMailer();
            $mailer->sendCustomMail($data);                
        }
        else
        {
          $headers = "From: ".$gs->from_name."<".$gs->from_email.">";
          mail($request->email,$subject,$msg,$headers);            
        }
        return response()->json('Your Password Reseted Successfully. Please Check your email for new Password.');
      }
      else{
        return response()->json('No Account Found With This Email.');  
      }  
    } */
    
    public function forgot(Request $request)
    {
        
        $gs = Generalsetting::findOrFail(1);
        $input = $request->all();
    
        if (User::where('email', '=', $request->email)->count() > 0) {
            $user = User::where('email', '=', $request->email)->firstOrFail();
            $admin = User::where('email', '=', $request->email)->firstOrFail();
            $autopass = Str::random(8);
            $input['password'] = bcrypt($autopass);
            $admin->update($input);
    
            $subject = "Reset Password Request";
            $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: 186px;
                        }
                        .email-header span {
                            font-size: 18px; 
                            font-weight: 600; 
                            color: #0F78F2;
                            display: block;
                            margin-top: 5px;						   
                        }		
                        .email-body {
                            padding: 20px;
                            font-size: 16px;
                            line-height: 1.5;
                            color: #333;
                        }
                        .email-body h3 {
                            color: #0A5CBC;
                        }
                        .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;
                            margin-top: 20px;
                        }
                        .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">
                    		<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 '.$user->name.',</h3>
                    		<p>We have generated a new password for your account as requested:</p>
                    		<p style="font-size: 16px; font-weight: bold; background-color: #eee; color: #002952; padding: 10px; border-radius: 4px;">' . $autopass . '</p>
                    		<p>Please use this password to <a href="https://fluxeassets.com/user/login" class="email-button" target="_blank">access your account</a>, and change it as soon as possible from your account settings for added security.</p>
                    		<p>If you did not request a password reset, please contact us immediately.</p>
                    		<p>Best regards,<br>The Fluxe Assets Support 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 {
                // SMTP 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($request->email);
    
                // Content
                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body    = $msg;
    
                $mail->send();
    
                return response()->json('Your Password Reset Successfully. Please check your email for new Password.');
            } catch (Exception $e) {
                return response()->json('Email could not be sent. Error: ' . $mail->ErrorInfo);
            }
    
        } else {
            return response()->json('No Account Found With This Email.');
        }
    }


    private function  code_image()
    {
        $actual_path = str_replace('project','',base_path());
        $image = imagecreatetruecolor(200, 50);
        $background_color = imagecolorallocate($image, 255, 255, 255);
        imagefilledrectangle($image,0,0,200,50,$background_color);

        $pixel = imagecolorallocate($image, 0,0,255);
        for($i=0;$i<500;$i++)
        {
            imagesetpixel($image,rand()%200,rand()%50,$pixel);
        }

        $font = $actual_path.'assets/front/fonts/NotoSans-Bold.ttf';
        $allowed_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        $length = strlen($allowed_letters);
        $letter = $allowed_letters[rand(0, $length-1)];
        $word='';
 
        $text_color = imagecolorallocate($image, 0, 0, 0);
        $cap_length=6;
        for ($i = 0; $i< $cap_length;$i++)
        {
            $letter = $allowed_letters[rand(0, $length-1)];
            imagettftext($image, 25, 1, 35+($i*25), 35, $text_color, $font, $letter);
            $word.=$letter;
        }
        $pixels = imagecolorallocate($image, 8, 186, 239);
        for($i=0;$i<500;$i++)
        {
            imagesetpixel($image,rand()%200,rand()%50,$pixels);
        }
        session(['captcha_string' => $word]);
        imagepng($image, $actual_path."assets/images/capcha_code.png");
    }

}
