<?php
require 'config/conn.php';
require 'config/session.php';
require 'vendor/autoload.php';

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

// Check if this is a form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['forgot_password'])) {
    $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. go to login to do so"];
        header("Location: forgot_password.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@Athenian.com', 'Athenian University');
        $mail->addAddress($email, $user['full_name']);
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Password Reset Request';
        
        $reset_link = "https://localhost/school-project/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: #FBBB01; 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: #FBBB01; margin-top: 0;'>Hello {$user['full_name']},</h2>
                
                <p style='font-size: 16px;'>We received a request to reset your password for your Athenian University account.</p>
                
                <div style='background-color: #f0f7ff; border-left: 4px solid #FBBB01; 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: #FBBB01; 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: #FBBB01;'>$reset_link</p>
                </div>
            </div>
            
            <div style='background-color: #f5f5f5; padding: 15px; text-align: center; font-size: 12px; color: #666;'>
                <p>© " . date('Y') . " Athenian University. All rights reserved.</p>
            </div>
        </div>
        ";
        
        $mail->AltBody = "Hello {$user['full_name']},\n\n"
            . "We received a request to reset your password for your Athenian University 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"
            . "Athenian University";
        
        $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>Athenian University - Forgot Password</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <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">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#fbbb01',
                        primaryDark: '#d9a401',
                        primaryLight: '#fdd45a',
                    },
                    fontFamily: {
                        poppins: ['Poppins', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .bg-primary-gradient {
                @apply bg-gradient-to-r from-primary to-primaryLight;
            }
            .text-primary-gradient {
                @apply bg-primary-gradient bg-clip-text text-transparent;
            }
            .animate-fadeIn {
                animation: fadeIn 0.5s ease;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(10px); }
                to { opacity: 1; transform: translateY(0); }
            }
            .btn-loading .btn-text {
                @apply invisible opacity-0;
            }
            .btn-loading::after {
                @apply content-[""] absolute w-5 h-5 top-0 left-0 right-0 bottom-0 m-auto border-2 border-transparent border-t-white rounded-full animate-spin;
            }
        }
    </style>
</head>
<body class="bg-gray-50 text-gray-800 font-poppins min-h-screen flex justify-center items-center p-5">
    <div class="w-full max-w-md flex flex-col items-center">
        <!-- Header -->
        <div class="text-center mb-8">
            <h1 class="text-4xl font-bold mb-2 text-primary-gradient">Password Recovery</h1>
            <p class="text-gray-600">Reset your password to regain access to your Athenian University account</p>
        </div>

        <!-- Display session messages -->
        <?php 
        if (isset($_SESSION['success_message'])) {
            echo '<div class="w-full p-3 mb-4 rounded-lg bg-green-100 text-green-700 border-l-4 border-green-500">' . $_SESSION['success_message'] . '</div>';
            unset($_SESSION['success_message']);
        }
        
        if (isset($_SESSION['error_messages'])) {
            foreach ($_SESSION['error_messages'] as $error) {
                echo '<div class="w-full p-3 mb-4 rounded-lg bg-red-100 text-red-700 border-l-4 border-red-500">' . $error . '</div>';
            }
            unset($_SESSION['error_messages']);
        }
        
        if (isset($reset_success)): ?>
            <div class="w-full p-3 mb-4 rounded-lg bg-green-100 text-green-700 border-l-4 border-green-500">
                <?php echo $reset_success; ?>
            </div>
        <?php endif; 
        
        if (isset($reset_error)): ?>
            <div class="w-full p-3 mb-4 rounded-lg bg-red-100 text-red-700 border-l-4 border-red-500">
                <?php echo $reset_error; ?>
            </div>
        <?php endif; ?>
        
        <!-- Tabs -->
        <div class="w-full flex mb-8 border-b-2 border-gray-200">
            <div class="flex-1 text-center py-4 cursor-pointer text-gray-500 font-medium" onclick="window.location.href='login.php'">Login</div>
            <div class="flex-1 text-center py-4 cursor-pointer text-gray-500 font-medium" onclick="window.location.href='registration.php'">Register</div>
            <div class="flex-1 text-center py-4 cursor-pointer text-primary font-semibold relative">
                Reset Password
                <div class="absolute bottom-0 left-0 w-full h-0.5 bg-primary"></div>
            </div>
        </div>

        <!-- Form -->
        <div class="w-full relative">
            <form id="forgotForm" class="bg-white rounded-xl shadow-md p-8 animate-fadeIn" method="POST">
                <div class="bg-primary/10 border-l-4 border-primary p-4 rounded-lg mb-6">
                    <p class="font-bold">How to reset your password:</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="mb-5">
                    <label for="forgotEmail" class="block mb-2 font-medium">Email Address</label>
                    <div class="relative">
                        <i class="fas fa-envelope absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                        <input type="email" id="forgotEmail" name="email" class="w-full pl-10 pr-4 py-3 bg-white border border-gray-200 rounded-lg text-gray-800 focus:outline-none focus:border-primary transition" 
                               placeholder="Enter your registered email" required value="<?php echo htmlspecialchars($email); ?>">
                    </div>
                    <?php if (!empty($errors['email'])): ?>
                        <small class="text-red-500 text-sm mt-1 block"><?php echo $errors['email']; ?></small>
                    <?php endif; ?>
                </div>
                
                <button type="submit" class="w-full py-3 bg-primary text-white rounded-lg font-medium mt-5 hover:bg-primaryDark transition relative" id="forgotBtn" name="forgot_password">
                    <span class="btn-text">Send Reset Link</span>
                </button>
                
                <div class="text-center mt-5 text-gray-600">
                    Remember your password? <a href="login.php" class="text-primary hover:underline">Sign in</a>
                </div>
            </form>
        </div>
    </div>
</body>
</html>
<?php
// Clear form data from session after displaying it
if (isset($_SESSION['form_data'])) {
    unset($_SESSION['form_data']);
}
?>