<?php
/**
 * Add Months Theme Functions
 */

// Theme setup
function addmonths_setup() {
    add_theme_support('title-tag');
    add_theme_support('html5', array('search-form', 'comment-form', 'comment-list', 'gallery', 'caption'));
}
add_action('after_setup_theme', 'addmonths_setup');

// Enqueue styles
function addmonths_scripts() {
    wp_enqueue_style('addmonths-style', get_stylesheet_uri(), array(), '1.0.0');
}
add_action('wp_enqueue_scripts', 'addmonths_scripts');

// Remove WordPress extras for cleaner output
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wp_shortlink_wp_head');
remove_action('wp_head', 'rest_output_link_wp_head');
remove_action('wp_head', 'wp_oembed_add_discovery_links');
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');

// Disable XML-RPC
add_filter('xmlrpc_enabled', '__return_false');

// Create beta signups table on theme activation
function addmonths_create_signups_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'beta_signups';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        email varchar(255) NOT NULL,
        platform varchar(20) NOT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY email (email)
    ) $charset_collate;";

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

// Handle beta signup AJAX
function addmonths_handle_signup() {
    // Verify nonce
    if (!wp_verify_nonce($_POST['nonce'], 'beta_signup_nonce')) {
        wp_send_json_error('Invalid request');
        return;
    }

    $email = sanitize_email($_POST['email']);
    $platform = sanitize_text_field($_POST['platform']);

    if (!is_email($email)) {
        wp_send_json_error('Invalid email address');
        return;
    }

    if (!in_array($platform, array('ios', 'android'))) {
        wp_send_json_error('Invalid platform');
        return;
    }

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

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

    if ($exists) {
        wp_send_json_success('Already signed up');
        return;
    }

    // Insert new signup
    $result = $wpdb->insert(
        $table_name,
        array(
            'email' => $email,
            'platform' => $platform
        ),
        array('%s', '%s')
    );

    if ($result) {
        wp_send_json_success('Signed up successfully');
    } else {
        wp_send_json_error('Failed to sign up');
    }
}
add_action('wp_ajax_beta_signup', 'addmonths_handle_signup');
add_action('wp_ajax_nopriv_beta_signup', 'addmonths_handle_signup');

// Admin page to view signups
function addmonths_admin_menu() {
    add_menu_page(
        'Beta Signups',
        'Beta Signups',
        'manage_options',
        'beta-signups',
        'addmonths_signups_page',
        'dashicons-email',
        30
    );
}
add_action('admin_menu', 'addmonths_admin_menu');

function addmonths_signups_page() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'beta_signups';

    // Handle CSV export
    if (isset($_GET['export']) && $_GET['export'] === 'csv') {
        $signups = $wpdb->get_results("SELECT * FROM $table_name ORDER BY created_at DESC");

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="beta-signups-' . date('Y-m-d') . '.csv"');

        $output = fopen('php://output', 'w');
        fputcsv($output, array('Email', 'Platform', 'Signed Up'));

        foreach ($signups as $signup) {
            fputcsv($output, array($signup->email, $signup->platform, $signup->created_at));
        }

        fclose($output);
        exit;
    }

    $signups = $wpdb->get_results("SELECT * FROM $table_name ORDER BY created_at DESC");
    $total = count($signups);
    $ios_count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE platform = 'ios'");
    $android_count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE platform = 'android'");

    ?>
    <div class="wrap">
        <h1>Beta Signups</h1>

        <div style="margin: 20px 0; display: flex; gap: 20px;">
            <div style="background: #fff; padding: 20px; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
                <h3 style="margin: 0 0 5px;">Total</h3>
                <p style="font-size: 32px; margin: 0; font-weight: bold;"><?php echo $total; ?></p>
            </div>
            <div style="background: #fff; padding: 20px; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
                <h3 style="margin: 0 0 5px;">iOS</h3>
                <p style="font-size: 32px; margin: 0; font-weight: bold;"><?php echo $ios_count; ?></p>
            </div>
            <div style="background: #fff; padding: 20px; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
                <h3 style="margin: 0 0 5px;">Android</h3>
                <p style="font-size: 32px; margin: 0; font-weight: bold;"><?php echo $android_count; ?></p>
            </div>
        </div>

        <p><a href="<?php echo admin_url('admin.php?page=beta-signups&export=csv'); ?>" class="button">Export CSV</a></p>

        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th>Email</th>
                    <th>Platform</th>
                    <th>Signed Up</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($signups): ?>
                    <?php foreach ($signups as $signup): ?>
                    <tr>
                        <td><?php echo esc_html($signup->email); ?></td>
                        <td><?php echo esc_html(ucfirst($signup->platform)); ?></td>
                        <td><?php echo esc_html($signup->created_at); ?></td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="3">No signups yet.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php
}
