<?php
/**
 * Admin Entries Management
 *
 * @package Spin_Wheel
 */

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

/**
 * SWP_Admin_Entries Class
 */
// Direct queries below target the plugin's own swp_entries / swp_winners tables
// (prepared, internal identifiers) with no applicable caching layer.
// phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL, WordPress.DB.PreparedSQLPlaceholders, PluginCheck.Security.DirectDB
class SWP_Admin_Entries {
    
    /**
     * Instance
     *
     * @var SWP_Admin_Entries
     */
    private static $instance = null;
    
    /**
     * Get instance
     *
     * @return SWP_Admin_Entries
     */
    public static function instance() {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        add_action('admin_menu', [$this, 'add_entries_page']);
        add_action('wp_ajax_swp_delete_entry', [$this, 'delete_entry']);
        add_action('wp_ajax_swp_bulk_delete_entries', [$this, 'bulk_delete_entries']);
        add_action('wp_ajax_swp_export_filtered_entries', [$this, 'export_filtered_entries']);
        add_action('wp_ajax_swp_load_entries_pagination', [$this, 'ajax_load_entries_pagination']);
    }
    
    /**
     * Add entries page
     */
    public function add_entries_page() {
        add_submenu_page(
            'edit.php?post_type=swp_wheel',
            __('Entries', 'spin-wheel'),
            __('Entries', 'spin-wheel'),
            'manage_options',
            'swp-entries',
            [$this, 'render_entries_page']
        );
    }
    
    /**
     * Render entries page
     */
    public function render_entries_page() {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only list filters on a manage_options screen; no state change.
        $status_filter = isset($_GET['status_filter']) ? sanitize_text_field(wp_unslash($_GET['status_filter'])) : '';
        $search_query = isset($_GET['search_query']) ? sanitize_text_field(wp_unslash($_GET['search_query'])) : '';
        
        // Pagination parameters
        $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
        $per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 10;
        
        // Validate per_page value
        $allowed_per_page = [10, 25, 50, 100, 200];
        if (!in_array($per_page, $allowed_per_page)) {
            $per_page = 10;
        }
        
        // Get all wheels for dropdown
        $wheels = get_posts([
            'post_type'      => 'swp_wheel',
            'posts_per_page' => -1,
            'post_status'    => 'any',
            'orderby'        => 'title',
            'order'          => 'ASC',
        ]);
        
        // Auto-select first wheel if no wheel_id is provided
        $wheel_id = isset($_GET['wheel_id']) ? intval($_GET['wheel_id']) : 0;
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        $auto_selected = false;
        if (!$wheel_id && !empty($wheels)) {
            $wheel_id = $wheels[0]->ID;
            $auto_selected = true;
        }
        
        // Get entries if wheel selected
        $entries = [];
        $all_entries_unfiltered = []; // For statistics - always unfiltered
        $total_entries = 0;
        $total_filtered = 0;
        $wheel_mode = '';
        
        if ($wheel_id) {
            $db = SWP_Database::instance();
            
            // Get all entries - UNFILTERED for statistics
            $all_entries_unfiltered = $db->get_all_entries($wheel_id);
            $total_entries = count($all_entries_unfiltered);
            
            // Get all entries for filtering (copy for filtering)
            $all_entries = $all_entries_unfiltered;
            
            // Apply status filter
            if ($status_filter && !empty($all_entries)) {
                $all_entries = $this->apply_status_filter($all_entries, $status_filter);
            }
            
            // Apply search filter
            if ($search_query && !empty($all_entries)) {
                $all_entries = $this->apply_search_filter($all_entries, $search_query);
            }
            
            $total_filtered = count($all_entries);
            
            // Calculate total pages
            $total_pages = $total_filtered > 0 ? ceil($total_filtered / $per_page) : 1;
            
            // Ensure current page doesn't exceed total pages
            $current_page = min($current_page, $total_pages);
            
            // Apply pagination
            $offset = ($current_page - 1) * $per_page;
            $entries = array_slice($all_entries, $offset, $per_page);
            
            $wheel_mode = get_post_meta($wheel_id, '_swp_wheel_mode', true);
        } else {
            $total_pages = 1;
        }
        
        include SPIN_WHEEL_PATH . 'admin/templates/entries.php';
    }
    
