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

// Check if token is valid
if (!isset($_GET['token']) || !isset($_GET['email'])) {
    $_SESSION['reset_error'] = "Invalid password reset link";
    header("Location: forgot_password.php");
    exit();
}

$token = $_GET['token'];
$email = $_GET['email'];

// Check if token exists and is not expired
$query = "SELECT id, reset_token_expiry FROM students 
          WHERE email = ? AND reset_token = ? AND reset_token_expiry > NOW()";
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $email, $token);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['reset_error'] = "Invalid or expired password reset link";
    header("Location: forgot_password.php");
    exit();
}

// Initialize error messages
$errors = [
    'password' => '',
    'confirm_password' => ''
];

// If form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_password'])) {
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    
    // Validate password
    if (empty($password)) {
        $errors['password'] = "Password is required";
    } elseif (strlen($password) < 8) {
        $errors['password'] = "Password must be at least 8 characters";
    } elseif (!preg_match("/[A-Z]/", $password)) {
        $errors['password'] = "Password must contain at least one uppercase letter";
    } elseif (!preg_match("/[a-z]/", $password)) {
        $errors['password'] = "Password must contain at least one lowercase letter";
    } elseif (!preg_match("/[0-9]/", $password)) {
        $errors['password'] = "Password must contain at least one number";
    } elseif (!preg_match("/[^A-Za-z0-9]/", $password)) {
        $errors['password'] = "Password must contain at least one special character";
    }
    
    // Validate confirm password
    if (empty($confirm_password)) {
        $errors['confirm_password'] = "Please confirm your password";
    } elseif ($password !== $confirm_password) {
        $errors['confirm_password'] = "Passwords do not match";
    }
    
    // If no errors, update password
    if (empty($errors['password']) && empty($errors['confirm_password'])) {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
        // Update password and clear reset token
        $update_query = "UPDATE students SET password = ?, reset_token = NULL, reset_token_expiry = NULL 
                         WHERE email = ?";
        $update_stmt = $conn->prepare($update_query);
        $update_stmt->bind_param("ss", $hashed_password, $email);
        
        if ($update_stmt->execute()) {
            $_SESSION['success_message'] = "Password updated successfully. You can now login with your new password.";
            header("Location: reset_password.php");
            exit();
        } else {
            $_SESSION['error_messages'] = ["Failed to update password. Please try again."];
            header("Location: reset_password.php?token=$token&email=$email");
            exit();
        }
    } else {
        $_SESSION['reset_errors'] = $errors;
        header("Location: reset_password.php?token=$token&email=$email");
        exit();
    }
}

// If there are validation errors from form submission, display them
if (isset($_SESSION['reset_errors'])) {
    $errors = array_merge($errors, $_SESSION['reset_errors']);
    unset($_SESSION['reset_errors']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Portal - Reset 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">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#fbbb01',
                    },
                    fontFamily: {
                        poppins: ['Poppins', 'sans-serif'],
                    },
                }
            }
        }
    </script>
</head>
<body class="bg-gray-100 font-poppins flex justify-center items-center min-h-screen p-5">
    <div class="w-full max-w-md">
        <div class="text-center mb-8">
            <h1 class="text-3xl font-bold mb-2 bg-gradient-to-r from-primary to-yellow-400 bg-clip-text text-transparent">Set New Password</h1>
            <p class="text-gray-600">Create a new password for your account</p>
        </div>

        <!-- Display session messages -->
        <?php 
        if (isset($_SESSION['error_messages'])) {
            foreach ($_SESSION['error_messages'] as $error) {
                echo '<div class="bg-red-50 text-red-600 border-l-4 border-red-600 p-3 rounded mb-5">' . $error . '</div>';
            }
            unset($_SESSION['error_messages']);
        }
        ?>
        
        <div class="bg-white rounded-lg shadow-md p-6">
            <form id="resetForm" method="POST">
                <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
                <input type="hidden" name="email" value="<?php echo htmlspecialchars($email); ?>">
                
                <div class="mb-5">
                    <label for="resetPassword" class="block font-medium text-gray-700 mb-2">New Password</label>
                    <div class="relative">
                        <i class="fas fa-lock absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                        <input type="password" id="resetPassword" name="password" class="w-full pl-10 pr-10 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="Enter new password" required>
                        <i class="fas fa-eye absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 cursor-pointer" id="toggleResetPassword"></i>
                    </div>
                    <?php if (!empty($errors['password'])): ?>
                        <small class="text-red-500 text-sm"><?php echo $errors['password']; ?></small>
                    <?php endif; ?>
                    <small class="text-gray-500 text-sm mt-1 block">
                        Must be at least 8 characters with one uppercase, one lowercase, one number, and one special character
                    </small>
                </div>
                
                <div class="mb-5">
                    <label for="resetConfirmPassword" class="block font-medium text-gray-700 mb-2">Confirm New Password</label>
                    <div class="relative">
                        <i class="fas fa-lock absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                        <input type="password" id="resetConfirmPassword" name="confirm_password" class="w-full pl-10 pr-10 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="Confirm new password" required>
                        <i class="fas fa-eye absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 cursor-pointer" id="toggleResetConfirmPassword"></i>
                    </div>
                    <?php if (!empty($errors['confirm_password'])): ?>
                        <small class="text-red-500 text-sm"><?php echo $errors['confirm_password']; ?></small>
                    <?php endif; ?>
                </div>
                
                <button type="submit" class="w-full bg-primary hover:bg-yellow-600 text-white font-medium py-2 px-4 rounded-md transition duration-300" id="resetBtn" name="reset_password">
                    <span class="btn-text">Update Password</span>
                </button>
                
                <div class="text-center mt-4 text-gray-600">
                    Remember your password? <a href="login.php" class="text-primary hover:underline">Sign in</a>
                </div>
            </form>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Password Toggle Visibility
            function setupPasswordToggle(toggleId, inputId) {
                const toggle = document.getElementById(toggleId);
                const input = document.getElementById(inputId);
                
                toggle.addEventListener('click', function() {
                    if (input.type === 'password') {
                        input.type = 'text';
                        toggle.classList.remove('fa-eye');
                        toggle.classList.add('fa-eye-slash');
                    } else {
                        input.type = 'password';
                        toggle.classList.remove('fa-eye-slash');
                        toggle.classList.add('fa-eye');
                    }
                });
            }
            
            setupPasswordToggle('toggleResetPassword', 'resetPassword');
            setupPasswordToggle('toggleResetConfirmPassword', 'resetConfirmPassword');
        });
    </script>
</body>
</html>
<?php
// Clear session messages
if (isset($_SESSION['reset_errors'])) {
    unset($_SESSION['reset_errors']);
}
?>