<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ob_start(); // Start output buffering


   

   session_start();

require '../config.php';

 $stmt = $pdo->query("SELECT * FROM settings ORDER BY id DESC LIMIT 1");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
  // Extract values safely
  
$cphone = $row['phone'];
$curl = $row['url'];
$cdomain = $row['domain'];
$cname = $row['domain_name'];
$cpass = $row['password'];
$cemail = $row['email2'];
$cright = $row['copyright'];
$chost = $row['contact_email'];
$cport = $row['service1'];

    } 
 

// Include PHPMailer
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';

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



if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = trim($_POST["email"]);

    // Check if email exists
    $stmt = $pdo->prepare("SELECT id FROM logins WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        $_SESSION['error'] = "Email not found!";
        header("Location: forget_password.php");
        exit();
    }

    // Generate Secure Token
    $token = bin2hex(random_bytes(32));
    $expires_at = date("Y-m-d H:i:s", strtotime("+10 minutes"));

    // Store Token in Database
    $stmt = $pdo->prepare("UPDATE logins SET reset_token = ?, reset_expires = ? WHERE email = ?");
    $stmt->execute([$token, $expires_at, $email]);

    // Send Reset Link via PHPMailer
    $mail = new PHPMailer(true);
    try {
        // SMTP Configuration
        $mail->isSMTP();
        $mail->Host = $chost;  // Change to your email provider's SMTP
        $mail->SMTPAuth = true;
        $mail->Username = $cemail;  // Your email
        $mail->Password = $cpass;  // Your email password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = $cport;

        // Email Settings
        $mail->setFrom($cemail, $cname);
        $mail->addAddress($email);
        $mail->isHTML(true);
        $mail->Subject = 'Password Reset Request';
        $mail->Body = "
            <h3>Password Reset Request</h3>
            <p>Click the link below to reset your password:</p>
            <p><a href='http://$cdomain/invest/reset_password.php?token=$token'>Reset Password</a></p>
            <p>This link expires in 10 minutes.</p>
        ";

        $mail->send();
        $_SESSION['success'] = "Reset link sent to your email!";
    } catch (Exception $e) {
        $_SESSION['error'] = "Email could not be sent. Error: {$mail->ErrorInfo}";
    }

    // Redirect to forget_password.php
    header("Location: forget_password.php");
    exit();
}

ob_end_flush(); // End output buffering
?>