    /**
     * Delete single entry
     */
    public function delete_entry() {
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'spin-wheel')]);
        }
        
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'swp_delete_nonce')) {
            wp_send_json_error(['message' => __('Security check failed', 'spin-wheel')]);
        }
        
        $entry_id = isset($_POST['entry_id']) ? intval($_POST['entry_id']) : 0;
        
        if (!$entry_id) {
            wp_send_json_error(['message' => __('Invalid entry ID', 'spin-wheel')]);
        }
        
        global $wpdb;
        
        // Delete from entries table
        $result = $wpdb->delete(
            $wpdb->prefix . 'swp_entries',
            ['id' => $entry_id],
            ['%d']
        );
        
        if ($result === false) {
            wp_send_json_error(['message' => __('Failed to delete entry', 'spin-wheel')]);
        }
        
        // Also delete from winners table if exists
        $wpdb->delete(
            $wpdb->prefix . 'swp_winners',
            ['entry_id' => $entry_id],
            ['%d']
        );
        
        wp_send_json_success(['message' => __('Entry deleted successfully', 'spin-wheel')]);
    }
    
    /**
     * Bulk delete entries
     */
    public function bulk_delete_entries() {
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'spin-wheel')]);
        }
        
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'swp_bulk_delete_nonce')) {
            wp_send_json_error(['message' => __('Security check failed', 'spin-wheel')]);
        }
        
        $entry_ids = isset($_POST['entry_ids']) ? array_map('intval', (array) wp_unslash($_POST['entry_ids'])) : [];
        
        if (empty($entry_ids) || !is_array($entry_ids)) {
            wp_send_json_error(['message' => __('No entries selected', 'spin-wheel')]);
        }
        
        // Sanitize entry IDs
        $entry_ids = array_map('intval', $entry_ids);
        $entry_ids = array_filter($entry_ids, function($id) { return $id > 0; });
        
        if (empty($entry_ids)) {
            wp_send_json_error(['message' => __('Invalid entry IDs', 'spin-wheel')]);
        }
        
        global $wpdb;
        
        // Prepare placeholders for IN clause
        $placeholders = implode(',', array_fill(0, count($entry_ids), '%d'));
        
        // Delete from entries table
        $result = $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}swp_entries WHERE id IN ($placeholders)",
            $entry_ids
        ));
        
        if ($result === false) {
            wp_send_json_error(['message' => __('Failed to delete entries', 'spin-wheel')]);
        }
        
        // Also delete from winners table
        $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}swp_winners WHERE entry_id IN ($placeholders)",
            $entry_ids
        ));
        
        $deleted_count = $result;
        wp_send_json_success([
            /* translators: %d: number of deleted entries */
            'message' => sprintf(__('%d entry(ies) deleted successfully', 'spin-wheel'), $deleted_count),
            'deleted_count' => $deleted_count
        ]);
    }
    
    /**
     * Export filtered entries (admin only)
     */
    public function export_filtered_entries() {
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Permission denied', 'spin-wheel'));
        }
        
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'swp_export_filtered_nonce')) {
            wp_die(esc_html__('Security check failed', 'spin-wheel'));
        }
        
        $wheel_id = isset($_POST['wheel_id']) ? intval($_POST['wheel_id']) : 0;
        $status_filter = isset($_POST['status_filter']) ? sanitize_text_field(wp_unslash($_POST['status_filter'])) : '';
        $search_query = isset($_POST['search_query']) ? sanitize_text_field(wp_unslash($_POST['search_query'])) : '';
        
        if (!$wheel_id) {
            wp_die(esc_html__('Invalid wheel', 'spin-wheel'));
        }
        
        $db = SWP_Database::instance();
        
        // Get all entries for filtering
        $all_entries = $db->get_all_entries($wheel_id);
        
        // Apply filters
        $filtered_entries = $all_entries;
        
        // Apply status filter
        if ($status_filter) {
            $filtered_entries = array_filter($filtered_entries, function($entry) use ($status_filter) {
                switch ($status_filter) {
                    case 'winner':
                        return $entry->is_selected_winner == 1;
                    case 'won_prize':
                        return $entry->is_winner == 1 && $entry->is_selected_winner == 0;
                    case 'participated':
                        return $entry->is_winner == 0;
                    default:
                        return true;
                }
            });
        }
        
        // Apply search filter
        if ($search_query && !empty($filtered_entries)) {
            $search_query_lower = strtolower($search_query);
            $filtered_entries = array_filter($filtered_entries, function($entry) use ($search_query_lower) {
                $utm_search = strtolower(swp_entry_format_utm_csv($entry));
                return (
                    strpos(strtolower($entry->user_name), $search_query_lower) !== false ||
                    strpos(strtolower($entry->user_email), $search_query_lower) !== false ||
                    strpos(strtolower($entry->user_phone), $search_query_lower) !== false ||
                    strpos(strtolower($entry->prize_label), $search_query_lower) !== false ||
                    strpos(strtolower($entry->prize_code), $search_query_lower) !== false ||
                    strpos(strtolower((string) $entry->id), $search_query_lower) !== false ||
                    ($utm_search !== '' && strpos($utm_search, $search_query_lower) !== false)
                );
            });
        }
        
        // Set headers for CSV download
        $filename = 'wheel-filtered-entries-' . $wheel_id . '-' . gmdate('Y-m-d-H-i-s') . '.csv';
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=' . $filename);
        
        // Create CSV
        $output = fopen('php://output', 'w'); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen,WordPress.WP.AlternativeFunctions.file_system_operations_fclose
        
        // Headers
        fputcsv($output, [
            'ID', 'Name', 'Email', 'Phone', 'Campaign (UTM)', 'Prize', 'Code', 'Is Winner', 'Is Selected Winner', 'Created At',
        ]);
        
        // Data
        foreach ($filtered_entries as $entry) {
            fputcsv($output, [
                $entry->id,
                swp_csv_safe_cell($entry->user_name),
                swp_csv_safe_cell($entry->user_email),
                swp_csv_safe_cell($entry->user_phone),
                swp_csv_safe_cell(swp_entry_format_utm_csv($entry)),
                swp_csv_safe_cell($entry->prize_label),
                swp_csv_safe_cell($entry->prize_code),
                $entry->is_winner ? 'Yes' : 'No',
                $entry->is_selected_winner ? 'Yes' : 'No',
                $entry->created_at,
            ]);
        }
        
        fclose($output); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen,WordPress.WP.AlternativeFunctions.file_system_operations_fclose
        exit;
    }
    
    /**
     * Apply status filter to entries
     */
    private function apply_status_filter($entries, $status_filter) {
        return array_values(array_filter($entries, function($entry) use ($status_filter) {
            switch ($status_filter) {
                case 'won_prize':
                    // Users who won a prize (is_winner = 1)
                    return $entry->is_winner == 1;
                    
                case 'selected_winner':
                    // Users who were selected as winners in event mode (is_selected_winner = 1)
                    return $entry->is_selected_winner == 1;
                    
                case 'participated':
                    // Users who only participated but didn't win (is_winner = 0 AND is_selected_winner = 0)
                    return $entry->is_winner == 0 && $entry->is_selected_winner == 0;
                    
                default:
                    // Show all entries
                    return true;
            }
        }));
    }
    
    /**
     * Apply search filter to entries
     */
    private function apply_search_filter($entries, $search_query) {
        $search_query_lower = strtolower($search_query);
        return array_values(array_filter($entries, function($entry) use ($search_query_lower) {
            $utm_search = strtolower(swp_entry_format_utm_csv($entry));
            return (
                strpos(strtolower($entry->user_name), $search_query_lower) !== false ||
                strpos(strtolower($entry->user_email), $search_query_lower) !== false ||
                strpos(strtolower($entry->user_phone), $search_query_lower) !== false ||
                strpos(strtolower($entry->prize_label), $search_query_lower) !== false ||
                strpos(strtolower($entry->prize_code), $search_query_lower) !== false ||
                strpos(strtolower((string) $entry->id), $search_query_lower) !== false ||
                ($utm_search !== '' && strpos($utm_search, $search_query_lower) !== false)
            );
        }));
    }
    
    /**
     * AJAX handler for pagination
     */
    public function ajax_load_entries_pagination() {
        // Security checks
        check_ajax_referer('swp_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'spin-wheel')]);
        }
        
        // Get parameters
        $wheel_id = isset($_POST['wheel_id']) ? intval($_POST['wheel_id']) : 0;
        $status_filter = isset($_POST['status_filter']) ? sanitize_text_field(wp_unslash($_POST['status_filter'])) : '';
        $search_query = isset($_POST['search_query']) ? sanitize_text_field(wp_unslash($_POST['search_query'])) : '';
        $current_page = isset($_POST['paged']) ? max(1, intval($_POST['paged'])) : 1;
        $per_page = isset($_POST['per_page']) ? intval($_POST['per_page']) : 50;
        
        // Validate per_page
        $allowed_per_page = [10, 25, 50, 100, 200];
        if (!in_array($per_page, $allowed_per_page)) {
            $per_page = 50;
        }
        
        if (!$wheel_id) {
            wp_send_json_error(['message' => __('Invalid wheel ID', 'spin-wheel')]);
        }
        
        $db = SWP_Database::instance();
        
        // Get all entries
        $all_entries = $db->get_all_entries($wheel_id);
        
        // Apply filters
        if ($status_filter && !empty($all_entries)) {
            $all_entries = $this->apply_status_filter($all_entries, $status_filter);
        }
        
        if ($search_query && !empty($all_entries)) {
            $all_entries = $this->apply_search_filter($all_entries, $search_query);
        }
        
        $total_filtered = count($all_entries);
        
        // Calculate total pages
        $total_pages = $total_filtered > 0 ? ceil($total_filtered / $per_page) : 1;
        
        // Ensure current page doesn't exceed total pages
        $current_page = min($current_page, $total_pages);
        
        // Apply pagination
        $offset = ($current_page - 1) * $per_page;
        $entries = array_slice($all_entries, $offset, $per_page);
        
        // Get wheel mode
        $wheel_mode = get_post_meta($wheel_id, '_swp_wheel_mode', true);
        
        // Generate table HTML
        ob_start();
        if (!empty($entries)) {
            foreach ($entries as $entry) {
                $this->render_table_row($entry, $wheel_mode);
            }
        } else {
            echo '<tr><td colspan="11" style="text-align:center;padding:40px;">' . esc_html__('No entries found.', 'spin-wheel') . '</td></tr>';
        }
        $table_html = ob_get_clean();
        
        // Generate pagination HTML - separate for top and bottom
        $pagination_top_html = $this->generate_pagination_html($current_page, $total_pages, $per_page, $total_filtered, false, true);
        $pagination_bottom_html = $this->generate_pagination_html($current_page, $total_pages, $per_page, $total_filtered, true, false);
        
        wp_send_json_success([
            'table_html' => $table_html,
            'pagination_top_html' => $pagination_top_html,
            'pagination_bottom_html' => $pagination_bottom_html,
            'total_filtered' => $total_filtered,
            'current_page' => $current_page,
            'total_pages' => $total_pages
        ]);
    }
    
    /**
     * Render a single table row
     */
    private function render_table_row($entry, $wheel_mode) {
        ?>
        <tr class="swp-entry-row <?php echo $entry->is_selected_winner ? 'swp-winner-row' : ''; ?>">
            <td class="swp-col-checkbox">
                <input type="checkbox" class="swp-entry-checkbox" value="<?php echo esc_attr($entry->id); ?>">
            </td>
            <td class="swp-col-id"><strong>#<?php echo esc_html($entry->id); ?></strong></td>
            <td class="swp-col-name">
                <strong><?php echo esc_html($entry->user_name); ?></strong>
            </td>
            <td class="swp-col-email">
                <a href="mailto:<?php echo esc_attr($entry->user_email); ?>">
                    <?php echo esc_html($entry->user_email); ?>
                </a>
            </td>
            <td class="swp-col-phone">
                <?php echo esc_html($entry->user_phone ?: '—'); ?>
            </td>
            <td class="swp-col-utm swp-entry-utm-cell"<?php
            $utm_plain = swp_entry_format_utm_csv($entry);
            echo $utm_plain !== '' ? ' title="' . esc_attr($utm_plain) . '"' : '';
            ?>>
                <?php
                $utm_html = swp_entry_format_utm_admin_cell($entry);
                echo $utm_html !== '' ? wp_kses($utm_html, ['br' => []]) : '<span>—</span>';
                ?>
            </td>
            <td class="swp-col-prize">
                <div class="swp-prize-info">
                    <strong><?php echo esc_html($entry->prize_label); ?></strong>
                </div>
            </td>
            <td class="swp-col-code">
                <?php if ($entry->prize_code) : ?>
                    <code class="swp-prize-code"><?php echo esc_html($entry->prize_code); ?></code>
                <?php else : ?>
                    <span>—</span>
                <?php endif; ?>
            </td>
            <td class="swp-col-date">
                <div class="swp-date-info">
                    <div><?php echo esc_html(date_i18n(get_option('date_format'), strtotime($entry->created_at))); ?></div>
                    <small><?php echo esc_html(date_i18n(get_option('time_format'), strtotime($entry->created_at))); ?></small>
                </div>
            </td>
            <td class="swp-col-status">
                <?php if ($entry->is_selected_winner) : ?>
                    <span class="swp-badge swp-badge-winner">
                        <span class="dashicons dashicons-trophy"></span>
                        <?php esc_html_e('Winner', 'spin-wheel'); ?>
                    </span>
                <?php elseif ($entry->is_winner) : ?>
                    <span class="swp-badge swp-badge-won">
                        <span class="dashicons dashicons-star-filled"></span>
                        <?php esc_html_e('Won Prize', 'spin-wheel'); ?>
                    </span>
                <?php else : ?>
                    <span class="swp-badge swp-badge-participated">
                        <?php esc_html_e('Participated', 'spin-wheel'); ?>
                    </span>
                <?php endif; ?>
            </td>
            <td class="swp-col-actions">
                <div class="swp-entry-actions">
                    <?php
                    /**
                     * Event Mode winner actions (Select Winner / Revert) are rendered here
                     * by the Spin Wheel Pro add-on. Nothing renders in the free plugin.
                     *
                     * @param object $entry      Entry row from swp_entries.
                     * @param string $wheel_mode Current wheel mode.
                     */
                    do_action('swp_entry_row_winner_actions', $entry, $wheel_mode);
                    ?>

                    <!-- Delete Button -->
                    <button type="button" class="button button-small swp-delete-entry"
                            data-entry-id="<?php echo esc_attr($entry->id); ?>"
                            data-user-name="<?php echo esc_attr($entry->user_name); ?>"
                            title="<?php esc_html_e('Delete Entry', 'spin-wheel'); ?>">
                        <span class="dashicons dashicons-trash"></span>
                        <?php esc_html_e('Delete', 'spin-wheel'); ?>
                    </button>
                </div>
            </td>
        </tr>
        <?php
    }
    
    /**
     * Generate pagination HTML
     */
    private function generate_pagination_html($current_page, $total_pages, $per_page, $total_filtered, $show_controls = true, $show_per_page = true) {
        // Return empty string if no entries
        if ($total_filtered == 0) {
            return '';
        }
        
        $has_multiple_pages = $total_filtered > $per_page;
        $show_pagination_controls = $has_multiple_pages && $show_controls;
        
        ob_start();
        ?>
        <div class="swp-pagination-wrapper">
            <?php if ($show_pagination_controls) : ?>
                <div class="swp-pagination-info">
                    <?php
                    $start = ($current_page - 1) * $per_page + 1;
                    $end = min($current_page * $per_page, $total_filtered);
                    printf(
                        /* translators: 1: first entry number, 2: last entry number, 3: total number of entries */
                        esc_html__('Showing %1$d-%2$d of %3$d entries', 'spin-wheel'),
                        (int) $start,
                        (int) $end,
                        (int) $total_filtered
                    );
                    ?>
                </div>
                
                <div class="swp-pagination-controls">
                    <?php if ($current_page > 1) : ?>
                        <a href="#" class="swp-pagination-link swp-prev-page" data-page="<?php echo esc_attr($current_page - 1); ?>">
                            <span class="dashicons dashicons-arrow-left-alt2"></span>
                            <span><?php esc_html_e('Previous', 'spin-wheel'); ?></span>
                        </a>
                    <?php endif; ?>
                    
                    <?php
                    $range = 2;
                    for ($i = 1; $i <= $total_pages; $i++) :
                        if ($i == 1 || $i == $total_pages || ($i >= $current_page - $range && $i <= $current_page + $range)) :
                            $active_class = ($i == $current_page) ? 'swp-current-page' : '';
                        ?>
                            <a href="#" class="swp-pagination-link <?php echo esc_attr($active_class); ?>" data-page="<?php echo esc_attr($i); ?>">
                                <?php echo esc_html($i); ?>
                            </a>
                        <?php
                        elseif ($i == $current_page - $range - 1 || $i == $current_page + $range + 1) :
                        ?>
                            <span class="swp-pagination-dots">...</span>
                        <?php
                        endif;
                    endfor;
                    ?>
                    
                    <?php if ($current_page < $total_pages) : ?>
                        <a href="#" class="swp-pagination-link swp-next-page" data-page="<?php echo esc_attr($current_page + 1); ?>">
                            <span><?php esc_html_e('Next', 'spin-wheel'); ?></span>
                            <span class="dashicons dashicons-arrow-right-alt2"></span>
                        </a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            
            <?php if ($show_per_page) : ?>
                <div class="swp-per-page-selector">
                    <label for="entries-per-page"><?php esc_html_e('Show:', 'spin-wheel'); ?></label>
                    <select id="entries-per-page" name="per_page">
                        <option value="10" <?php selected($per_page, 10); ?>>10</option>
                        <option value="25" <?php selected($per_page, 25); ?>>25</option>
                        <option value="50" <?php selected($per_page, 50); ?>>50</option>
                        <option value="100" <?php selected($per_page, 100); ?>>100</option>
                        <option value="200" <?php selected($per_page, 200); ?>>200</option>
                    </select>
                </div>
            <?php endif; ?>
        </div>
        <?php
        return ob_get_clean();
    }
}

// phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL, WordPress.DB.PreparedSQLPlaceholders, PluginCheck.Security.DirectDB
