<?php
require_once "include/session.php";
if (isLoggedIn()) {
  header("Location: dashboard.php");
}
require_once "include/db.php";
require_once "functions.php"; // contains log_audit()

$token = $_GET['token'] ?? '';
$isValidToken = false;
$error = $success = "";

// STEP 1: Validate token
if ($token) {
    $stmt = $conn->prepare("SELECT id, email FROM users WHERE reset_token = ? AND token_expiry > NOW()");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($user_id, $user_email);
        $stmt->fetch();
        $isValidToken = true;

        // Log token usage
        log_audit($conn, "Reset Password Token Used", "users", $user_id, null, "Valid token accessed", $user_id, $user_email, $token, "GuestPortal");
    } else {
        $error = "The reset link is invalid or has expired.";
        log_audit($conn, "Invalid Reset Token Attempt", "users", null, null, "Attempted token: $token", null, null, $token, "GuestPortal");
    }
} else {
    $error = "Missing reset token.";
}

// STEP 2: Handle reset form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_submit'])) {
    require_once "includes/db.php";
    require_once 'functions.php';

    $token = $_POST['token'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    $success = $error = "";

    $stmt = $conn->prepare("SELECT id, email FROM users WHERE reset_token = ? AND token_expiry > NOW()");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows === 0) {
        $error = "Token has expired or is invalid.";
    } elseif ($new_password !== $confirm_password) {
        $error = "Passwords do not match.";
    } else {
        $stmt->bind_result($user_id, $user_email);
        $stmt->fetch();

        $hashed = password_hash($new_password, PASSWORD_BCRYPT);

        $update = $conn->prepare("UPDATE users SET password = ?, reset_token = NULL, token_expiry = NULL WHERE id = ?");
        $update->bind_param("si", $hashed, $user_id);

        if ($update->execute()) {
            $success = "Password reset successfully. You can now login";

            log_audit(
                $conn,
                "Password Reset Success",
                "users",
                $user_id,
                null,
                "User reset password",
                $user_id,
                $user_email,
                $token,
                "UserPortal"
            );

            sendPasswordResetConfirmation($user_email);

        } else {
            $error = "Password reset failed. Please try again.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Password | HealthBüro Healthcare Management</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- [favicon] begin -->
    <link rel="shortcut icon" type="image/x-icon" href="https://sylvianettebox.net/favicon.ico" />
    <link rel="icon" type="image/x-icon" href="https://sylvianettebox.net/favicon.ico" />
    <!-- [favicon] end -->
    <link rel="stylesheet" href="auth.css" type="text/css"  />
    
</head>
<body>
    <div class="auth-container">
        <button class="theme-toggle" id="themeToggle">
            <i class="fas fa-moon"></i>
        </button>
        
        <?php include 'illustrator.php'?>
        
        <div class="auth-forms">
            <div class="logo">
                <h1>HealthBüro</h1>
                <p>Healthcare Management System</p>
            </div>
            
            <!-- Reset Password Form -->
            <form method="POST">
                <div id="reset-password-form" class="auth-form active">
                    <h2 class="form-title">Create New Password</h2>
                    <?php if (!empty($success)): ?>
                        <div class="success-message">
                            <span class="close-btn">&times;</span>
                            <i class="fas fa-check-circle"></i> <?= $success ?>
                        </div>
                    <?php elseif (!empty($error)): ?>
                        <div class="error-message">
                            <span class="close-btn">&times;</span>
                            <i class="fas fa-times-circle"></i> <?= $error ?>
                        </div>
                    <?php endif; ?>
                    <?php if ($isValidToken): ?>
                    <div class="form-group">
                        <div class="input-group">
                            <i class="fas fa-lock input-icon"></i>
                            <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">
                            <input type="password" name="new_password" class="form-control" placeholder="Enter your new password">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <div class="input-group">
                            <i class="fas fa-lock input-icon"></i>
                            <input type="password" name="confirm_password" class="form-control" placeholder="Confirm your new password">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <button class="btn btn-primary" name="reset_submit">Update Password</button>
                    </div>
                    <?php endif; ?>
                    <div class="auth-footer">
                        <a href="login" >Back to Login</a>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Theme toggle
            const themeToggle = document.getElementById('themeToggle');
            const body = document.body;
            
            themeToggle.addEventListener('click', function() {
                body.classList.toggle('dark-mode');
                
                if (body.classList.contains('dark-mode')) {
                    themeToggle.innerHTML = '<i class="fas fa-sun"></i>';
                } else {
                    themeToggle.innerHTML = '<i class="fas fa-moon"></i>';
                }
            });
            
        });
        document.getElementById('toggle-login-password').addEventListener('click', function () {
            const passwordInput = document.getElementById('login-password');
            const toggleIcon = this;
        
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                toggleIcon.classList.remove('fa-eye');
                toggleIcon.classList.add('fa-eye-slash');
            } else {
                passwordInput.type = 'password';
                toggleIcon.classList.remove('fa-eye-slash');
                toggleIcon.classList.add('fa-eye');
            }
        });
        document.querySelectorAll('.close-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                this.parentElement.style.display = 'none';
            });
        });
    </script>
</body>
</html>