<?php
// =========================
// HowCan Newsletter System with SMTP Auto Welcome Mail
// =========================

// =========================
// Handle Newsletter Subscription
// =========================
function howcan_handle_newsletter_subscription() {

    if ( isset($_POST['howcan_newsletter_nonce']) 
        && wp_verify_nonce($_POST['howcan_newsletter_nonce'], 'howcan_newsletter_action') ) {

        if ( isset($_POST['newsletter_email']) && is_email($_POST['newsletter_email']) ) {

            $email = sanitize_email($_POST['newsletter_email']);

            // 1️⃣ Save to WordPress DB
            $subscribers = get_option('howcan_newsletter_emails', array());
            if (!in_array($email, $subscribers, true)) {
                $subscribers[] = $email;
                update_option('howcan_newsletter_emails', $subscribers);
            }

            // 2️⃣ Send Auto Welcome Email via SMTP (wp_mail)
            $subject = "Welcome to HowCan Newsletter!";
            $message = "Hi Subscriber,\n\nThank you for subscribing to our newsletter. Stay tuned for updates!\n\nBest regards,\nHowCan Team";
            $headers = array('Content-Type: text/plain; charset=UTF-8');

            wp_mail($email, $subject, $message, $headers);

            // 3️⃣ Admin Notification
            wp_mail(
                get_option('admin_email'),
                'New Newsletter Subscriber',
                'New subscriber: ' . $email,
                ['Content-Type: text/plain; charset=UTF-8']
            );

            // 4️⃣ Redirect with success
            wp_safe_redirect(add_query_arg('subscribed', '1', wp_get_referer() ?: home_url()));
            exit;
        }
    }
}
add_action('init', 'howcan_handle_newsletter_subscription');


// =========================
// Admin Menu & CSV Export
// =========================
function howcan_newsletter_menu() {
    add_menu_page(
        'Newsletter Subscribers',
        'Newsletter Subscribers',
        'manage_options',
        'howcan-newsletter-subscribers',
        'howcan_newsletter_page',
        'dashicons-email-alt',
        26
    );
}
add_action('admin_menu', 'howcan_newsletter_menu');

function howcan_newsletter_page() {
    ?>
    <div class="wrap">
        <h1>Newsletter Subscribers</h1>
        <p>Below is the list of subscribers.</p>
        <?php
        $subscribers = get_option('howcan_newsletter_emails', array());

        if (!empty($subscribers)) {
            echo '<div class="table-responsive">';
            echo '<table class="table table-bordered table-hover align-middle">';
            echo '<thead class="table-light"><tr>';
            echo '<th>#</th><th>Email</th>';
            echo '</tr></thead><tbody>';

            $i = 1;
            foreach ($subscribers as $email) {
                echo '<tr>';
                echo '<td>' . $i . '</td>';
                echo '<td>' . esc_html($email) . '</td>';
                echo '</tr>';
                $i++;
            }

            echo '</tbody></table></div>';

            echo '<form method="post" class="mt-3">';
            submit_button('Export CSV', 'primary', 'howcan_export_csv');
            echo '</form>';

        } else {
            echo '<p>No subscribers found.</p>';
        }
        ?>
    </div>
    <?php
}

// CSV Export Handler
add_action('admin_init', 'howcan_export_csv_handler');
function howcan_export_csv_handler() {

    if (isset($_POST['howcan_export_csv'])) {

        if (!current_user_can('manage_options')) return;

        $subscribers = get_option('howcan_newsletter_emails', array());
        if (empty($subscribers)) return;

        if (ob_get_length()) ob_end_clean();

        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=newsletter-subscribers.csv');

        echo "Email\n";
        foreach ($subscribers as $email) {
            echo $email . "\n";
        }
        exit;
    }
}