<?php
/**
 * Newsletter Subscription Section — Gmind Institute Homepage
 *
 * Include this file in home/index.php BEFORE the CTA Banner section.
 * It reads newsletter settings from $newsletterSettings array.
 *
 * Required variables:
 * @var array $newsletterSettings — from HomeController
 * @var string $csrfToken         — CSRF token for form submission
 */
$basePath = defined('BASE_PATH') ? BASE_PATH : '/gmind';

// Provide safe defaults
$newsletterSettings = $newsletterSettings ?? [];

$nlEnabled    = ($newsletterSettings['newsletter_enabled'] ?? '1') === '1';
$nlTitle      = $newsletterSettings['newsletter_title'] ?? __('newsletter.title');
$nlSubtitle   = $newsletterSettings['newsletter_subtitle'] ?? __('newsletter.subtitle');
$nlButtonText = $newsletterSettings['newsletter_button_text'] ?? __('newsletter.subscribe');
$csrfToken    = $csrfToken ?? '';
?>

<?php if ($nlEnabled): ?>
<!-- ============================================================
     Newsletter Subscription Section
     ============================================================ -->
<section class="newsletter-section" aria-label="Newsletter subscription">
    <div class="container">
        <div class="newsletter-wrapper">
            <div class="newsletter-content">
                <div class="newsletter-icon">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="48" height="48">
                        <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>
                        <polyline points="22,6 12,13 2,6"/>
                    </svg>
                </div>
                <h2 class="newsletter-title"><?= htmlspecialchars($nlTitle, ENT_QUOTES, 'UTF-8') ?></h2>
                <p class="newsletter-subtitle"><?= htmlspecialchars($nlSubtitle, ENT_QUOTES, 'UTF-8') ?></p>
            </div>
            <form class="newsletter-form" id="newsletterForm" method="POST" action="<?= $basePath ?>/newsletter/subscribe">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">
                <div class="newsletter-form-fields">
                    <input type="text" name="name" class="newsletter-input newsletter-input-name" placeholder="<?= __('newsletter.name_placeholder') ?>" autocomplete="name">
                    <input type="email" name="email" class="newsletter-input newsletter-input-email" placeholder="<?= __('newsletter.placeholder') ?>" required autocomplete="email">
                    <button type="submit" class="newsletter-submit-btn" id="newsletterSubmitBtn">
                        <span class="newsletter-btn-text"><?= htmlspecialchars($nlButtonText, ENT_QUOTES, 'UTF-8') ?></span>
                        <span class="newsletter-btn-loading" style="display:none;">
                            <svg class="newsletter-spinner" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10" stroke-dasharray="30 60"/></svg>
                            <?= __('newsletter.subscribing') ?>
                        </span>
                    </button>
                </div>
                <div class="newsletter-message" id="newsletterMessage" style="display:none;"></div>
                <p class="newsletter-privacy"><?= __('newsletter.privacy') ?></p>
            </form>
        </div>
    </div>
</section>

<style>
/* ── Newsletter Section ── */
.newsletter-section {
    background: linear-gradient(135deg, #1a237e 0%, #0d47a1 50%, #01579b 100%);
    padding: 80px 0;
    position: relative;
    overflow: hidden;
}

.newsletter-section::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -20%;
    width: 500px;
    height: 500px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.03);
    pointer-events: none;
}

.newsletter-section::after {
    content: '';
    position: absolute;
    bottom: -30%;
    left: -10%;
    width: 400px;
    height: 400px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.03);
    pointer-events: none;
}

.newsletter-wrapper {
    max-width: 700px;
    margin: 0 auto;
    text-align: center;
    position: relative;
    z-index: 1;
}

.newsletter-content {
    margin-bottom: 2rem;
}

.newsletter-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    margin-bottom: 1.5rem;
}

.newsletter-icon svg {
    color: rgba(255, 255, 255, 0.9);
}

.newsletter-title {
    font-family: 'Poppins', sans-serif;
    font-size: 2rem;
    font-weight: 700;
    color: #ffffff;
    margin: 0 0 0.75rem 0;
    line-height: 1.3;
}

.newsletter-subtitle {
    font-family: 'Inter', sans-serif;
    font-size: 1rem;
    color: rgba(255, 255, 255, 0.8);
    line-height: 1.6;
    margin: 0;
}

.newsletter-form {
    margin-top: 1rem;
}

.newsletter-form-fields {
    display: flex;
    gap: 0.75rem;
    align-items: stretch;
    flex-wrap: wrap;
    justify-content: center;
}

.newsletter-input {
    font-family: 'Inter', sans-serif;
    font-size: 0.95rem;
    padding: 14px 18px;
    border: 2px solid rgba(255, 255, 255, 0.2);
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.1);
    color: #ffffff;
    transition: all 0.3s ease;
    outline: none;
}

.newsletter-input::placeholder {
    color: rgba(255, 255, 255, 0.5);
}

.newsletter-input:focus {
    border-color: rgba(255, 255, 255, 0.5);
    background: rgba(255, 255, 255, 0.15);
}

