<?php
error_reporting(E_ALL);
session_start();

// Include the database connection
require_once('../Connections/ebanking.php');

// Include PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

if (isset($_POST['email'])) {
    $user_id = $_POST['email'];

    // Sanitize email input
    $email = mysqli_real_escape_string($ebanking, $_POST['email']);
    
    // Prepare and execute the query
    $query = "SELECT email, accountno, password FROM customer WHERE email='$email'";
    $result = mysqli_query($ebanking, $query);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $email = $row['email'];
        $accountno = $row['accountno'];
        $password = $row['password'];

        // Send password email
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host       = 'mail.wolfvillecu.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'noreply@wolfvillecu.com';
            $mail->Password   = 'yc1]f2FqB{6J';
            $mail->SMTPSecure = 'ssl';
            $mail->Port       = 465;
            $mail->setFrom('noreply@wolfvillecu.com', 'Wolfville Credit Union');
            $mail->addAddress($email, $accountno);
            $mail->isHTML(true);
            $mail->Subject = 'Wolfville Credit Union Canada - Password Recovery';
            $mail->Body    = '<p>Dear ' . $accountno . ',</p>'
                            . '<p>Your password for Wolfville Credit Union Canada login is:</p>'
                            . '<h2 style="font-size: 24px; color: #4CAF50; margin-bottom: 20px;">' . $password . '</h2>'
                            . '<p>Please keep this information secure and do not share it with anyone.</p>'
                            . '<p>If you did not request this password recovery, please contact our support team immediately.</p>'
                            . '<p>Thank you for banking with us.</p>'
                            . '<p>Sincerely,</p>'
                            . '<p>Wolfville Credit Union, Canada</p>';
            $mail->send();

            // Redirect to confirmation page
            header("Location: forgotpassword.php?done=1");
            die;
        } catch (Exception $e) {
            echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
        }
    } else {
        // Invalid user ID
        header("Location: forgotpassword.php?done=2");
    }
}
?>
