<?php
declare(strict_types=1);
session_start();
require_once __DIR__ . '/db/config.php';

if (isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if ($username && $email && $password && $confirm_password) {
        if ($password !== $confirm_password) {
            $error = "Passwords do not match.";
        } elseif (strlen($password) < 6) {
            $error = "Password must be at least 6 characters.";
        } else {
            $pdo = db();
            // Check if username or email exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
            $stmt->execute([$username, $email]);
            if ($stmt->fetch()) {
                $error = "Username or email already exists.";
            } else {
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("INSERT INTO users (username, email, password, role) VALUES (?, ?, ?, 'user')");
                if ($stmt->execute([$username, $email, $hashed_password])) {
                    $success = "Registration successful! You can now <a href='login.php' class='text-tiktok-cyan'>login</a>.";
                } else {
                    $error = "Registration failed. Please try again.";
                }
            }
        }
    } else {
        $error = "Please fill in all fields.";
    }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Register - TikTok Live AI</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="assets/css/custom.css?v=<?= time() ?>">
  <style>
    body { font-family: 'Inter', sans-serif; background-color: #0f0f0f; color: #fff; height: 100vh; display: flex; align-items: center; justify-content: center; }
    .card-register { background-color: #1a1a1a; border: 1px solid #333; border-radius: 12px; width: 100%; max-width: 450px; }
    .form-control { background-color: #262626; border-color: #444; color: #fff; }
    .form-control:focus { background-color: #2d2d2d; border-color: #00f2ea; color: #fff; box-shadow: 0 0 0 0.25rem rgba(0, 242, 234, 0.25); }
    .btn-register { background-color: #00f2ea; color: #000; font-weight: 700; border-radius: 8px; border: none; padding: 12px; }
    .btn-register:hover { background-color: #00d8d1; color: #000; }
    .text-tiktok-cyan { color: #00f2ea; }
  </style>
</head>
<body>

<div class="card-register p-4 shadow-lg">
    <div class="text-center mb-4">
        <h3 class="fw-bold"><span class="text-tiktok-cyan">Join</span> TikTok AI</h3>
        <p class="text-secondary small">Create your account to get started</p>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-danger bg-dark text-danger border-danger py-2 small"><?= $error ?></div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="alert alert-success bg-dark text-success border-success py-2 small"><?= $success ?></div>
    <?php else: ?>
    <form method="POST">
        <div class="mb-3">
            <label for="username" class="form-label small text-secondary">Username</label>
            <input type="text" name="username" id="username" class="form-control" value="<?= htmlspecialchars($_POST['username'] ?? '') ?>" required autofocus>
        </div>
        <div class="mb-3">
            <label for="email" class="form-label small text-secondary">Email Address</label>
            <input type="email" name="email" id="email" class="form-control" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required>
        </div>
        <div class="row">
            <div class="col-md-6 mb-3">
                <label for="password" class="form-label small text-secondary">Password</label>
                <input type="password" name="password" id="password" class="form-control" required>
            </div>
            <div class="col-md-6 mb-4">
                <label for="confirm_password" class="form-label small text-secondary">Confirm Password</label>
                <input type="password" name="confirm_password" id="confirm_password" class="form-control" required>
            </div>
        </div>
        <div class="d-grid">
            <button type="submit" class="btn btn-register">Register Now</button>
        </div>
    </form>
    <?php endif; ?>
    
    <div class="text-center mt-4">
        <p class="small text-secondary">Already have an account? <a href="login.php" class="text-tiktok-cyan text-decoration-none">Login here</a></p>
        <a href="/" class="text-secondary small text-decoration-none">&larr; Back to Site</a>
    </div>
</div>

</body>
</html>
