<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';

$error = '';
$success = '';

$settings = get_site_settings($pdo);

// Check if registration is allowed
if (!($settings['allow_registration'] ?? 1)) {
    redirect('login?error=registration_disabled');
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $password_confirm = $_POST['password_confirmation'] ?? '';

    if (empty($name) || empty($email) || empty($password)) {
        $error = "All fields are required.";
    } elseif ($password !== $password_confirm) {
        $error = "Passwords do not match.";
    } elseif (strlen($password) < 8) {
        $error = "Password must be at least 8 characters long.";
    } else {
        try {
            // Check if email already exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                $error = "Email already registered.";
            } else {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $webhook_token = bin2hex(random_bytes(32)); // 64-char unique token
                
                // First user is admin, others are user
                $stmt = $pdo->query("SELECT COUNT(*) FROM users");
                $user_count = $stmt->fetchColumn();
                $role = ($user_count == 0) ? 'admin' : 'user';

                $stmt = $pdo->prepare("INSERT INTO users (name, email, password, role, webhook_token) VALUES (?, ?, ?, ?, ?)");
                if ($stmt->execute([$name, $email, $hash, $role, $webhook_token])) {
                    redirect('login?registered=1');
                } else {
                    $error = "Registration failed.";
                }
            }
        } catch(PDOException $e) {
            $error = "Database Error.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sign Up - <?= htmlspecialchars($settings['site_name']) ?></title>
    <link rel="icon" type="image/png" href="<?= htmlspecialchars($settings['site_favicon']) ?>" sizes="16x16">
    <!-- remix icon font css  -->
    <link rel="stylesheet" href="assets/css/remixicon.css">
    <!-- BootStrap css -->
    <link rel="stylesheet" href="assets/css/lib/bootstrap.min.css">
    <!-- main css -->
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<!-- Main Wrapper -->
<section class="auth bg-base d-flex flex-wrap">  
    <div class="auth-left d-lg-block d-none">
        <div class="d-flex align-items-center flex-column h-100 justify-content-center bg-primary-50">
            <img src="https://img.freepik.com/premium-vector/two-factor-authentication-concept-illustration_114360-5488.jpg" alt="" style="max-width: 80%; border-radius: 12px; mix-blend-mode: darken;">
        </div>
    </div>
    <div class="auth-right py-32 px-24 d-flex flex-column justify-content-center">
        <div class="max-w-464-px mx-auto w-100">
            <div>
                <a href="index.php" class="mb-40 max-w-290-px">
                    <img src="<?= htmlspecialchars($settings['site_logo']) ?>" alt="<?= htmlspecialchars($settings['site_name']) ?> Logo">
                </a>
                <h4 class="mb-12">Sign Up to your Account</h4>
                <p class="mb-32 text-secondary-light text-lg">Welcome! please enter your details</p>
            </div>
            
            <?php if($error): ?>
                <div class="alert alert-danger px-16 py-11 text-sm radius-8 mb-24"><?= htmlspecialchars($error) ?></div>
            <?php endif; ?>

            <form method="POST" action="register">
                <div class="icon-field mb-16">
                    <span class="icon top-50 translate-middle-y">
                        <iconify-icon icon="f7:person"></iconify-icon>
                    </span>
                    <input type="text" class="form-control h-56-px bg-neutral-50 radius-12" name="name" placeholder="Name" value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" required>
                </div>
                <div class="icon-field mb-16">
                    <span class="icon top-50 translate-middle-y">
                        <iconify-icon icon="mage:email"></iconify-icon>
                    </span>
                    <input type="email" class="form-control h-56-px bg-neutral-50 radius-12" name="email" placeholder="Email" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required>
                </div>
                <div class="mb-20">
                    <div class="position-relative">
                        <div class="icon-field">
                            <span class="icon top-50 translate-middle-y">
                                <iconify-icon icon="solar:lock-password-outline"></iconify-icon>
                            </span> 
                            <input type="password" class="form-control h-56-px bg-neutral-50 radius-12" id="your-password" name="password" placeholder="Password" required>
                        </div>
                        <span class="toggle-password ri-eye-line cursor-pointer position-absolute end-0 top-50 translate-middle-y me-16 text-secondary-light" data-toggle="#your-password"></span>
                    </div>
                </div>

                 <div class="mb-20">
                    <div class="position-relative">
                        <div class="icon-field">
                            <span class="icon top-50 translate-middle-y">
                                <iconify-icon icon="solar:lock-password-outline"></iconify-icon>
                            </span> 
                            <input type="password" class="form-control h-56-px bg-neutral-50 radius-12" id="confirm-password" name="password_confirmation" placeholder="Confirm Password" required>
                        </div>
                        <span class="toggle-password ri-eye-line cursor-pointer position-absolute end-0 top-50 translate-middle-y me-16 text-secondary-light" data-toggle="#confirm-password"></span>
                    </div>
                     <span class="mt-12 text-sm text-secondary-light">Your password must have at least 8 characters</span>
                </div>

                <button type="submit" class="btn btn-primary text-sm btn-sm px-12 py-16 w-100 radius-12 mx-auto mt-32"> Sign Up</button>

                <div class="mt-32 text-center text-sm">
                    <p class="mb-0">Already have an account? <a href="login.php" class="text-primary-600 fw-semibold">Sign In</a></p>
                </div>
                
            </form>
        </div>
    </div>
</section>

<!-- jQuery library js -->
<script src="assets/js/lib/jquery-3.7.1.min.js"></script>
<!-- Bootstrap js -->
<script src="assets/js/lib/bootstrap.bundle.min.js"></script>
<!-- Iconify Font js -->
<script src="assets/js/lib/iconify-icon.min.js"></script>
<!-- main js -->
<script src="assets/js/app.js"></script>
<script>
      // ================== Password Show Hide Js Start ==========
      function initializePasswordToggle(toggleSelector) {
        $(toggleSelector).on('click', function() {
            $(this).toggleClass("ri-eye-off-line");
            var input = $($(this).attr("data-toggle"));
            if (input.attr("type") === "password") {
                input.attr("type", "text");
            } else {
                input.attr("type", "password");
            }
        });
      }
      initializePasswordToggle('.toggle-password');
      // ========================= Password Show Hide Js End ===========================
</script>
</body>
</html>


