<?php
// Subscribers Custom Taxonomy
function create_subscribers_taxonomy() {
    $labels = array(
        'name'              => 'Subscribers',
        'singular_name'     => 'Subscriber',
        'search_items'      => 'Search Subscribers',
        'all_items'         => 'All Subscribers',
        'parent_item'       => 'Parent Subscriber',
        'parent_item_colon' => 'Parent Subscriber:',
        'edit_item'         => 'Edit Subscriber',
        'update_item'       => 'Update Subscriber',
        'add_new_item'      => 'Add New Subscriber',
        'new_item_name'     => 'New Subscriber Email',
        'menu_name'         => 'Subscribers',
    );

    $args = array(
        'hierarchical'      => false,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'show_in_menu'      => true,
        'show_in_nav_menus' => false,
        'show_tagcloud'     => false,
        'public'            => false,
        'show_in_rest'      => false,
        'meta_box_cb'       => false, // Hide meta box from posts
    );

    register_taxonomy('subscribers', array(), $args);
}
add_action('init', 'create_subscribers_taxonomy', 0);

// Add custom columns to subscribers taxonomy admin
function subscribers_taxonomy_columns($columns) {
    $new_columns = array();
    $new_columns['cb'] = $columns['cb'];
    $new_columns['name'] = 'Email Address';
    $new_columns['subscriber_date'] = 'Date Submitted';
    $new_columns['posts'] = 'Count';
    
    return $new_columns;
}
add_filter('manage_edit-subscribers_columns', 'subscribers_taxonomy_columns');

// Populate custom columns
function subscribers_taxonomy_custom_columns($content, $column_name, $term_id) {
    if ($column_name == 'subscriber_date') {
        $date = get_term_meta($term_id, 'submission_date', true);
        if ($date) {
            $content = date('F j, Y g:i a', strtotime($date));
        } else {
            $content = 'N/A';
        }
    }
    return $content;
}
add_filter('manage_subscribers_custom_column', 'subscribers_taxonomy_custom_columns', 10, 3);

// Add custom fields to taxonomy add form
function subscribers_taxonomy_add_form_fields() {
    ?>
    <div class="form-field">
        <label for="submission_date">Submission Date</label>
        <input type="datetime-local" name="submission_date" id="submission_date" value="" />
        <p class="description">Date when the subscriber signed up</p>
    </div>
    <?php
}
add_action('subscribers_add_form_fields', 'subscribers_taxonomy_add_form_fields');

// Add custom fields to taxonomy edit form
function subscribers_taxonomy_edit_form_fields($term) {
    $submission_date = get_term_meta($term->term_id, 'submission_date', true);
    $formatted_date = '';
    if ($submission_date) {
        $formatted_date = date('Y-m-d\TH:i', strtotime($submission_date));
    }
    ?>
    <tr class="form-field">
        <th scope="row" valign="top">
            <label for="submission_date">Submission Date</label>
        </th>
        <td>
            <input type="datetime-local" name="submission_date" id="submission_date" value="<?php echo esc_attr($formatted_date); ?>" />
            <p class="description">Date when the subscriber signed up</p>
        </td>
    </tr>
    <?php
}
add_action('subscribers_edit_form_fields', 'subscribers_taxonomy_edit_form_fields');

// Save custom taxonomy meta fields
function save_subscribers_taxonomy_meta($term_id) {
    if (isset($_POST['submission_date'])) {
        update_term_meta($term_id, 'submission_date', sanitize_text_field($_POST['submission_date']));
    }
}
add_action('edited_subscribers', 'save_subscribers_taxonomy_meta');
add_action('create_subscribers', 'save_subscribers_taxonomy_meta');

// Function to add new subscriber
function add_new_subscriber_taxonomy($email) {
    // Check if subscriber already exists
    $existing = term_exists($email, 'subscribers');
    
    if ($existing) {
        return false; // Subscriber already exists
    }
    
    // Create new subscriber term
    $result = wp_insert_term($email, 'subscribers');
    
    if (!is_wp_error($result)) {
        // Add submission date meta
        update_term_meta($result['term_id'], 'submission_date', current_time('mysql'));
        return true;
    }
    
    return false;
}

