<?php
session_start();
require 'config/conn.php';
require 'config/session.php';

// Check if this is a form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['forgot_password'])) {
    require 'vendor/autoload.php';
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

    $email = trim($_POST['email']);
    
    // Store form data in session in case of errors
    $_SESSION['form_data'] = [
        'email' => $email
    ];
    
    // Validate email
    $errors = [];
    
    if (empty($email)) {
        $errors['email'] = "Email is required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = "Invalid email format";
    }
    
    if (!empty($errors)) {
        $_SESSION['forgot_errors'] = $errors;
        header("Location: forgot_password.php");
        exit();
    }
    
    // Check if email exists and account is verified
    $stmt = $conn->prepare("SELECT id, full_name, is_verified FROM students WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        $errors['email'] = "Email not registered";
        $_SESSION['forgot_errors'] = $errors;
        header("Location: forgot_password.php");
        exit();
    }
    
    $user = $result->fetch_assoc();
    
    if (!$user['is_verified']) {
        $_SESSION['error_messages'] = ["Your account is not verified. Please verify your account first."];
        header("Location: login.php");
        exit();
    }
    
    // Generate reset token
    $reset_token = bin2hex(random_bytes(32));
    $reset_token_expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));
    
    // Update user record with reset token
    $stmt = $conn->prepare("UPDATE students SET reset_token = ?, reset_token_expiry = ? WHERE email = ?");
    $stmt->bind_param("sss", $reset_token, $reset_token_expiry, $email);
    $stmt->execute();
    
    // Send reset email
    $mail = new PHPMailer(true);
    
    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'holuwaseunisrael@gmail.com';
        $mail->Password   = 'ceae tepn tfyx oxjn';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = 465;
        
        // Recipients
        $mail->setFrom('noreply@omstech.com', 'Omstech Academy');
        $mail->addAddress($email, $user['full_name']);
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Password Reset Request';
        
        $reset_link = "https://localhost/cv/reset_password.php?token=$reset_token&email=" . urlencode($email);
        
        $mail->Body = "
        <div style='max-width: 600px; margin: 0 auto; border: 1px solid #e0e0e0; border-radius: 8px; overflow: hidden;'>
            <div style='background-color: #1E88E5; padding: 25px; text-align: center;'>
                <h1 style='color: white; margin: 0; font-size: 24px;'>Password Reset Request</h1>
            </div>
            
            <div style='padding: 25px;'>
                <h2 style='color: #1E88E5; margin-top: 0;'>Hello {$user['full_name']},</h2>
                
                <p style='font-size: 16px;'>We received a request to reset your password for your Omstech Academy account.</p>
                
                <div style='background-color: #f0f7ff; border-left: 4px solid #1E88E5; padding: 15px; margin: 20px 0;'>
                    <p>If you didn't make this request, you can safely ignore this email.</p>
                    <p>Otherwise, click the button below to reset your password:</p>
                </div>
                
                <div style='text-align: center; margin: 25px 0;'>
                    <a href='$reset_link' style='display: inline-block; padding: 12px 25px; background-color: #1E88E5; color: white; text-decoration: none; border-radius: 5px; font-weight: bold;'>
                        Reset Password
                    </a>
                </div>
                
                <p style='font-size: 14px; color: #666;'>This link will expire in 1 hour. If you need a new link, you can request another password reset.</p>
                
                <div style='background-color: #f5f5f5; padding: 15px; border-radius: 5px; margin-top: 20px;'>
                    <p style='margin: 0; font-size: 13px; color: #666;'>If the button above doesn't work, copy and paste this link into your browser:</p>
                    <p style='margin: 5px 0 0; word-break: break-all; font-size: 13px; color: #1E88E5;'>$reset_link</p>
                </div>
            </div>
            
            <div style='background-color: #f5f5f5; padding: 15px; text-align: center; font-size: 12px; color: #666;'>
                <p>© " . date('Y') . " Omstech Academy. All rights reserved.</p>
            </div>
        </div>
        ";
        
        $mail->AltBody = "Hello {$user['full_name']},\n\n"
            . "We received a request to reset your password for your Omstech Academy account.\n\n"
            . "Please click the following link to reset your password:\n"
            . "$reset_link\n\n"
            . "This link will expire in 1 hour. If you didn't request this, you can ignore this email.\n\n"
            . "Best regards,\n"
            . "Omstech Academy";
        
        $mail->send();
        
        // Clear form data from session
        unset($_SESSION['form_data']);
        
        // Set success message
        $_SESSION['success_message'] = "Password reset link sent to your email. Please check your inbox (and spam folder).";
        header("Location: forgot_password.php");
        exit();
        
    } catch (Exception $e) {
        $_SESSION['error_messages'] = ["Failed to send password reset email. Please try again later."];
        header("Location: forgot_password.php");
        exit();
    }
}

// Initialize error messages
$errors = [
    'email' => ''
];

// Retrieve form data from session if available
$form_data = isset($_SESSION['form_data']) ? $_SESSION['form_data'] : [];
$email = $form_data['email'] ?? '';

