<?php
/**
 * Plugin Name: GamePulse Newsletter
 * Description: Simple newsletter subscription form for the GamePulse blog.
 * Version: 1.0.0
 * Author: Gemini
 */

if (!defined('ABSPATH')) exit;

// Create table on activation
register_activation_hook(__FILE__, 'gamepulse_newsletter_install');
function gamepulse_newsletter_install() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'gamepulse_subscriptions';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        email varchar(100) NOT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        UNIQUE KEY email (email)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

// Shortcode to display the form
add_shortcode('gamepulse_newsletter', 'gamepulse_newsletter_form_shortcode');
function gamepulse_newsletter_form_shortcode() {
    ob_start();
    ?>
    <div class="gamepulse-newsletter-container" style="background: #1a1a1a; padding: 2rem; border-radius: 12px; border: 1px solid #333; margin: 2rem 0; text-align: center;">
        <h3 style="color: #E63946; margin-top: 0;">Stay in the Loop</h3>
        <p style="color: #ccc;">Get the latest gaming news, reviews, and "realises" delivered to your inbox.</p>
        <form id="gamepulse-newsletter-form" style="display: flex; flex-direction: column; gap: 1rem; max-width: 400px; margin: 0 auto;">
            <input type="email" name="email" placeholder="Your email address" required style="padding: 12px; border-radius: 6px; border: 1px solid #444; background: #2a2a2a; color: #fff;">
            <button type="submit" style="padding: 12px; border-radius: 6px; border: none; background: #E63946; color: #fff; font-weight: bold; cursor: pointer; transition: background 0.3s;">Subscribe Now</button>
            <div id="gamepulse-newsletter-message" style="margin-top: 1rem; font-size: 0.9rem;"></div>
        </form>
    </div>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('gamepulse-newsletter-form');
        const messageDiv = document.getElementById('gamepulse-newsletter-message');

        form.addEventListener('submit', function(e) {
            e.preventDefault();
            const email = form.querySelector('input[name="email"]').value;
            const button = form.querySelector('button');
            
            button.disabled = true;
            button.textContent = 'Subscribing...';
            messageDiv.textContent = '';
            messageDiv.style.color = '#fff';

            const formData = new FormData();
            formData.append('action', 'gamepulse_subscribe');
            formData.append('email', email);
            formData.append('_wpnonce', '<?php echo wp_create_nonce("gamepulse_newsletter_nonce"); ?>');

            fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    messageDiv.textContent = data.data.message;
                    messageDiv.style.color = '#4CAF50';
                    form.reset();
                } else {
                    messageDiv.textContent = data.data.message;
                    messageDiv.style.color = '#f44336';
                }
            })
            .catch(error => {
                messageDiv.textContent = 'An error occurred. Please try again.';
                messageDiv.style.color = '#f44336';
            })
            .finally(() => {
                button.disabled = false;
                button.textContent = 'Subscribe Now';
            });
        });
    });
    </script>
    <?php
    return ob_get_clean();
}

// AJAX handler
add_action('wp_ajax_gamepulse_subscribe', 'gamepulse_handle_subscription');
add_action('wp_ajax_nopriv_gamepulse_subscribe', 'gamepulse_handle_subscription');

function gamepulse_handle_subscription() {
    check_ajax_referer('gamepulse_newsletter_nonce', '_wpnonce');

    $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';

    if (!is_email($email)) {
        wp_send_json_error(['message' => 'Please enter a valid email address.']);
    }

    global $wpdb;
    $table_name = $wpdb->prefix . 'gamepulse_subscriptions';

    // Check if already subscribed
    $exists = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $table_name WHERE email = %s", $email));

    if ($exists) {
        wp_send_json_error(['message' => 'You are already subscribed!']);
    }

    $inserted = $wpdb->insert(
        $table_name,
        ['email' => $email],
        ['%s']
    );

    if ($inserted) {
        // Send notification to admin using MailService
        if (file_exists(ABSPATH . 'mail/MailService.php')) {
            require_once ABSPATH . 'mail/MailService.php';
            $site_name = get_bloginfo('name');
            MailService::sendMail(
                null, // Fallback to MAIL_TO
                "New Subscriber for $site_name",
                "<p>A new user has subscribed to your newsletter: <strong>$email</strong></p>",
                "A new user has subscribed to your newsletter: $email"
            );
        }

        wp_send_json_success(['message' => 'Thank you for subscribing!']);
    } else {
        wp_send_json_error(['message' => 'Subscription failed. Please try again later.']);
    }
}
