<?php
require_once(__DIR__ . '/../common.php');
require_once(__DIR__ . '/../config.php');

// Function to sanitize input
function sanitize_input($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

if (session_status() === PHP_SESSION_NONE) {
    session_start(); // Start session for captcha
}

$msg = '';
$error = '';
$errors = array();

if (isset($_POST['submit'])) {
    // Validate captcha
    if (!isset($_SESSION['security_code']) || strcasecmp(trim((string)($_POST['captcha'] ?? '')), $_SESSION['security_code']) !== 0) {
        $errors['captcha'] = 'Please correctly enter the code above.';
    }

    // Proceed if there are no errors
    if (empty($errors)) {
        unset($_SESSION['security_code']); // one-time captcha
        $input = sanitize_input($_POST['email']);
        
        if (filter_var($input, FILTER_VALIDATE_EMAIL)) {
            // Input is an email address, proceed with email logic
            $query = "SELECT id, email FROM sm_editors WHERE email = :email";
            $stmt = $pdo->prepare($query);
            $stmt->bindParam(':email', $input, PDO::PARAM_STR);
        } elseif ($input === 'superadmin') {
            // Input matches the superadmin username stored in the email column
            $query = "SELECT id, email FROM sm_editors WHERE email = :username";
            $stmt = $pdo->prepare($query);
            $stmt->bindParam(':username', $input, PDO::PARAM_STR);
        } else {
            // Input is not a valid email or superadmin username
            $error = 'Please enter a valid email address. Only email addresses are allowed.';
            $input = ''; // Clear input to avoid further processing
        }

        if (!isset($error) || $error === '') {
            $stmt->execute();
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($result) {
                $user_id = $result['id'];
                $email = $result['email'];
                
                // Generate a unique token
                $token = bin2hex(random_bytes(32));
                $expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));  // Token valid for 1 hour
                
                // Store the token and expiry in the database
                $insert_query = "INSERT INTO password_resets (user_id, token, expiry) VALUES (:user_id, :token, :expiry)";
                $insert_stmt = $pdo->prepare($insert_query);
                $insert_stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
                $insert_stmt->bindParam(':token', $token, PDO::PARAM_STR);
                $insert_stmt->bindParam(':expiry', $expiry, PDO::PARAM_STR);
                $insert_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 ($smtp_row = $smtp_settings_result->fetch(PDO::FETCH_ASSOC)) {
                    $smtp_settings[$smtp_row['setting_key']] = $smtp_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($email);
                $mail->Subject = "Password Reset Request";

                // Build the reset link from the configured site URL (never from
                // request headers, which an attacker can spoof to steal the token).
                $reset_link = rtrim($site_url, '/') . "/editors/reset-password.php?token=" . $token;
                
                $msgHTML = "Hello,<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 account exists (prevents enumeration).
                $msg = 'If that account exists, we sent a link to reset the password.';
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password</title>
    <link rel="stylesheet" href="./../css/style.css"> <!-- Link to your CSS file for styling -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"> <!-- Font Awesome for Icons -->
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
        }
        .container {
            background: #ffffff;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.2);
            width: 100%;
            max-width: 500px;
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .message {
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], input[type="email"] {
            width: calc(100% - 20px);
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 16px;
        }
        .button-primary {
            background-color: #007BFF;
            color: #fff;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            width: 100%;
            transition: background-color 0.3s;
        }
        .button-primary:hover {
            background-color: #0056b3;
        }
        .error {
            color: red;
            font-size: 14px;
        }
        .msg {
            color: green;
            font-size: 14px;
        }
        img {
            display: block;
            margin: 0 auto;
        }
    </style>
</head>
<body>
<div class="container">
    <h1><i class="fas fa-unlock-alt"></i> Forgot Password</h1>
    <div class="message">
        <span class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></span>
        <span class="msg"><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></span>
    </div>
    <form method="post" action="forgot-password.php" class="form-style">
        <!-- Captcha image -->
        <div class="form-group">
            <img src="./../captcha/CaptchaSecurityImages.php?width=160&height=50&characters=5&<?= time() ?>" /><br />
            <label for="captcha">Enter The Code Above:</label>
            <input name="captcha" type="text" required />
            <span class="error"><?= htmlspecialchars($errors['captcha'] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
        </div>

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

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