<?php
require_once "include/session.php";
if (isLoggedIn()) {
  header("Location: dashboard.php");
}
if (isset($_POST['reg_submit'])) {
    require_once "include/db.php";
    require_once 'functions.php'; // Make sure this contains log_audit() and handleImageUpload()

    $user_type  = $_POST['user_type'] ?? 'Regular';
    $userID     = trim($_POST['userID'] ?? '');
    $email      = trim($_POST['email'] ?? '');
    $password   = $_POST['password'] ?? '';
    $confirm_pw = $_POST['password_confirm'] ?? '';
    $name       = trim($_POST['name'] ?? '');
    $phone      = trim($_POST['phone'] ?? '');
    $address    = trim($_POST['address'] ?? '');

    // Handle image upload
    $profile_pic = handleImageUpload('profile_pic', 'profile_pics');

    // VALIDATION
    if ($password !== $confirm_pw) {
        $error = "Passwords do not match.";
    } else {
        // Check if email already exists
        $check = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $check->bind_param("s", $email);
        $check->execute();
        $check->store_result();

        if ($check->num_rows > 0) {
            $error = "An account with this email already exists.";
        } else {
            $otp = generateOTP();
            $expiry = date("Y-m-d H:i:s", strtotime("+10 minutes"));
            $hashed_password = password_hash($password, PASSWORD_BCRYPT);

            $stmt = $conn->prepare("INSERT INTO users 
                (userID, email, password, user_type, name, phone, address, profile_pic) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssssss", $userID, $email, $hashed_password, $user_type, $name, $phone, $address, $profile_pic);

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

                // Log audit
                log_audit(
                    $conn,
                    "Account Registration",
                    "users",
                    $stmt->insert_id,
                    null,
                    json_encode([
                        "email" => $email,
                        "name" => $name,
                        "user_type" => $user_type
                    ]),
                    $_SERVER['REMOTE_ADDR'],
                    $_SERVER['HTTP_USER_AGENT'],
                    $email,
                    "RegisterPortal"
                );

                // Redirect with success message (GET parameter)
                $success = 'Kindly check your eMail for OTP to complete registration';
            } else {
                $error = "Something went wrong. 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>Sign-Up | 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>
            
            <!-- SignUp Form -->
            <form method="POST" enctype="multipart/form-data">
                <div id="login-form" class="auth-form active">
                    <h2 class="form-title">Login to HealthBüro</h2>
            
                    <?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 ?>
                        </div>
                    <?php endif; ?>
            
                    <input type="hidden" name="user_type" id="user_type" value="Regular">
            
                    <!-- User ID -->
                    <div class="form-group">
                        <div class="input-group">
                            <i class="fas fa-id-card input-icon"></i>
                            <input type="text" class="form-control" name="userID" id="userID" placeholder="User ID" required>
                        </div>
                    </div>
            
                    <!-- Email -->
                    <div class="form-group">
                        <div class="input-group">
                            <i class="fas fa-envelope input-icon"></i>
                            <input type="email" class="form-control" name="email" placeholder="Enter your email address" id="signup-email" required>
                        </div>
                    </div>
            
                    <!-- Password -->
                    <div class="form-group">
                        <div class="input-group">
                            <i class="fas fa-lock input-icon"></i>
                            <input type="password" class="form-control" name="password" placeholder="Create a strong password" id="signup-password" required>
                            <i class="fas fa-eye password-toggle" id="toggle-signup-password"></i>
                        </div>
                    </div>
            
                    <!-- Confirm Password -->
                    <div class="form-group">
                        <div class="input-group">
                            <i class="fas fa-lock input-icon"></i>
                            <input type="password" class="form-control" name="password_confirm" placeholder="Confirm your password" id="signup-confirm" required>
                            <i class="fas fa-eye password-toggle" id="toggle-signup-confirm"></i>
                        </div>
                        <div class="text-danger mt-2" id="password-error" style="display: none;">
                            <i class="fas fa-exclamation-circle"></i> Passwords do not match
                        </div>
                    </div>
            
                    <!-- Full Name -->
                    <div class="form-group">
                        <div class="input-group">
                            <i class="fas fa-user input-icon"></i>
                            <input type="text" class="form-control" placeholder="Enter your full name" id="signup-name" name="name" required>
                        </div>
                    </div>
            
                    <!-- Phone -->
                    <div class="form-group">
                        <div class="input-group">
                            <i class="fas fa-phone input-icon"></i>
                            <input type="tel" class="form-control" placeholder="Enter your phone number" id="signup-phone" name="phone" required>
                        </div>
                    </div>
            
                    <!-- Address -->
                    <div class="form-group">
                        <div class="input-group">
                            <i class="fas fa-map-marker-alt input-icon"></i>
                            <input type="text" class="form-control" placeholder="Enter your address" id="signup-address" name="address">
                        </div>
                    </div>
            
                    <!-- Profile Picture -->
                    <div class="form-group">
                        <div class="input-group">
                            <i class="fas fa-image input-icon"></i>
                            <input type="file" class="form-control" id="signup-profile-pic" name="profile_pic" accept="image/*">
                        </div>
                    </div>
            
                    <!-- Terms -->
                    <div class="terms">
                        <input type="checkbox" id="terms" reqiured>
                        <label for="terms">I agree to the <a href="#">Terms of Service</a> and <a href="#">Privacy Policy</a></label>
                    </div>
            
                    <!-- Submit -->
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary" id="signup-btn" name="reg_submit">Create Account</button>
                    </div>
            
                    <!-- Footer -->
                    <div class="auth-footer">
                        Already have an account? <a href="login">Sign In</a>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <?php if (isset($success)) {
        header("Refresh:5; healthburo.com/verify-email?vemail={$email}");
        exit;
    }?>
    <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>';
                }
            });
            
        });
        // Password match validation
        const password = document.getElementById('signup-password');
        const confirmPassword = document.getElementById('signup-confirm');
        const errorMessage = document.getElementById('password-error');
        const submitBtn = document.getElementById('signup-btn');
    
        function checkPasswords() {
            if (password.value && confirmPassword.value && password.value !== confirmPassword.value) {
                errorMessage.style.display = 'block';
                submitBtn.disabled = true;
            } else {
                errorMessage.style.display = 'none';
                submitBtn.disabled = false;
            }
        }
    
        password.addEventListener('input', checkPasswords);
        confirmPassword.addEventListener('input', checkPasswords);
    
        // Password toggle function
        function togglePasswordVisibility(toggleId, inputId) {
            const toggleIcon = document.getElementById(toggleId);
            const inputField = document.getElementById(inputId);
    
            toggleIcon.addEventListener('click', () => {
                const type = inputField.getAttribute('type') === 'password' ? 'text' : 'password';
                inputField.setAttribute('type', type);
                toggleIcon.classList.toggle('fa-eye');
                toggleIcon.classList.toggle('fa-eye-slash');
            });
        }
    
        // Enable toggle for both password fields
        togglePasswordVisibility('toggle-signup-password', 'signup-password');
        togglePasswordVisibility('toggle-signup-confirm', 'signup-confirm');
        
        document.querySelectorAll('.close-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                this.parentElement.style.display = 'none';
            });
        });
        // Auto-generate a random userID (prefix + timestamp)
        document.getElementById('userID').value = 'HB-' + Math.floor(10000 + Math.random() * 90000) + '-PT';
    </script>
</body>
</html>