<?php
session_start();
include 'config/db.php';
include 'includes/send_email.php';  // Include email helper

$error = '';
$success = '';
$step = 'request';

// Step 1: Request password reset
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['request_reset'])) {
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    
    $result = $conn->query("SELECT * FROM users WHERE email='$email'");
    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        
        // Generate unique token
        $token = bin2hex(random_bytes(32));
        $expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));
        
        // Create password_resets table if not exists
        $conn->query("CREATE TABLE IF NOT EXISTS password_resets (
            id INT AUTO_INCREMENT PRIMARY KEY,
            email VARCHAR(100) NOT NULL,
            token VARCHAR(255) NOT NULL,
            expires_at DATETIME NOT NULL,
            used TINYINT DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )");
        
        // Delete old tokens for this email
        $conn->query("DELETE FROM password_resets WHERE email='$email'");
        
        // Insert new token
        $stmt = $conn->prepare("INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $email, $token, $expiry);
        $stmt->execute();
        
        // Create reset link
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
        $reset_link = $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/reset_password.php?token=" . $token;
        
        // Email HTML content
        $email_body = "
        <html>
        <head>
            <title>Password Reset Request - BMYA-SHELDANG</title>
            <style>
                body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
                .container { font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; background: #f5f5f5; }
                .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; text-align: center; color: white; border-radius: 10px 10px 0 0; }
                .content { background: white; padding: 30px; border-radius: 0 0 10px 10px; }
                .button { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 20px 0; }
                .footer { font-size: 12px; color: #999; text-align: center; margin-top: 20px; padding-top: 20px; border-top: 1px solid #eee; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2>🔐 BMYA-SHELDANG</h2>
                    <p>Password Reset Request</p>
                </div>
                <div class='content'>
                    <p>Dear <strong>" . htmlspecialchars($user['name']) . "</strong>,</p>
                    <p>We received a request to reset your password for your BMYA-SHELDANG account.</p>
                    <p>Click the button below to create a new password:</p>
                    <div style='text-align: center;'>
                        <a href='" . $reset_link . "' class='button' style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block;'>Reset Password</a>
                    </div>
                    <p>If the button doesn't work, copy and paste this link into your browser:</p>
                    <p style='background: #f0f0f0; padding: 10px; border-radius: 5px; word-break: break-all; font-size: 12px;'>" . $reset_link . "</p>
                    <p>If you didn't request this, please ignore this email. Your password will remain unchanged.</p>
                    <div class='footer'>
                        <p>This reset link will expire in 1 hour for security reasons.</p>
                        <p>© 2024 BMYA-SHELDANG | Bishnupriya Manipuri Youth Association</p>
                    </div>
                </div>
            </div>
        </body>
        </html>
        ";
        
        // Send email using PHPMailer
        $email_result = sendEmail($email, "🔐 Password Reset Request - BMYA-SHELDANG", $email_body);
        
        if ($email_result['success']) {
            $success = "✅ Password reset link has been sent to your email address.<br>Please check your inbox (and spam folder).";
            $step = 'sent';
        } else {
            // If email fails, show link for development
            $success = "⚠️ Email could not be sent. Please use this link to reset your password:<br>
                        <div style='background: #f0f0f0; padding: 10px; border-radius: 5px; margin-top: 10px; word-break: break-all;'>
                            <a href='$reset_link' target='_blank'>$reset_link</a>
                        </div>
                        <p style='margin-top: 10px;'><small>Error: " . $email_result['message'] . "</small></p>";
            $step = 'sent';
        }
    } else {
        $error = "❌ Email address not found in our records.";
    }
}
?>
<!-- Rest of your HTML remains the same -->