.newsletter-input-name {
    flex: 0 0 180px;
}

.newsletter-input-email {
    flex: 1 1 250px;
    min-width: 200px;
}

.newsletter-submit-btn {
    font-family: 'Poppins', sans-serif;
    font-size: 0.95rem;
    font-weight: 600;
    padding: 14px 28px;
    border: none;
    border-radius: 8px;
    background: #ff6d00;
    color: #ffffff;
    cursor: pointer;
    transition: all 0.3s ease;
    white-space: nowrap;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.newsletter-submit-btn:hover {
    background: #e65100;
    transform: translateY(-1px);
    box-shadow: 0 4px 15px rgba(255, 109, 0, 0.4);
}

.newsletter-submit-btn:active {
    transform: translateY(0);
}

.newsletter-submit-btn:disabled {
    opacity: 0.7;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}

.newsletter-spinner {
    animation: newsletter-spin 1s linear infinite;
}

@keyframes newsletter-spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

.newsletter-message {
    margin-top: 1rem;
    padding: 10px 16px;
    border-radius: 6px;
    font-size: 0.9rem;
    font-weight: 500;
    text-align: center;
}

.newsletter-message-success {
    background: rgba(76, 175, 80, 0.2);
    color: #a5d6a7;
    border: 1px solid rgba(76, 175, 80, 0.3);
}

.newsletter-message-error {
    background: rgba(244, 67, 54, 0.2);
    color: #ef9a9a;
    border: 1px solid rgba(244, 67, 54, 0.3);
}

.newsletter-privacy {
    font-size: 0.8rem;
    color: rgba(255, 255, 255, 0.5);
    margin-top: 0.75rem;
}

/* ── Responsive ── */
@media (max-width: 768px) {
    .newsletter-section {
        padding: 60px 0;
    }

    .newsletter-title {
        font-size: 1.5rem;
    }

    .newsletter-form-fields {
        flex-direction: column;
    }

    .newsletter-input-name,
    .newsletter-input-email {
        flex: 1 1 auto;
        width: 100%;
    }

    .newsletter-submit-btn {
        width: 100%;
        justify-content: center;
    }
}

@media (max-width: 480px) {
    .newsletter-section {
        padding: 40px 0;
    }

    .newsletter-title {
        font-size: 1.25rem;
    }

    .newsletter-subtitle {
        font-size: 0.9rem;
    }

    .newsletter-icon {
        width: 60px;
        height: 60px;
    }

    .newsletter-icon svg {
        width: 32px;
        height: 32px;
    }
}
</style>

<script>
(function() {
    var form = document.getElementById('newsletterForm');
    if (!form) return;

    var msgEl = document.getElementById('newsletterMessage');
    var btnText = form.querySelector('.newsletter-btn-text');
    var btnLoading = form.querySelector('.newsletter-btn-loading');
    var submitBtn = document.getElementById('newsletterSubmitBtn');

    form.addEventListener('submit', function(e) {
        e.preventDefault();

        var email = form.querySelector('input[name="email"]').value.trim();
        if (!email) return;

        // Show loading
        btnText.style.display = 'none';
        btnLoading.style.display = 'inline-flex';
        submitBtn.disabled = true;

        var formData = new FormData(form);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', form.action, true);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.onreadystatechange = function() {
            if (xhr.readyState !== 4) return;

            // Reset button
            btnText.style.display = 'inline';
            btnLoading.style.display = 'none';
            submitBtn.disabled = false;

            try {
                var res = JSON.parse(xhr.responseText);
                msgEl.textContent = res.message || 'Something happened.';
                msgEl.className = 'newsletter-message newsletter-message-' + (res.success ? 'success' : 'error');
                msgEl.style.display = 'block';

                if (res.success) {
                    form.querySelector('input[name="email"]').value = '';
                    form.querySelector('input[name="name"]').value = '';
                }

                // Auto-hide after 5 seconds
                setTimeout(function() {
                    msgEl.style.display = 'none';
                }, 5000);
            } catch (err) {
                // Server returned non-JSON response (likely an error page)
                // Do NOT show fake success — show the real error
                if (xhr.status === 200) {
                    // Status 200 but not JSON — might be a redirect to home page
                    msgEl.textContent = '<?= __('newsletter.submitted_refresh') ?>';
                    msgEl.className = 'newsletter-message newsletter-message-success';
                } else {
                    msgEl.textContent = '<?= __('newsletter.server_error') ?>' + ' (code ' + xhr.status + ').';
                    msgEl.className = 'newsletter-message newsletter-message-error';
                }
                msgEl.style.display = 'block';
            }
        };

        xhr.onerror = function() {
            btnText.style.display = 'inline';
            btnLoading.style.display = 'none';
            submitBtn.disabled = false;
            msgEl.textContent = '<?= __('newsletter.network_error') ?>';
            msgEl.className = 'newsletter-message newsletter-message-error';
            msgEl.style.display = 'block';
        };

        xhr.send(formData);
    });
})();
</script>
<?php endif; ?>
