<?php
declare(strict_types=1);
require_once __DIR__ . '/bootstrap.php';

$title = 'Join SubscribeNetwork';
$errors = [];
$success = false;

// CSRF token (simple)
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $errors[] = 'Invalid security token.';
    } else {
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $display_name = trim($_POST['display_name'] ?? '');
        $user_type = $_POST['user_type'] ?? 'fan';
        
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email required.';
        if (strlen($password) < 10) $errors[] = 'Password must be at least 10 characters.';
        if (empty($display_name)) $errors[] = 'Display name required.';
        if (!in_array($user_type, ['fan','creator','brand'])) $errors[] = 'Invalid account type.';
        
        // Creator specific
        $creator_platform = null;
        $creator_platform_url = null;
        if ($user_type === 'creator') {
            $creator_platform = $_POST['creator_platform'] ?? '';
            $creator_platform_url = trim($_POST['creator_platform_url'] ?? '');
            if (empty($creator_platform)) $errors[] = 'Please select your platform.';
            if (!filter_var($creator_platform_url, FILTER_VALIDATE_URL)) $errors[] = 'Valid platform URL required.';
        }
        
        // Brand specific
        $company_name = null;
        if ($user_type === 'brand') {
            $company_name = trim($_POST['company_name'] ?? '');
            if (empty($company_name)) $errors[] = 'Company name required.';
        }
        
        // Check email uniqueness
        if (empty($errors)) {
            $stmt = db()->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) $errors[] = 'Email already registered.';
        }
        
        // Create user
        if (empty($errors)) {
            try {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $status = ($user_type === 'brand') ? 'pending' : 'active';
                $db = db();
                $stmt = $db->prepare("INSERT INTO users (email, password_hash, display_name, user_type, status, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
                $stmt->execute([$email, $hash, $display_name, $user_type, $status]);
                $user_id = (int)$db->lastInsertId();
                
                if ($user_type === 'creator') {
                    $stmt = $db->prepare("INSERT INTO creator_profiles (user_id, platform, platform_url, onboarding_step) VALUES (?, ?, ?, 'collective_setup')");
                    $stmt->execute([$user_id, $creator_platform, $creator_platform_url]);
                } elseif ($user_type === 'brand') {
                    $stmt = $db->prepare("INSERT INTO brand_profiles (user_id, company_name, approval_status) VALUES (?, ?, 'pending')");
                    $stmt->execute([$user_id, $company_name]);
                } elseif ($user_type === 'fan') {
                    $interests = isset($_POST['interests']) ? json_encode($_POST['interests']) : '[]';
                    $stmt = $db->prepare("INSERT INTO fan_profiles (user_id, interests, onboarding_complete) VALUES (?, ?, 0)");
                    $stmt->execute([$user_id, $interests]);
                }
                
                $_SESSION['user_id'] = $user_id;
                $_SESSION['user_type'] = $user_type;
                header('Location: /dashboard/index.php');
                exit;
            } catch (PDOException $e) {
                $errors[] = 'Database error: ' . $e->getMessage();
            }
        }
    }
}

require_once __DIR__ . '/includes/header.php';
?>

<div class="container" style="max-width: 700px; margin: 2rem auto;">
    <div class="glass-card" style="padding: 2rem;">
        <h1 class="text-center gradient-text">Join the SubscribeNetwork</h1>
        <p class="text-center" style="margin-bottom: 1.5rem;">Choose the account type that fits you.</p>
        
        <?php if (!empty($errors)): ?>
            <div style="background: rgba(255,68,68,0.2); border: 1px solid #ff4444; color: #ff8888; padding: 0.75rem; border-radius: 12px; margin-bottom: 1.5rem;">
                <?= implode('<br>', array_map('htmlspecialchars', $errors)) ?>
            </div>
        <?php endif; ?>
        
        <form method="post" id="registerForm">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
            
            <!-- Common fields -->
            <label>Display Name</label>
            <input type="text" name="display_name" value="<?= htmlspecialchars($_POST['display_name'] ?? '') ?>" required>
            
            <label>Email</label>
            <input type="email" name="email" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required>
            
            <label>Password (min 10 characters)</label>
            <input type="password" name="password" required>
            
            <!-- Account type radio buttons -->
            <label>I want to join as a...</label>
            <div style="display: flex; gap: 1rem; margin-bottom: 1rem;">
                <label><input type="radio" name="user_type" value="fan" <?= ($_POST['user_type'] ?? 'fan') === 'fan' ? 'checked' : '' ?>> ❤️ Fan</label>
                <label><input type="radio" name="user_type" value="creator" <?= ($_POST['user_type'] ?? '') === 'creator' ? 'checked' : '' ?>> 🎙️ Creator</label>
                <label><input type="radio" name="user_type" value="brand" <?= ($_POST['user_type'] ?? '') === 'brand' ? 'checked' : '' ?>> 🏢 Brand</label>
            </div>
            
            <!-- Creator fields (hidden by default) -->
            <div id="creatorFields" style="display: none;">
                <label>Existing Platform</label>
                <select name="creator_platform">
                    <option value="patreon">Patreon</option>
                    <option value="substack">Substack</option>
                    <option value="youtube">YouTube</option>
                    <option value="spotify">Spotify</option>
                    <option value="other">Other</option>
                </select>
                <label>Profile URL</label>
                <input type="url" name="creator_platform_url" placeholder="https://...">
            </div>
            
            <!-- Brand fields (hidden by default) -->
            <div id="brandFields" style="display: none;">
                <label>Company Name</label>
                <input type="text" name="company_name" placeholder="Your brand or agency">
            </div>
            
            <!-- Fan interests (optional) -->
            <div id="fanFields" style="display: none;">
                <label>Interests (select up to 5)</label>
                <div style="display: flex; flex-wrap: wrap; gap: 0.5rem;">
                    <label><input type="checkbox" name="interests[]" value="gaming"> 🎮 Gaming</label>
                    <label><input type="checkbox" name="interests[]" value="art"> 🎨 Art</label>
                    <label><input type="checkbox" name="interests[]" value="music"> 🎵 Music</label>
                    <label><input type="checkbox" name="interests[]" value="podcast"> 🎙️ Podcast</label>
                    <label><input type="checkbox" name="interests[]" value="writing"> ✍️ Writing</label>
                    <label><input type="checkbox" name="interests[]" value="fitness"> 💪 Fitness</label>
                </div>
            </div>
            
            <button type="submit" class="btn-primary" style="width: 100%; margin-top: 1.5rem;">Create Account →</button>
        </form>
        
        <div class="text-center" style="margin-top: 1.5rem;">
            Already have an account? <a href="/login.php">Sign in</a>
        </div>
    </div>
</div>

<script>
    const userTypeRadios = document.querySelectorAll('input[name="user_type"]');
    const creatorDiv = document.getElementById('creatorFields');
    const brandDiv = document.getElementById('brandFields');
    const fanDiv = document.getElementById('fanFields');
    
    function updateFields() {
        creatorDiv.style.display = 'none';
        brandDiv.style.display = 'none';
        fanDiv.style.display = 'none';
        const selected = document.querySelector('input[name="user_type"]:checked');
        if (selected) {
            if (selected.value === 'creator') creatorDiv.style.display = 'block';
            if (selected.value === 'brand') brandDiv.style.display = 'block';
            if (selected.value === 'fan') fanDiv.style.display = 'block';
        }
    }
    userTypeRadios.forEach(radio => radio.addEventListener('change', updateFields));
    updateFields();
</script>

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