<?php
/**
 * AJAX Handlers for Groups Modal and other new features
 * WP Mailinglist Plugin
 */

if (!defined('ABSPATH')) exit; // Exit if accessed directly

/**
 * Enqueue groups modal script
 */
function newsletters_enqueue_groups_modal_script() {
    $screen = get_current_screen();
    $page = isset($_GET['page']) ? sanitize_text_field($_GET['page']) : '';
    
    // Only enqueue on newsletter pages
    if (strpos($page, 'newsletters') !== false || (isset($screen->post_type) && $screen->post_type === 'post')) {
        wp_enqueue_script(
            'newsletters-groups-modal',
            plugins_url('js/groups-modal.js', dirname(__FILE__)),
            array('jquery', 'jquery-ui-dialog'),
            '1.0.0',
            true
        );
        
        // Localize script with translations and AJAX URL
        wp_localize_script('newsletters-groups-modal', 'newsletters_groups_modal', array(
            'nonce' => wp_create_nonce('get_group_lists'),
            'viewing_lists' => esc_js(__('Viewing Lists in Group:', 'wp-mailinglist')),
            'loading' => esc_js(__('Loading...', 'wp-mailinglist')),
            'error' => esc_js(__('Error loading lists. Please try again.', 'wp-mailinglist')),
            'no_lists' => esc_js(__('No lists found in this group.', 'wp-mailinglist')),
            'list_name' => esc_js(__('List Name', 'wp-mailinglist')),
            'subscribers' => esc_js(__('Subscribers', 'wp-mailinglist')),
            'active' => esc_js(__('active', 'wp-mailinglist'))
        ));
    }
}
add_action('admin_enqueue_scripts', 'newsletters_enqueue_groups_modal_script');

/**
 * Enqueue deactivation survey script
 */
function newsletters_enqueue_deactivation_survey() {
    $screen = get_current_screen();
    
    // Only on plugins page
    if (isset($screen->id) && $screen->id === 'plugins') {
        wp_enqueue_script(
            'newsletters-deactivation-survey',
            plugins_url('js/deactivation-survey.js', dirname(__FILE__)),
            array('jquery'),
            '1.0.0',
            true
        );

        wp_localize_script('newsletters-deactivation-survey', 'newsletters_survey_strings', array(
            'quick_feedback' => __('QUICK FEEDBACK', 'wp-mailinglist'),
            'intro' => __('If you have a moment, please share why you are deactivating Newsletters:', 'wp-mailinglist'),
            'reason_found_better' => __('I found a better plugin.', 'wp-mailinglist'),
            'reason_temporary' => __('Temporary deactivation.', 'wp-mailinglist'),
            'reason_missing_features' => __('Missing features.', 'wp-mailinglist'),
            'reason_not_working' => __('Plugin not working well. Issue(s) found.', 'wp-mailinglist'),
            'reason_other' => __('Other (We really would appreciate your comments to improve our product).', 'wp-mailinglist'),
            'placeholder_found_better' => __('Please let us know which plugin', 'wp-mailinglist'),
            'placeholder_not_working' => __('Please let us know the issue(s) or feel free to submit a ticket', 'wp-mailinglist'),
            'placeholder_missing_features' => __('Please let us know which features', 'wp-mailinglist'),
            'placeholder_default' => __('Please share the reason', 'wp-mailinglist'),
            'submit_btn' => __('Submit & Deactivate', 'wp-mailinglist'),
            'submit_btn_loading' => __('Submitting...', 'wp-mailinglist'),
            'skip_btn' => __('Skip & Deactivate', 'wp-mailinglist'),
            'support_link' => __('Submit support request &rarr;', 'wp-mailinglist'),
            'alert_select_reason' => __('Please select a reason', 'wp-mailinglist')
        ));
    }
}
add_action('admin_enqueue_scripts', 'newsletters_enqueue_deactivation_survey');

/**
 * AJAX handler to get lists for a specific group
 * Security: Nonce verification, input sanitization, SQL escaping
 */