// Bottom section shortcode with subscription form
function bottomsection($atts = array()) {
    
    $atts = shortcode_atts(array(
        'class' => 'bottom-section'
    ), $atts);
    
    // Handle form submission
    $message = '';
    if (isset($_POST['subscribe_submit']) && isset($_POST['email'])) {
        
        // Verify nonce
        if (wp_verify_nonce($_POST['subscriber_nonce'], 'subscriber_form')) {
            $email = sanitize_email($_POST['email']);
            
            if (is_email($email)) {
                $result = add_new_subscriber_taxonomy($email);
                
                if ($result) {
                    $message = '<div class="alert alert-success mb-3">Thank you! You have been successfully subscribed.</div>';
                } else {
                    $message = '<div class="alert alert-warning mb-3">This email is already subscribed to our updates.</div>';
                }
            } else {
                $message = '<div class="alert alert-danger mb-3">Please enter a valid email address.</div>';
            }
        } else {
            $message = '<div class="alert alert-danger mb-3">Security check failed. Please try again.</div>';
        }
    }
    
    ob_start();
    ?>
    <div class="<?php echo esc_attr($atts['class']); ?>" style="background-color: #000; color:#fff; padding-top: 0px; padding-bottom:10px;">
        <div class="container">
            <?php echo $message; ?>
            <div class="row">
                
                <div class="col-md-7 d-flex align-items-center">
                     <h3>Join our news letter for the latest offers and news</h3>
                </div>
                
                <div class="col-md-5 d-flex align-items-center">
                    <div class="email-signup w-100">
                        <form action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" method="post" class="position-relative">
                            <?php wp_nonce_field('subscriber_form', 'subscriber_nonce'); ?>
                            <input type="email" 
                                   name="email" 
                                   placeholder="Enter your email address" 
                                   required 
                                   class="form-control w-100"
                                   style="background: #fff; color: #000; padding: 15px 150px 15px 20px; border: none; border-radius: 100px; font-size: 16px;">
                            <button type="submit" 
                                    name="subscribe_submit"
                                    class="btn btn-primary position-absolute"
                                    style="right: 5px; top: 50%; transform: translateY(-50%); background: #17bf28; border: none; padding: 10px 20px; border-radius: 100px; font-weight: bold;">
                                SUBSCRIBE <i class="bi bi-arrow-right-short"></i>
                            </button>
                        </form>
                    </div>
                </div>
                
            </div>
        </div>
    </div>
    
    <style>
    .email-signup input::placeholder {
        color: #666;
    }
    .email-signup input:focus {
        outline: none;
        box-shadow: 0 0 0 0.2rem rgba(237, 33, 33, 0.25);
    }
    .email-signup button:hover {
        background: #c71e1e !important;
    }
    @media (max-width: 576px) {
        .email-signup input {
            padding: 12px 120px 12px 15px !important;
            font-size: 14px !important;
        }
        .email-signup button {
            padding: 8px 15px !important;
            font-size: 12px !important;
        }
    }
    .alert {
        padding: 10px 15px;
        margin-bottom: 15px;
        border-radius: 4px;
    }
    .alert-success {
        background-color: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    .alert-warning {
        background-color: #fff3cd;
        color: #856404;
        border: 1px solid #ffeaa7;
    }
    .alert-danger {
        background-color: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }
    </style>
    
    <?php
    return ob_get_clean();
}
add_shortcode('newsletter', 'bottomsection');

// Add admin menu for easier access
function subscribers_admin_menu() {
    add_menu_page(
        'Subscribers',
        'Subscribers',
        'manage_options',
        'edit-tags.php?taxonomy=subscribers',
        '',
        'dashicons-email-alt',
        26
    );
}
add_action('admin_menu', 'subscribers_admin_menu');

// Function to export subscribers CSV
function export_subscribers_csv() {
    if (isset($_GET['export_subscribers']) && current_user_can('manage_options')) {
        $subscribers = get_terms(array(
            'taxonomy' => 'subscribers',
            'hide_empty' => false,
        ));
        
        if (!empty($subscribers)) {
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="subscribers-' . date('Y-m-d') . '.csv"');
            
            $output = fopen('php://output', 'w');
            fputcsv($output, array('Email', 'Date Submitted'));
            
            foreach ($subscribers as $subscriber) {
                $date = get_term_meta($subscriber->term_id, 'submission_date', true);
                $formatted_date = $date ? date('Y-m-d H:i:s', strtotime($date)) : '';
                fputcsv($output, array($subscriber->name, $formatted_date));
            }
            
            fclose($output);
            exit;
        }
    }
}
add_action('admin_init', 'export_subscribers_csv');

// Add export button to subscribers page
function add_export_button_to_subscribers() {
    $screen = get_current_screen();
    if ($screen && $screen->id == 'edit-subscribers') {
        echo '<div class="wrap"><p><a href="' . admin_url('edit-tags.php?taxonomy=subscribers&export_subscribers=1') . '" class="button button-secondary">Export Subscribers CSV</a></p></div>';
    }
}
add_action('admin_notices', 'add_export_button_to_subscribers');

?>