<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/SimpleCaptcha.php';
require_once __DIR__ . '/includes/MailQueue.php';

if (isUserLoggedIn()) {
    redirect('');
}

$pdo = getPDO();
$errorMsg = null;
$successMsg = null;

$preselectAnnouncer = ($_GET['as'] ?? '') === 'announcer';
$formRole = $preselectAnnouncer ? 'announcer' : 'client';
$formAnnouncerType = '';
$formEmail = '';
$formUsername = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
    $formEmail = trim($_POST['email'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $formUsername = $username;
    $password = trim($_POST['password'] ?? '');
    $confirmPassword = trim($_POST['confirm_password'] ?? '');
    $formRole = ($_POST['role'] ?? '') === 'announcer' ? 'announcer' : 'client';
    $formAnnouncerType = $_POST['announcer_type'] ?? '';
    $address = trim($_POST['address'] ?? '');
    $captchaInput = $_POST['captcha'] ?? '';
    $termsAccepted = isset($_POST['accept_terms']);

    $announcerType = null;
    if ($formRole === 'announcer') {
        $announcerType = in_array($formAnnouncerType, ['independent', 'club', 'agency'], true) ? $formAnnouncerType : null;
    }

    if (!SimpleCaptcha::verify($captchaInput)) {
        $errorMsg = __('err_captcha');
    } elseif (empty($email)) {
        $errorMsg = __('err_email_invalid');
    } elseif (!preg_match('/^[a-zA-Z0-9_-]{3,30}$/', $username)) {
        $errorMsg = __('err_username_invalid');
    } elseif (strlen($password) < 8) {
        $errorMsg = __('err_password_too_short');
    } elseif ($password !== $confirmPassword) {
        $errorMsg = __('err_passwords_mismatch');
    } elseif ($formRole === 'announcer' && empty($announcerType)) {
        $errorMsg = __('err_announcer_type_required');
    } elseif ($announcerType === 'club' && empty($address)) {
        $errorMsg = __('err_address_required');
    } elseif (!$termsAccepted) {
        $errorMsg = __('err_terms_required');
    } else {
        $stmtCheck = $pdo->prepare("SELECT email, username FROM users WHERE email = ? OR username = ?");
        $stmtCheck->execute([$email, $username]);
        $existing = $stmtCheck->fetch();

        if ($existing && $existing['email'] === $email) {
            $errorMsg = __('err_email_taken');
        } elseif ($existing) {
            $errorMsg = __('err_username_taken');
        } else {
            try {
                $token = bin2hex(random_bytes(32));
                $passwordHash = password_hash($password, PASSWORD_BCRYPT);

                $stmt = $pdo->prepare("INSERT INTO users
                    (email, username, password_hash, role, announcer_type, address, token, email_verified, status, terms_accepted_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'inactive', NOW())");
                $stmt->execute([
                    $email,
                    $username,
                    $passwordHash,
                    $formRole,
                    $announcerType,
                    $announcerType === 'club' ? $address : null,
                    $token,
                ]);

                unset($_SESSION['post_verify_redirect']);
                if ($formRole === 'announcer') {
                    $_SESSION['post_verify_redirect'] = 'publicar.php';
                }

                $verifyLink = BASE_URL . '/verify-account.php?token=' . $token;
                $targetRole = resolveUserTargetRole(['role' => $formRole, 'announcer_type' => $announcerType]);

                queueAutoresponderEmail(
                    $pdo,
                    'account_activation',
                    $targetRole,
                    $email,
                    ['name' => $email, 'link' => $verifyLink],
                    'Activa tu cuenta en Princesitas',
                    "<p>Para activar tu cuenta, haz clic en el siguiente enlace:</p><p><a href='{$verifyLink}'>{$verifyLink}</a></p>"
                );

                $successMsg = __('msg_register_success');
            } catch (PDOException $e) {
                $errorMsg = __('msg_error_submit') . ' (' . $e->getMessage() . ')';
            }
        }
    }
}

$pageTitle = __('register_title');
require_once ROOT_PATH . '/templates/partials/header.php';
?>

<div class="max-w-xl mx-auto px-4 py-16">
    <div class="bg-luxury-card border border-luxury-rose/10 rounded-2xl p-8 border-rose-glow space-y-6">

        <div class="text-center">
            <h1 class="font-playfair text-2xl font-bold text-luxury-rose"><?= __('register_title') ?></h1>
            <p class="text-sm font-light text-luxury-muted mt-1"><?= __('register_subtitle') ?></p>
        </div>

        <?php if ($successMsg): ?>
            <div class="p-4 bg-emerald-950/30 border border-emerald-500/20 text-emerald-400 text-sm font-light rounded-lg leading-relaxed">
                ✅ <?= e($successMsg) ?>
            </div>
        <?php else: ?>
            <?php if ($errorMsg): ?>
                <div class="p-3 bg-red-950/30 border border-red-500/20 text-red-400 text-sm font-light rounded-lg">
                    ⚠️ <?= e($errorMsg) ?>
                </div>
            <?php endif; ?>

            <form action="" method="POST" class="space-y-5" id="register-form">

                <!-- Role selector -->
                <div>
                    <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_account_type') ?> *</label>
                    <div class="grid grid-cols-2 gap-3">
                        <label class="flex items-center justify-center gap-2 border border-luxury-rose/20 rounded-lg p-3 cursor-pointer text-sm <?= $formRole === 'client' ? 'bg-luxury-rose/10 border-luxury-rose' : '' ?>">
                            <input type="radio" name="role" value="client" class="role-radio" <?= $formRole === 'client' ? 'checked' : '' ?>>
                            <?= __('role_client') ?>
                        </label>
                        <label class="flex items-center justify-center gap-2 border border-luxury-rose/20 rounded-lg p-3 cursor-pointer text-sm <?= $formRole === 'announcer' ? 'bg-luxury-rose/10 border-luxury-rose' : '' ?>">
                            <input type="radio" name="role" value="announcer" class="role-radio" <?= $formRole === 'announcer' ? 'checked' : '' ?>>
                            <?= __('role_announcer') ?>
                        </label>
                    </div>
                </div>

                <!-- Announcer type (shown only when role=announcer) -->
                <div id="announcer-type-block" class="<?= $formRole === 'announcer' ? '' : 'hidden' ?>">
                    <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_announcer_type') ?> *</label>
                    <div class="space-y-2">
                        <?php
                        $announcerTypeOptions = [
                            'independent' => ['label' => __('announcer_type_independent'), 'desc' => __('announcer_type_independent_desc')],
                            'club' => ['label' => __('announcer_type_club'), 'desc' => __('announcer_type_club_desc')],
                            'agency' => ['label' => __('announcer_type_agency'), 'desc' => __('announcer_type_agency_desc')],
                        ];
                        foreach ($announcerTypeOptions as $typeValue => $typeInfo):
                            $isChecked = $formAnnouncerType === $typeValue;
                        ?>
                            <label class="announcer-type-option flex items-start gap-3 border border-luxury-rose/20 rounded-lg p-3 cursor-pointer text-sm <?= $isChecked ? 'bg-luxury-rose/10 border-luxury-rose' : '' ?>">
                                <input type="radio" name="announcer_type" value="<?= $typeValue ?>" class="announcer-type-radio mt-0.5" <?= $isChecked ? 'checked' : '' ?>>
                                <span>
                                    <span class="font-semibold text-luxury-platinum"><?= e($typeInfo['label']) ?></span>
                                    <span class="block text-[11px] text-luxury-muted italic mt-0.5">(<?= e($typeInfo['desc']) ?>)</span>
                                </span>
                            </label>
                        <?php endforeach; ?>
                    </div>

                    <div id="address-block" class="mt-4 <?= $formAnnouncerType === 'club' ? '' : 'hidden' ?>">
                        <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_address') ?> *</label>
                        <input type="text" name="address" value="<?= e($_POST['address'] ?? '') ?>"
                               class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                        <p class="text-[10px] text-luxury-muted mt-1.5 font-light"><?= __('field_address_hint') ?></p>
                    </div>
                </div>

                <!-- Email -->
                <div>
                    <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_account_email') ?> *</label>
                    <input type="email" name="email" required value="<?= e($formEmail) ?>"
                           class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                </div>

                <!-- Username -->
                <div>
                    <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_username') ?> *</label>
                    <input type="text" name="username" required minlength="3" maxlength="30" pattern="[a-zA-Z0-9_-]+" value="<?= e($formUsername) ?>"
                           class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                    <p class="text-[10px] text-luxury-muted mt-1.5 font-light"><?= __('field_username_hint') ?></p>
                </div>

                <!-- Password -->
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_password') ?> *</label>
                        <input type="password" name="password" required minlength="8"
                               class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold uppercase tracking-wider text-luxury-muted mb-2"><?= __('field_confirm_password') ?> *</label>
                        <input type="password" name="confirm_password" required minlength="8"
                               class="bg-luxury-darker text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                    </div>
                </div>

                <!-- Captcha -->
                <div class="bg-luxury-darker/60 rounded-xl p-4 border border-luxury-rose/5 space-y-3">
                    <div class="flex items-center justify-between">
                        <span class="text-xs font-semibold uppercase tracking-wider text-luxury-muted"><?= __('admin_captcha') ?></span>
                        <div class="flex items-center gap-2">
                            <img id="captcha-img" src="<?= BASE_URL ?>/captcha-image.php" alt="captcha" class="rounded border border-luxury-rose/15">
                            <button type="button" onclick="reloadCaptcha()" class="text-luxury-rose hover:text-luxury-rosehover text-xs" title="<?= __('captcha_reload') ?>">↻</button>
                        </div>
                    </div>
                    <input type="text" name="captcha" required autocomplete="off" placeholder="<?= __('captcha_placeholder') ?>"
                           class="bg-luxury-card text-luxury-platinum border border-luxury-rose/20 rounded-lg w-full p-2.5 outline-none focus:border-luxury-rose text-sm">
                </div>

                <!-- Aceptación obligatoria de las CGU -->
                <label class="flex items-start text-sm font-light text-luxury-gray cursor-pointer">
                    <input type="checkbox" name="accept_terms" value="1" required
                           class="rounded bg-luxury-darker border-luxury-rose/20 text-luxury-rose focus:ring-luxury-rose focus:ring-offset-luxury-dark mr-3 mt-0.5 h-4 w-4 shrink-0">
                    <span><?= __('terms_checkbox_label') ?>
                        <a href="<?= BASE_URL ?>/terminos" target="_blank" class="text-luxury-rose underline hover:text-luxury-rosehover"><?= __('terms_link_text') ?></a>.
                    </span>
                </label>

                <button type="submit" class="w-full py-3 bg-gradient-to-r from-luxury-rose to-luxury-rosehover hover:from-luxury-rosehover hover:to-luxury-rose text-luxury-dark text-xs font-bold uppercase tracking-widest rounded-lg shadow-md transition duration-300">
                    <?= __('btn_register') ?>
                </button>
            </form>

            <p class="text-center text-xs text-luxury-muted">
                <?= __('already_have_account') ?> <a href="<?= BASE_URL ?>/login.php" class="text-luxury-rose hover:text-luxury-rosehover underline"><?= __('login_link') ?></a>
            </p>
        <?php endif; ?>

    </div>
</div>

<script>
    function reloadCaptcha() {
        document.getElementById('captcha-img').src = '<?= BASE_URL ?>/captcha-image.php?t=' + Date.now();
    }

    const roleRadios = document.querySelectorAll('.role-radio');
    const announcerBlock = document.getElementById('announcer-type-block');
    const announcerTypeRadios = document.querySelectorAll('.announcer-type-radio');
    const addressBlock = document.getElementById('address-block');

    function updateRoleUI() {
        const checked = document.querySelector('.role-radio:checked');
        announcerBlock.classList.toggle('hidden', !checked || checked.value !== 'announcer');
        roleRadios.forEach(r => {
            r.closest('label').classList.toggle('bg-luxury-rose/10', r.checked);
            r.closest('label').classList.toggle('border-luxury-rose', r.checked);
        });
    }
    roleRadios.forEach(r => r.addEventListener('change', updateRoleUI));

    function updateAnnouncerTypeUI() {
        const checked = document.querySelector('.announcer-type-radio:checked');
        addressBlock.classList.toggle('hidden', !checked || checked.value !== 'club');
        announcerTypeRadios.forEach(r => {
            r.closest('label').classList.toggle('bg-luxury-rose/10', r.checked);
            r.closest('label').classList.toggle('border-luxury-rose', r.checked);
        });
    }
    announcerTypeRadios.forEach(r => r.addEventListener('change', updateAnnouncerTypeUI));
    updateAnnouncerTypeUI();
</script>

<?php
require_once ROOT_PATH . '/templates/partials/footer.php';
?>
