<?php
/**
 * User Registration Page
 * PHP User Registration - https://rskworld.in
 * Developer: Molla Samser | RSK World
 * Contact: help@rskworld.in | +91 93305 39277
 * Year: 2026
 */

require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/includes/functions.php';

if (isLoggedIn()) {
    header('Location: dashboard.php');
    exit;
}

$errors = [];
$success = '';

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

    if (strlen($name) < 2) $errors[] = 'Name must be at least 2 characters.';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Please enter a valid email.';
    if (strlen($password) < 8) $errors[] = 'Password must be at least 8 characters.';
    if ($password !== $password_confirm) $errors[] = 'Passwords do not match.';

    if (empty($errors)) {
        $pdo = getDbConnection();
        $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ?');
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            $errors[] = 'This email is already registered.';
        } else {
            $token = generateVerificationToken();
            $tokenExpires = date('Y-m-d H:i:s', time() + 86400); // 24 hours
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare('INSERT INTO users (name, email, password, verification_token, token_expires_at) VALUES (?, ?, ?, ?, ?)');
            $stmt->execute([$name, $email, $hash, $token, $tokenExpires]);
            sendVerificationEmail($email, $name, $token);
            setFlash('success', 'Registration successful! Please check your email to verify your account.');
            header('Location: login.php');
            exit;
        }
    }
}

$pageTitle = 'Register';
require_once __DIR__ . '/includes/header.php';
?>

<div class="auth-card">
    <h1><i class="fas fa-user-plus"></i> Create Account</h1>
    <p class="subtitle">PHP User Registration — <a href="https://rskworld.in" target="_blank">rskworld.in</a></p>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-error">
            <?php foreach ($errors as $e): ?>
                <div><?= htmlspecialchars($e) ?></div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <form method="post" action="" class="auth-form" novalidate>
        <div class="form-group">
            <label for="name">Full Name</label>
            <input type="text" id="name" name="name" value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" required minlength="2" placeholder="Your name">
        </div>
        <div class="form-group">
            <label for="email">Email</label>
            <input type="email" id="email" name="email" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required placeholder="you@example.com">
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input type="password" id="password" name="password" required minlength="8" placeholder="Min 8 characters">
            <span id="password-strength" class="password-strength" aria-live="polite"></span>
        </div>
        <div class="form-group">
            <label for="password_confirm">Confirm Password</label>
            <input type="password" id="password_confirm" name="password_confirm" required minlength="8" placeholder="Repeat password">
        </div>
        <button type="submit" class="btn btn-primary">Register</button>
    </form>
    <script>
    (function() {
        var el = document.getElementById('password');
        var out = document.getElementById('password-strength');
        if (!el || !out) return;
        function strength(p) {
            if (!p || p.length < 6) return { label: 'Too short', cls: 'strength-weak' };
            if (p.length < 8) return { label: 'Weak', cls: 'strength-weak' };
            var hasNum = /\d/.test(p), hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(p), hasUpper = /[A-Z]/.test(p);
            if (p.length >= 12 && hasNum && (hasSpecial || hasUpper)) return { label: 'Strong', cls: 'strength-strong' };
            if (p.length >= 8 && (hasNum || hasSpecial || hasUpper)) return { label: 'Medium', cls: 'strength-medium' };
            return { label: 'Weak', cls: 'strength-weak' };
        }
        el.addEventListener('input', function() {
            var s = strength(this.value);
            out.textContent = this.value ? s.label : '';
            out.className = 'password-strength ' + (this.value ? s.cls : '');
        });
    })();
    </script>
    <p class="auth-footer">Already have an account? <a href="login.php">Log in</a></p>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