function ajax_get_group_lists() {
    global $wpdb, $Mailinglist, $SubscribersList;
    
    // Security: Verify nonce
    if (!check_ajax_referer('get_group_lists', 'security', false)) {
        wp_send_json_error(array(
            'message' => esc_html__('Security check failed', 'wp-mailinglist')
        ));
        wp_die();
    }
    
    // Security: Check user capabilities
    if (!current_user_can('edit_posts')) {
        wp_send_json_error(array(
            'message' => esc_html__('Insufficient permissions', 'wp-mailinglist')
        ));
        wp_die();
    }
    
    // Security: Sanitize and validate input
    $group_id = isset($_POST['group_id']) ? absint($_POST['group_id']) : 0;
    
    if (empty($group_id) || $group_id < 1) {
        wp_send_json_error(array(
            'message' => esc_html__('Invalid group ID', 'wp-mailinglist')
        ));
        wp_die();
    }
    
    // Security: Use prepared statement for SQL query
    $lists_query = $wpdb->prepare(
        "SELECT `id`, `title` FROM `" . $wpdb->prefix . esc_sql($Mailinglist->table) . "` WHERE `group_id` = %d ORDER BY `title` ASC",
        $group_id
    );
    $lists = $wpdb->get_results($lists_query);
    
    if (empty($lists)) {
        wp_send_json_success(array(
            'lists' => array(),
            'message' => esc_html__('No lists found in this group', 'wp-mailinglist')
        ));
        wp_die();
    }
    
    // Format lists with subscriber counts
    $formatted_lists = array();
    foreach ($lists as $list) {
        // Security: Sanitize output
        $list_id = absint($list->id);
        $subscriber_count = $SubscribersList->count(array('list_id' => $list_id, 'active' => 'Y'));
        
        $formatted_lists[] = array(
            'id' => $list_id,
            'title' => esc_html(__($list->title)),
            'subscriber_count' => absint($subscriber_count)
        );
    }
    
    wp_send_json_success(array(
        'lists' => $formatted_lists
    ));
    wp_die();
}

/**
 * AJAX handler for post preview (without saving)
 * Security: Nonce verification, input sanitization
 * Uses plugin's template rendering to properly show preview with shortcodes
 */
function ajax_newsletters_post_preview() {
    global $wpdb, $Mailinglist, $Theme, $wpMail;
    
    // Get plugin instance - wpMail is the global instance
    if (!isset($wpMail)) {
        $wpMail = $GLOBALS['wpMail'];
    }
    
    // Security: Verify nonce
    if (!check_ajax_referer('post_preview', 'security', false)) {
        wp_send_json_error(array(
            'message' => esc_html__('Security check failed', 'wp-mailinglist')
        ));
        wp_die();
    }
    
    // Security: Check user capabilities
    if (!current_user_can('edit_posts')) {
        wp_send_json_error(array(
            'message' => esc_html__('Insufficient permissions', 'wp-mailinglist')
        ));
        wp_die();
    }
    
    // Security: Sanitize and validate input
    $post_id = isset($_POST['post_ID']) ? absint($_POST['post_ID']) : 0;
    
    if (empty($post_id) || $post_id < 1) {
        wp_send_json_error(array(
            'message' => esc_html__('Invalid post ID', 'wp-mailinglist')
        ));
        wp_die();
    }
    
    // Security: Verify user can edit this post
    if (!current_user_can('edit_post', $post_id)) {
        wp_send_json_error(array(
            'message' => esc_html__('You do not have permission to preview this post', 'wp-mailinglist')
        ));
        wp_die();
    }
    
    // Get post object
    $post = get_post($post_id);
    if (!$post) {
        wp_send_json_error(array(
            'message' => esc_html__('Post not found', 'wp-mailinglist')
        ));
        wp_die();
    }
    
    // Set global post for shortcodes
    global $shortcode_post;
    $shortcode_post = $post;
    
    // Get theme ID from POST or meta
    $theme_id = isset($_POST['newsletters_theme_id']) ? absint($_POST['newsletters_theme_id']) : get_post_meta($post_id, '_newsletters_theme_id', true);
    
    // Get theme using the plugin's helper function
    $theme = false;
    if (!empty($theme_id) && function_exists('newsletters_get_theme')) {
        $theme = newsletters_get_theme($theme_id);
    } elseif (!empty($theme_id)) {
        // Fallback: Direct database query
        $theme_query = $wpdb->prepare(
            "SELECT * FROM `" . $wpdb->prefix . esc_sql($Theme->table) . "` WHERE `id` = %d LIMIT 1",
            $theme_id
        );
        $theme = $wpdb->get_row($theme_query);
    }
    
    // If no theme, get default theme
    if (!$theme) {
        $default_theme_query = "SELECT * FROM `" . $wpdb->prefix . esc_sql($Theme->table) . "` WHERE `def` = 'Y' LIMIT 1";
        $theme = $wpdb->get_row($default_theme_query);
    }
    
    // Build message content
    $message = '<h1>' . $post->post_title . '</h1>';
    
    // Show date/author if enabled
    $show_date = isset($_POST['newsletters_showdate']) ? sanitize_text_field($_POST['newsletters_showdate']) : get_post_meta($post_id, '_newsletters_showdate', true);
    if (!empty($show_date)) {
        $message .= '<p><em>' . __('By', 'wp-mailinglist') . ' ' . get_the_author_meta('display_name', $post->post_author) . ' - ' . get_the_date('', $post) . '</em></p>';
    }
    
    $message .= wpautop($post->post_content);
    
    // Process shortcodes using plugin's function
    $message = do_shortcode($message);
    
    // Build full HTML with theme
    if ($theme && !empty($theme->content)) {
        // Replace [newsletters_main_content] placeholder in theme with actual content
        $output = str_replace('[newsletters_main_content]', $message, $theme->content);
        // Also try legacy placeholder
        $output = str_replace('[newsletters_content]', $message, $output);
        $output = str_replace('[' . $wpMail->pre . '_content]', $message, $output);
        $output = str_replace('[' . $wpMail->pre . '_main_content]', $message, $output);
    } else {
        // No theme, just wrap in basic HTML
        $output = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>' . esc_html($post->post_title) . '</title></head><body>' . $message . '</body></html>';
    }
    
    // Process template variables and shortcodes
    if (method_exists($wpMail, 'process_set_variables')) {
        $output = $wpMail->process_set_variables(null, null, $output, false, false, false);
    }
    
    // Apply inline styles if enabled
    if (method_exists($wpMail, 'inlinestyles')) {
        $output = $wpMail->inlinestyles($output);
    }
    
    wp_send_json_success(array(
        'html' => $output
    ));
    wp_die();
}