// If there are validation errors from form submission, display them
if (isset($_SESSION['forgot_errors'])) {
    $errors = array_merge($errors, $_SESSION['forgot_errors']);
    unset($_SESSION['forgot_errors']);
}

// Check for password reset messages
if (isset($_SESSION['reset_success'])) {
    $reset_success = $_SESSION['reset_success'];
    unset($_SESSION['reset_success']);
}

if (isset($_SESSION['reset_error'])) {
    $reset_error = $_SESSION['reset_error'];
    unset($_SESSION['reset_error']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Portal - Forgot Password</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        :root {
            --primary-bg: #1a202c;
            --secondary-bg: #2d3748;
            --sidebar-bg: #171923;
            --text-primary: #f7fafc;
            --text-secondary: #e2e8f0;
            --accent-color: #4299e1;
            --card-bg: #2d3748;
            --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            --error-color: #e53e3e;
            --success-color: #48bb78;
        }

        .light-mode {
            --primary-bg: #f7fafc;
            --secondary-bg: #edf2f7;
            --sidebar-bg: #ffffff;
            --text-primary: #1a202c;
            --text-secondary: #4a5568;
            --accent-color: #3182ce;
            --card-bg: #ffffff;
            --shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            --error-color: #f56565;
            --success-color: #68d391;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            transition: background-color 0.3s, color 0.3s, transform 0.3s;
        }

        body {
            font-family: 'Poppins', 'Helvetica', sans-serif;
            background-color: var(--primary-bg);
            color: var(--text-primary);
            line-height: 1.6;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .auth-container {
            width: 100%;
            max-width: 1200px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .auth-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .auth-header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            background: linear-gradient(90deg, var(--accent-color), #63b3ed);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
        }

        .auth-header p {
            color: var(--text-secondary);
            font-size: 1.1rem;
        }

        .auth-tabs {
            display: flex;
            margin-bottom: 30px;
            border-bottom: 2px solid var(--secondary-bg);
            width: 100%;
            max-width: 500px;
        }

        .auth-tab {
            flex: 1;
            text-align: center;
            padding: 15px 0;
            cursor: pointer;
            font-weight: 500;
            color: var(--text-secondary);
            position: relative;
        }

        .auth-tab.active {
            color: var(--accent-color);
            font-weight: 600;
        }

        .auth-tab.active::after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 0;
            width: 100%;
            height: 2px;
            background-color: var(--accent-color);
        }

        .auth-forms {
            width: 100%;
            max-width: 500px;
            position: relative;
        }

        .auth-form {
            background-color: var(--card-bg);
            border-radius: 10px;
            padding: 30px;
            box-shadow: var(--shadow);
            display: none;
        }

        .auth-form.active {
            display: block;
            animation: fadeIn 0.5s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text-primary);
        }

        .input-wrapper {
            position: relative;
        }

        .form-control {
            width: 100%;
            padding: 12px 15px 12px 40px;
            border: 1px solid var(--secondary-bg);
            border-radius: 8px;
            background-color: var(--primary-bg);
            color: var(--text-primary);
            font-family: 'Poppins', sans-serif;
            font-size: 1rem;
            transition: border-color 0.3s;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--accent-color);
        }

        .input-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-secondary);
        }

        .btn {
            display: inline-block;
            width: 100%;
            padding: 12px;
            background-color: var(--accent-color);
            color: white;
            border: none;
            border-radius: 8px;
            font-family: 'Poppins', sans-serif;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.3s;
            margin-top: 20px;
            position: relative;
        }

        .btn:hover {
            background-color: #3182ce;
        }

        .auth-switch {
            text-align: center;
            margin-top: 20px;
            color: var(--text-secondary);
        }

        .auth-switch a {
            color: var(--accent-color);
            text-decoration: none;
            margin-left: 5px;
        }

        .auth-switch a:hover {
            text-decoration: underline;
        }

        .mode-toggle-container {
            position: fixed;
            top: 20px;
            right: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            z-index: 100;
        }

        .mode-toggle-label {
            color: var(--text-secondary);
            font-size: 0.9rem;
        }

        .mode-toggle {
            width: 60px;
            height: 30px;
            background-color: var(--secondary-bg);
            border-radius: 15px;
            cursor: pointer;
            display: flex;
            align-items: center;
            padding: 0 5px;
            position: relative;
        }

        .toggle-ball {
            width: 20px;
            height: 20px;
            background-color: var(--accent-color);
            border-radius: 50%;
            position: absolute;
            left: 5px;
            transition: transform 0.3s;
        }

        .light-mode .toggle-ball {
            transform: translateX(30px);
        }

        .form-message {
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }

        .error-message {
            background-color: rgba(229, 62, 62, 0.1);
            color: var(--error-color);
            border-left: 3px solid var(--error-color);
        }

        .success-message {
            background-color: rgba(72, 187, 120, 0.1);
            color: var(--success-color);
            border-left: 3px solid var(--success-color);
        }

        .error-text {
            color: var(--error-color);
            font-size: 0.8rem;
            margin-top: 5px;
            display: block;
        }

        .reset-instructions {
            background-color: rgba(66, 153, 225, 0.1);
            border-left: 4px solid var(--accent-color);
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 8px;
        }
        
        .reset-instructions p {
            margin-bottom: 10px;
        }

        /* Loading spinner for submit button */
        .btn-loading .btn-text {
            visibility: hidden;
            opacity: 0;
        }
        
        .btn-loading::after {
            content: "";
            position: absolute;
            width: 20px;
            height: 20px;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
            border: 3px solid transparent;
            border-top-color: white;
            border-radius: 50%;
            animation: button-loading-spinner 1s ease infinite;
        }
        
        @keyframes button-loading-spinner {
            from { transform: rotate(0turn); }
            to { transform: rotate(1turn); }
        }

        @media (max-width: 768px) {
            .auth-header h1 {
                font-size: 2rem;
            }
            
            .auth-header p {
                font-size: 1rem;
            }
            
            .auth-form {
                padding: 25px;
            }
        }

        @media (max-width: 480px) {
            .auth-header h1 {
                font-size: 1.8rem;
            }
            
            .auth-tabs {
                max-width: 100%;
            }
            
            .mode-toggle-container {
                top: 10px;
                right: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="auth-container">
        <div class="auth-header">
            <h1>Password Recovery</h1>
            <p>Reset your password to regain access to your account</p>
        </div>

        <!-- Display session messages -->
        <?php 
        if (isset($_SESSION['success_message'])) {
            echo '<div class="form-message success-message" style="display: block;">' . $_SESSION['success_message'] . '</div>';
            unset($_SESSION['success_message']);
        }
        
        if (isset($_SESSION['error_messages'])) {
            foreach ($_SESSION['error_messages'] as $error) {
                echo '<div class="form-message error-message" style="display: block;">' . $error . '</div>';
            }
            unset($_SESSION['error_messages']);
        }
        
        // Display password reset messages
        if (isset($reset_success)): ?>
            <div class="form-message success-message" style="display: block;">
                <?php echo $reset_success; ?>
            </div>
        <?php endif; 
        
        if (isset($reset_error)): ?>
            <div class="form-message error-message" style="display: block;">
                <?php echo $reset_error; ?>
            </div>
        <?php endif; ?>
        
        <div class="auth-tabs">
            <div class="auth-tab" onclick="window.location.href='login.php'">Login</div>
            <div class="auth-tab" onclick="window.location.href='registration.php'">Register</div>
            <div class="auth-tab active">Reset Password</div>
        </div>

        <div class="auth-forms">
            <form id="forgotForm" class="auth-form active" method="POST">
                <div class="reset-instructions">
                    <p><strong>How to reset your password:</strong></p>
                    <p>1. Enter your email address below</p>
                    <p>2. Check your email for a password reset link</p>
                    <p>3. Follow the instructions to set a new password</p>
                </div>
                
                <div class="form-group">
                    <label for="forgotEmail">Email Address</label>
                    <div class="input-wrapper">
                        <i class="fas fa-envelope input-icon"></i>
                        <input type="email" id="forgotEmail" name="email" class="form-control" 
                               placeholder="Enter your registered email" required value="<?php echo htmlspecialchars($email); ?>">
                    </div>
                    <?php if (!empty($errors['email'])): ?>
                        <small class="error-text"><?php echo $errors['email']; ?></small>
                    <?php endif; ?>
                </div>
                
                <button type="submit" class="btn" id="forgotBtn" name="forgot_password">
                    <span class="btn-text">Send Reset Link</span>
                </button>
                
                <div class="auth-switch">
                    Remember your password? <a href="login.php" class="switch-to-login">Sign in</a>
                </div>
            </form>
        </div>
    </div>

    <!-- Dark/Light Mode Toggle -->
    <div class="mode-toggle-container">
        <span class="mode-toggle-label" id="modeLabel">Dark</span>
        <div class="mode-toggle" id="modeToggle">
            <div class="toggle-ball"></div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Dark/Light Mode Toggle
            const modeToggle = document.getElementById('modeToggle');
            const modeLabel = document.getElementById('modeLabel');
            const body = document.body;
            
            const savedMode = localStorage.getItem('mode');
            const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            
            if (savedMode === 'light' || (!savedMode && !systemPrefersDark)) {
                body.classList.add('light-mode');
                modeLabel.textContent = 'Light';
            } else {
                modeLabel.textContent = 'Dark';
            }
            
            modeToggle.addEventListener('click', function() {
                body.classList.toggle('light-mode');
                
                if (body.classList.contains('light-mode')) {
                    modeLabel.textContent = 'Light';
                    localStorage.setItem('mode', 'light');
                } else {
                    modeLabel.textContent = 'Dark';
                    localStorage.setItem('mode', 'dark');
                }
            });
            
            // Form submission loading state
            const forgotForm = document.getElementById('forgotForm');
            const forgotBtn = document.getElementById('forgotBtn');
            
            if (forgotForm) {
                forgotForm.addEventListener('submit', function() {
                    forgotBtn.classList.add('btn-loading');
                    forgotBtn.disabled = true;
                });
            }
        });
    </script>
</body>
</html>
<?php
// Clear form data from session after displaying it
if (isset($_SESSION['form_data'])) {
    unset($_SESSION['form_data']);
}
?>