<?php
session_start(); // Start session for captcha
require_once('common.php'); // Ensure this includes your PDO connection setup
require_once('functions.php');

// Initialize error and message variables
$errors = array();
$msg = '';
$error = '';

// Handle form submission
if (isset($_POST['submit'])) {
    // Validate the human check (Turnstile or image captcha)
    if (function_exists('captcha_verify') && !captcha_verify($_POST)) {
        $errors['captcha'] = 'Please complete the verification and try again.';
    }

    // Proceed if there are no errors
    if (empty($errors)) {
        // Securely prepare the SQL query using prepared statements to prevent SQL injection
        $email = trim($_POST['email']);
        
        $query = "SELECT * FROM sm_poets WHERE email = :email";
        
        try {
            // Use PDO to execute the query
            $stmt = $pdo->prepare($query);
            $stmt->bindParam(':email', $email, PDO::PARAM_STR);
            $stmt->execute();
            $result = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($result) {
                // Generate a unique reset token and set an expiry time
                $reset_token = bin2hex(random_bytes(32));
                $token_expiry = date('Y-m-d H:i:s', strtotime('+1 hour')); // Token valid for 1 hour
                
                // Store the reset token and expiry in the database
                $update_query = "UPDATE sm_poets SET reset_token = :reset_token, token_expiry = :token_expiry WHERE email = :email";
                $update_stmt = $pdo->prepare($update_query);
                $update_stmt->bindParam(':reset_token', $reset_token, PDO::PARAM_STR);
                $update_stmt->bindParam(':token_expiry', $token_expiry, PDO::PARAM_STR);
                $update_stmt->bindParam(':email', $email, PDO::PARAM_STR);
                $update_stmt->execute();

                // Fetch email settings from the database
                $smtp_settings_query = "SELECT setting_key, setting_value FROM mail_settings";
                $smtp_settings_result = $pdo->query($smtp_settings_query);
                $smtp_settings = [];
                while ($row = $smtp_settings_result->fetch(PDO::FETCH_ASSOC)) {
                    $smtp_settings[$row['setting_key']] = $row['setting_value'];
                }

                // Load PHPMailer files from lowercase directory
                require_once('phpmailer/src/PHPMailer.php');
                require_once('phpmailer/src/SMTP.php');
                require_once('phpmailer/src/Exception.php');

                // Send the reset link via email using PHPMailer
                $mail = new PHPMailer\PHPMailer\PHPMailer();
                $mail->IsSMTP();
                $mail->Host = $smtp_settings['mail_host'];
                $mail->SMTPAuth = true;  // Assuming SMTPAuth is needed
                $mail->SMTPSecure = $smtp_settings['mail_encryption'] ?? 'ssl';
                $mail->Port = $smtp_settings['mail_port'];
                $mail->Username = $smtp_settings['mail_username'];
                $mail->Password = $smtp_settings['mail_password'];

                $mail->SetFrom($smtp_settings['mail_from_address'], $smtp_settings['mail_from_name']);
                $mail->AddAddress($result['email'], $result['author_name'] . " " . $result['author_lastname']);
                $mail->Subject = "Password Reset Request";

                $reset_link = $site_url . "/reset-password.php?token=" . $reset_token;
                $msgHTML = "Hello " . htmlspecialchars($result['author_name'], ENT_QUOTES) . ",<br/><br/>";
                $msgHTML .= "You have requested to reset your password. Please click the link below to reset your password:<br/>";
                $msgHTML .= '<a href="' . $reset_link . '">' . $reset_link . '</a><br/><br/>';
                $msgHTML .= "This link is valid for 1 hour.";

                $mail->MsgHTML($msgHTML);

                // Send email and set message
                if ($mail->Send()) {
                    $msg = 'If you entered a valid email, we sent you a link to reset your password.';
                } else {
                    $error = 'There was an error sending the email. Please try again.';
                }
            } else {
                // Do not reveal whether the email exists (prevents account enumeration).
                $msg = 'If you entered a valid email, we sent you a link to reset your password.';
            }

        } catch (PDOException $e) {
            error_log('forgot-password.php PDOException: ' . $e->getMessage());
            $error = 'A temporary error occurred. Please try again.';
        }
    }
}

// Include header and menu
include_once('header.php');
include_once('menu.php');
?>

<!-- Centered form layout -->
<div class="container">
    <h2>Recover Your Password</h2>
    <span class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></span>
    <span class="msg"><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></span>

    <form method="post" action="forgot-password.php" class="form-style">
        <!-- Human verification (Turnstile or image captcha) -->
        <div class="form-group">
            <?= function_exists('captcha_widget') ? captcha_widget() : '' ?>
            <span class="error"><?= htmlspecialchars($errors['captcha'] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
        </div>

        <!-- Email input -->
        <div class="form-group">
            <label for="email">Please Enter Your Email Address:</label>
            <input value="<?= isset($_POST['email']) ? htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8') : '' ?>" name="email" type="text" size="32" />
        </div>

        <input name="submit" value="Email Me My Password" type="submit" class="button-primary" />
    </form>
</div>

<?php
include_once('footer.php');
?>
