<?php
require_once "include/session.php";
if (isLoggedIn()) {
  header("Location: dashboard.php");
}
$email = $_GET['vemail'];
session_start();
require_once "include/db.php";
require_once 'functions.php'; // Make sure this contains log_audit()

// Handle resend-code GET request
if (isset($_GET['resend-code'])) {
    $email = trim($_GET['resend-code']);
    $otp = generateOTP(); // Assuming 6-digit code
    $expiry = date("Y-m-d H:i:s", strtotime("+10 minutes"));

    // Prepare the update statement
    $stmt = $conn->prepare("UPDATE users SET otp_code = ?, otp_expiry = ? WHERE email = ?");
    $stmt->bind_param("sss", $otp, $expiry, $email);

    if ($stmt->execute() && $stmt->affected_rows > 0) {
        // ✅ Send OTP Email
        sendOTP($email, $otp);

        // ✅ Log audit
        log_audit(
            $conn,
            "OTP Regenerated for Existing User",
            "users",
            null,
            null,
            json_encode([
                "email" => $email,
                "otp" => $otp
            ]),
            $_SERVER['REMOTE_ADDR'],
            $_SERVER['HTTP_USER_AGENT'],
            $email,
            "RegisterPortal"
        );

        $success = "An OTP has been re-sent to your email.";
    } else {
        $error = "No matching email found or OTP update failed.";
    }
}

// Email Verification Handler
if (isset($_POST['verify_email_submit'])) {
    require_once "include/db.php";
    require_once 'functions.php';

    $email = trim($_GET['vemail']);
    $otp = implode('', $_POST['code']); // Join OTP inputs

    $stmt = $conn->prepare("SELECT id, otp_code, otp_expiry FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();

    // Check if we got a result
    if ($stmt->num_rows === 0) {
        $error2 = "Account not found.";
    }

    $stmt->bind_result($user_id, $stored_otp, $otp_expiry);
    $stmt->fetch();
    $stmt->close();

    if ($otp !== $stored_otp) {
        $error2 = "Invalid OTP entered.";
    } elseif (strtotime($otp_expiry) < time()) {
        $error2 = "OTP has expired. Please request a new one.";
    } else {
        $stmt = $conn->prepare("UPDATE users SET otp_code = NULL, otp_expiry = NULL, is_verified = 1 WHERE email = ?");
        $stmt->bind_param("s", $email);
        if ($stmt->execute()) {
            // ✅ Audit log
            log_audit(
                $conn,
                "Email Verified",
                "users",
                $user_id,
                null,
                json_encode(["email" => $email]),
                $_SERVER['REMOTE_ADDR'],
                $_SERVER['HTTP_USER_AGENT'],
                $email,
                "VerifyOTP"
            );
        
            // ✅ Use reusable function to send email
            sendVerificationSuccessEmail($email);
        
            $success2 = "Email verified successfully. You may now log in.";
            header("Location: login");
            exit;
        } else {
            $error2 = "Something went wrong. Try again.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OTP Confirmation | 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 class="auth-form active">
                    <?php if ($email): ?>
                    <h2 class="form-title">Verify Your Email</h2>
                    <div class="form-group">
                        <p class="text-center">We've sent a 6-digit code to your email<br><strong><?php echo $email ?></strong></p>
                        <?php if (!empty($success)): ?>
                            <div class="success-message">
                                <span class="close-btn">&times;</span>
                                <i class="fas fa-check-circle"></i> <?= $success ?>
                                <p>Redirecting in 5 seconds...</p>
                                <script>
                                    setTimeout(function() {
                                        window.location.href = "https://healthburo.com/verify-email?vemail=<?= urlencode($email) ?>";
                                    }, 5000);
                                </script>
                            </div>
                        <?php elseif (!empty($error)): ?>
                            <div class="error-message">
                                <span class="close-btn">&times;</span>
                                <i class="fas fa-times-circle"></i> <?= $error ?>
                                <p>Redirecting in 5 seconds...</p>
                                <script>
                                    setTimeout(function() {
                                        window.location.href = "https://healthburo.com/verify-email?vemail=<?= urlencode($email) ?>";
                                    }, 5000);
                                </script>
                            </div>
                        <?php endif; ?>
                        <?php if (!empty($success2)): ?>
                            <div class="success-message">
                                <span class="close-btn">&times;</span>
                                <i class="fas fa-check-circle"></i> <?= $success2 ?>
                                <p>Redirecting in 5 seconds...</p>
                                <script>
                                    setTimeout(function() {
                                        window.location.href = "login";
                                    }, 5000);
                                </script>
                            </div>
                        <?php elseif (!empty($error2)): ?>
                            <div class="error-message">
                                <span class="close-btn">&times;</span>
                                <i class="fas fa-times-circle"></i> <?= $error2 ?>
                                <p>Redirecting in 5 seconds...</p>
                                <script>
                                    setTimeout(function() {
                                        window.location.href = "login";
                                    }, 5000);
                                </script>
                            </div>
                        <?php endif; ?>
                        <div class="otp-container">
                            <input type="int" name="code[]" class="otp-input" maxlength="1" required>
                            <input type="int" name="code[]" class="otp-input" maxlength="1" required>
                            <input type="int" name="code[]" class="otp-input" maxlength="1" required>
                            <input type="int" name="code[]" class="otp-input" maxlength="1" required>
                            <input type="int" name="code[]" class="otp-input" maxlength="1" required>
                            <input type="int" name="code[]" class="otp-input" maxlength="1" required>
                        </div>
                        
                        <div class="resend-link">
                            Didn't receive the code? <a href="?resend-code=<?php echo $email ?>">Resend Code</a>
                        </div>
                        
                        <button class="btn btn-primary" name="verify_email_submit">Verify Account</button>
                    </div>
                    <?php endif; ?>
                    <div class="auth-footer">
                        <a href="sign-up" id="back-to-signup">Back to Registration</a>
                    </div>
                    <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>';
                }
            });
            
        });
        const inputs = document.querySelectorAll('.otp-input');

          inputs.forEach((input, index) => {
            input.addEventListener('input', (e) => {
              const value = e.target.value;
              if (value.length === 1 && index < inputs.length - 1) {
                inputs[index + 1].focus();
              }
            });
        
            input.addEventListener('keydown', (e) => {
              if (e.key === "Backspace" && !input.value && index > 0) {
                inputs[index - 1].focus();
              }
            });
        });
    </script>
</body>
</html>