<?php
$page_title = "Forgot Password";
require_once 'includes/header.php';
require_once 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require_once 'vendor/phpmailer/phpmailer/src/SMTP.php';
require_once 'vendor/phpmailer/phpmailer/src/Exception.php';

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

// Check if user is already logged in
if (isset($_SESSION['user_id'])) {
    header('Location: user/dashboard.php');
    exit();
}

$message = '';
$message_type = '';

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

    if (empty($email)) {
        $message = "Please enter your email address.";
        $message_type = "error";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = "Please enter a valid email address.";
        $message_type = "error";
    } else {
        $db = Database::getInstance()->connect();

        // Check if email exists
        $stmt = $db->prepare("SELECT id, username FROM users WHERE email = ? AND email_verified = 1");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if ($user) {
            // Generate reset token
            $reset_token = bin2hex(random_bytes(32));
            $token_expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));

            // Update user with reset token
            $update_stmt = $db->prepare("
                UPDATE users SET
                    password_reset_token = ?,
                    password_reset_expiry = ?,
                    updated_at = NOW()
                WHERE id = ?
            ");
            $update_stmt->execute([$reset_token, $token_expiry, $user['id']]);

            // Send reset email
            $reset_link = SITE_URL . "/reset-password.php?token=" . $reset_token;
            $subject = "Password Reset - " . SITE_NAME;
            $email_content = "
            <html>
            <head>
                <title>Password Reset</title>
            </head>
            <body>
                <h2>Password Reset Request</h2>
                <p>Hi {$user['username']},</p>
                <p>You have requested to reset your password for your " . SITE_NAME . " account.</p>
                <p>Click the link below to reset your password:</p>
                <p><a href='" . $reset_link . "' style='background-color: #667eea; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>Reset Password</a></p>
                <p>If the button doesn't work, copy and paste this link into your browser:</p>
                <p>" . $reset_link . "</p>
                <p>This link will expire in 1 hour for security reasons.</p>
                <p>If you didn't request this password reset, please ignore this email.</p>
                <br>
                <p>Best regards,<br>" . SITE_NAME . " Team</p>
            </body>
            </html>
            ";

            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
            $headers .= "From: " . SITE_NAME . " <" . SITE_EMAIL . ">" . "\r\n";

            // Send email using PHPMailer
            $mail = new PHPMailer(true);
            try {
                $mail->isSMTP();
                $mail->Host = SMTP_HOST;
                $mail->SMTPAuth = true;
                $mail->Username = SMTP_USERNAME;
                $mail->Password = SMTP_PASSWORD;
                $mail->SMTPSecure = SMTP_ENCRYPTION;
                $mail->Port = SMTP_PORT;

                $mail->setFrom(SITE_EMAIL, SITE_NAME);
                $mail->addAddress($email);

                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body = $email_content;

                $mail->send();
                $message = "Password reset instructions have been sent to your email address.";
                $message_type = "success";
            } catch (Exception $e) {
                $message = "Failed to send reset email. Please try again later.";
                $message_type = "error";
            }
        } else {
            // Don't reveal if email exists or not for security
            $message = "If an account with that email address exists, password reset instructions have been sent.";
            $message_type = "success";
        }
    }
}
?>

<!-- Start main-content -->
<section class="page-title" style="background-image: url(images/bg/page-title-bg.jpg);">
  <div class="auto-container">
    <div class="title-outer">
      <ul class="page-breadcrumb">
         <li><a href="index.php">Home</a></li>
        <li>Forgot Password</li>
      </ul>
      <h1 class="title">Forgot Password</h1>
    </div>
  </div>
</section>
<!-- end main-content -->

<section class="contact-details pt-120 pb-120">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-6 col-md-8 col-sm-10 col-12">
                <div class="inner-column right-column" style="margin: 0 auto; background: #ffffff; padding: 40px; border-radius: 12px; box-shadow: 0px 15px 40px rgba(0, 0, 0, 0.05); border: 1px solid rgba(0, 0, 0, 0.05);">
                    <div class="sec-title mb-30 text-center">
                        <h2 class="title splt-txt">Forgot Password?</h2>
                        <p class="text">Enter your email address and we'll send you a link to reset your password.</p>
                    </div>

                    <?php if ($message): ?>
                        <div class="alert <?php echo $message_type === 'success' ? 'alert-success' : 'alert-danger'; ?> mb-4" style="background-color: <?php echo $message_type === 'success' ? '#d4edda' : '#f8d7da'; ?>; border-color: <?php echo $message_type === 'success' ? '#c3e6cb' : '#f5c6cb'; ?>; color: <?php echo $message_type === 'success' ? '#155724' : '#721c24'; ?>; padding: 12px 20px; border-radius: 6px; font-size: 15px; border-left: 4px solid <?php echo $message_type === 'success' ? '#28a745' : '#dc3545'; ?>;">
                            <i class="fa-solid <?php echo $message_type === 'success' ? 'fa-circle-check' : 'fa-triangle-exclamation'; ?> me-2"></i> <?php echo htmlspecialchars($message); ?>
                        </div>
                    <?php endif; ?>

                    <form method="POST" action="">
                        <div class="type-feild">
                            <i class="fa-light fa-envelope" style="color: var(--theme-color2); font-size: 18px; top: 12px;"></i>
                            <input type="email" name="email" class="required" autocomplete="email" required placeholder="Enter your email address*" style="border-bottom: 1px solid rgba(92, 92, 91, 0.2); font-size: 16px; padding: 10px 10px 10px 35px; background: transparent; transition: all 0.3s ease;" onfocus="this.style.borderColor='var(--theme-color2)'" onblur="this.style.borderColor='rgba(92, 92, 91, 0.2)'">
                        </div>

                        <div class="text-center">
                            <button type="submit" class="btn-two" style="width: 100%; border: none; border-radius: 6px; padding: 16px 20px; font-weight: 600; cursor: pointer; transition: all 0.3s ease;">Send Reset Link</button>
                        </div>

                        <div class="text-center mt-4">
                             <a href="login.php" class="text-decoration-none text-theme-color2" style="font-size: 15px; font-weight: 600;">Back to login</a>
                        </div>
                    </form>

                </div>
            </div>
        </div>
    </div>
</section>

<?php require_once 'includes/footerm.php'; ?>