// Register AJAX handlers
add_action('wp_ajax_newsletters_get_group_lists', 'ajax_get_group_lists');
add_action('wp_ajax_newsletters_post_preview', 'ajax_newsletters_post_preview');
add_action('wp_ajax_newsletters_get_list_subscribers', 'ajax_get_list_subscribers');
add_action('wp_ajax_newsletters_get_role_users', 'ajax_get_role_users');
add_action('admin_enqueue_scripts', 'newsletters_enqueue_send_post_modals_script');

/**
 * Enqueue send post modals script
 */
function newsletters_enqueue_send_post_modals_script() {
    $screen = get_current_screen();
    
    // Only enqueue on post edit pages or newsletters pages
    if ((isset($screen->post_type) && ($screen->post_type === 'post' || $screen->post_type === 'page')) || (isset($_GET['page']) && strpos($_GET['page'], 'newsletters') !== false)) {
        wp_enqueue_script(
            'newsletters-send-post-modals',
            plugins_url('js/send-post-modals.js', dirname(__FILE__)),
            array('jquery', 'jquery-ui-dialog'),
            '1.0.0',
            true
        );
        
        wp_localize_script('newsletters-send-post-modals', 'newsletters_send_modals', array(
            'nonce' => wp_create_nonce('newsletters_send_modals'),
            'viewing_subscribers' => esc_js(__('Viewing Subscribers in List', 'wp-mailinglist')),
            'viewing_users' => esc_js(__('Viewing Users in Role', 'wp-mailinglist')),
            'loading' => esc_js(__('Loading...', 'wp-mailinglist')),
            'error' => esc_js(__('Error loading data. Please try again.', 'wp-mailinglist')),
            'no_results' => esc_js(__('No results found.', 'wp-mailinglist')),
            'email' => esc_js(__('Email Address', 'wp-mailinglist')),
            'id' => esc_js(__('ID', 'wp-mailinglist')),
            'username' => esc_js(__('Username', 'wp-mailinglist')),
            'prev' => esc_js(__('Prev', 'wp-mailinglist')),
            'next' => esc_js(__('Next', 'wp-mailinglist')),
            'page' => esc_js(__('Page', 'wp-mailinglist')),
            'of' => esc_js(__('of', 'wp-mailinglist')),
            'search_placeholder' => esc_js(__('Search subscribers...', 'wp-mailinglist')),
            'search_users_placeholder' => esc_js(__('Search users...', 'wp-mailinglist'))
        ));
    }
}

/**
 * AJAX handler to get subscribers for a specific list
 */
