<?php
session_start();
require_once 'db_connect.php';

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

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

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

    try {
        // 1. Check if the email exists in the database
        $stmt = $pdo->prepare("SELECT id, name FROM students WHERE email = ?");
        $stmt->execute([$email]);
        $student = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($student) {
            // 2. Automatically create 'password_resets' table if it doesn't exist
            $pdo->exec("CREATE TABLE IF NOT EXISTS password_resets (
                id INT AUTO_INCREMENT PRIMARY KEY,
                email VARCHAR(255) NOT NULL,
                token VARCHAR(255) NOT NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )");

            // 3. Generate a secure token
            $token = bin2hex(random_bytes(32));

            // Delete any existing tokens for this email
            $pdo->prepare("DELETE FROM password_resets WHERE email = ?")->execute([$email]);

            // Save the new token
            $pdo->prepare("INSERT INTO password_resets (email, token) VALUES (?, ?)")->execute([$email, $token]);

            // 4. Create the reset link (Updated for Ahmad Academy)
            $reset_link = "https://new.ahmadonlineacademy.com/reset_password.php?token=" . $token;

            // 5. Send Email (SMTP)
            $mail = new PHPMailer(true);
            try {
                $mail->isSMTP();
                $mail->Host       = 'smtp.hostinger.com'; 
                $mail->SMTPAuth   = true;
                
                // IMPORTANT: Update these credentials to your Ahmad Academy email
                $mail->Username   = 'info@ahmadonlineacademy.com'; 
                $mail->Password   = 'Your_Hostinger_Password_Here'; 
                
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; 
                $mail->Port       = 465;
                $mail->CharSet    = 'UTF-8';

                // Set From Email and Name
                $mail->setFrom('info@ahmadonlineacademy.com', 'Ahmad Academy');
                $mail->addAddress($email, $student['name']);

                $mail->isHTML(true);
                $mail->Subject = 'Password Reset Link - Ahmad Academy';
                
                // Email Body Design (Ahmad Academy Premium Theme)
                $mail->Body = "
                    <div style='font-family: Arial, sans-serif; max-width: 600px; margin: auto; border: 1px solid #e2e8f0; padding: 40px; border-radius: 15px; background-color: #f8fafc; border-top: 6px solid #d4af37;'>
                        <div style='text-align: center; margin-bottom: 20px;'>
                            <h2 style='color: #022c22; margin: 0; font-size: 24px;'>Reset Your Password</h2>
                        </div>
                        <p style='color: #334155; font-size: 16px;'>Hello <strong>{$student['name']}</strong>,</p>
                        <p style='color: #334155; font-size: 16px; line-height: 1.6;'>
                            We received a request to reset the password for your Ahmad Academy account. Please click the button below to set a new password:
                        </p>
                        <div style='text-align: center; margin: 35px 0;'>
                            <a href='{$reset_link}' style='background-color: #d4af37; color: #022c22; padding: 15px 35px; text-decoration: none; border-radius: 50px; font-weight: bold; font-size: 16px; display: inline-block; box-shadow: 0 5px 15px rgba(212, 175, 55, 0.4);'>Reset Password</a>
                        </div>
                        <p style='color: #64748b; font-size: 14px; line-height: 1.5;'>
                            If you did not request a password reset, please ignore this email or contact support if you have concerns.
                        </p>
                        <hr style='border: none; border-top: 1px solid #cbd5e1; margin: 30px 0;'>
                        <p style='color: #94a3b8; font-size: 12px; text-align: center; margin: 0; line-height: 1.6;'>
                            Best Regards,<br><strong style='color: #064e3b;'>Ahmad Academy Team</strong><br>
                            <a href='https://new.ahmadonlineacademy.com' style='color: #d4af37; text-decoration: none;'>www.ahmadonlineacademy.com</a>
                        </p>
                    </div>
                ";

                $mail->send();
                
                // Set Success Message
                $_SESSION['status_msg'] = "A password reset link has been sent to your email. Please check your inbox.";
                $_SESSION['status_type'] = "success";

            } catch (Exception $e) {
                // Set SMTP Error Message
                $_SESSION['status_msg'] = "There was a problem sending the email. Please try again later.";
                $_SESSION['status_type'] = "error";
            }
        } else {
            // Email not found in Database
            $_SESSION['status_msg'] = "No account found with this email address!";
            $_SESSION['status_type'] = "error";
        }
    } catch (PDOException $e) {
        // Database Error
        $_SESSION['status_msg'] = "System Error: " . $e->getMessage();
        $_SESSION['status_type'] = "error";
    }

    header("Location: forgot_password.php");
    exit;
} else {
    header("Location: login.php");
    exit;
}
?>