function ajax_get_list_subscribers() {
    global $wpdb, $SubscribersList, $Subscriber;
    
    if (!check_ajax_referer('newsletters_send_modals', 'security', false)) {
        wp_send_json_error(array('message' => __('Security check failed', 'wp-mailinglist')));
    }
    
    if (!current_user_can('edit_posts')) {
        wp_send_json_error(array('message' => __('Insufficient permissions', 'wp-mailinglist')));
    }
    
    $list_id = isset($_POST['list_id']) ? absint($_POST['list_id']) : 0;
    $page = isset($_POST['page']) ? absint($_POST['page']) : 1;
    $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
    $per_page = 20;
    $offset = ($page - 1) * $per_page;
    
    if (empty($list_id)) {
        wp_send_json_error(array('message' => __('Invalid list ID', 'wp-mailinglist')));
    }
    
    // Build query
    // We need to join with subscribers table to search by email/etc if needed
    // But SubscribersList->select already handles list connection.
    // Let's rely on SubscribersList model but we might need a custom query for efficiency and search
    
    $search_sql = "";
    if (!empty($search)) {
        $search_term = '%' . $wpdb->esc_like($search) . '%';
        $search_sql = $wpdb->prepare(" AND (s.`email` LIKE %s)", $search_term);
    }
    
    // Count total
    $count_query = $wpdb->prepare(
        "SELECT COUNT(DISTINCT s.`id`) FROM `" . $wpdb->prefix . $Subscriber->table . "` s 
        LEFT JOIN `" . $wpdb->prefix . $SubscribersList->table . "` sl ON s.`id` = sl.`subscriber_id` 
        WHERE sl.`list_id` = %d AND sl.`active` = 'Y' $search_sql",
        $list_id
    );
    $total_subscribers = $wpdb->get_var($count_query);
    $total_pages = ceil($total_subscribers / $per_page);
    
    // Fetch subscribers
    $query = $wpdb->prepare(
        "SELECT DISTINCT s.`id`, s.`email` FROM `" . $wpdb->prefix . $Subscriber->table . "` s 
        LEFT JOIN `" . $wpdb->prefix . $SubscribersList->table . "` sl ON s.`id` = sl.`subscriber_id` 
        WHERE sl.`list_id` = %d AND sl.`active` = 'Y' $search_sql 
        ORDER BY s.`id` DESC LIMIT %d, %d",
        $list_id, $offset, $per_page
    );
    
    $subscribers = $wpdb->get_results($query);
    
    $formatted_subscribers = array();
    foreach ($subscribers as $sub) {
        $formatted_subscribers[] = array(
            'id' => $sub->id,
            'email' => $sub->email
        );
    }
    
    wp_send_json_success(array(
        'subscribers' => $formatted_subscribers,
        'total_pages' => $total_pages,
        'current_page' => $page
    ));
}

/**
 * AJAX handler to get users for a specific role
 */
function ajax_get_role_users() {
    global $wp_roles;
    
    if (!check_ajax_referer('newsletters_send_modals', 'security', false)) {
        wp_send_json_error(array('message' => __('Security check failed', 'wp-mailinglist')));
    }
    
    if (!current_user_can('edit_posts')) {
        wp_send_json_error(array('message' => __('Insufficient permissions', 'wp-mailinglist')));
    }
    
    $role = isset($_POST['role']) ? sanitize_text_field($_POST['role']) : '';
    $page = isset($_POST['page']) ? absint($_POST['page']) : 1;
    $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
    $per_page = 20;
    
    if (empty($role)) {
        wp_send_json_error(array('message' => __('Invalid role', 'wp-mailinglist')));
    }
    
    $args = array(
        'role' => $role,
        'number' => $per_page,
        'paged' => $page,
        'search' => '*' . $search . '*',
        'fields' => array('ID', 'user_email', 'display_name'),
        'orderby' => 'display_name',
        'order' => 'ASC'
    );
    
    $user_query = new WP_User_Query($args);
    $users = $user_query->get_results();
    $total_users = $user_query->get_total();
    $total_pages = ceil($total_users / $per_page);
    
    $formatted_users = array();
    foreach ($users as $user) {
        $formatted_users[] = array(
            'id' => $user->ID,
            'user_email' => $user->user_email,
            'display_name' => $user->display_name
        );
    }
    
    wp_send_json_success(array(
        'users' => $formatted_users,
        'total_pages' => $total_pages,
        'current_page' => $page
    ));
}

?>
