<?php
/**
 * Handles URL list functionality for health issues.
 */

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

class Rank_URL_List {

    /**
     * Initialize hooks.
     */
    public static function init() {
        add_action('wp_ajax_rank_get_issue_urls', array(__CLASS__, 'ajax_get_issue_urls'));
    }

    /**
     * AJAX handler for getting URLs from a batch.
     */
    public static function ajax_get_issue_urls() {
        // Verify nonce and permissions
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'rank_ajax_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
            return;
        }

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Permission denied'));
            return;
        }

        // Get and validate batch ID
        $batch_id = isset($_POST['batch_id']) ? sanitize_key($_POST['batch_id']) : '';
        if (empty($batch_id) || strpos($batch_id, 'rank_batch_') !== 0) {
            wp_send_json_error(array('message' => 'Invalid batch ID'));
            return;
        }

        // Get page and per_page parameters
        $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
        $per_page = isset($_POST['per_page']) ? min(200, max(1, intval($_POST['per_page']))) : 200;

        // Get batch data
        $batch_data = get_option($batch_id);
        if (!$batch_data || !isset($batch_data['issues']) || !is_array($batch_data['issues'])) {
            wp_send_json_error(array('message' => 'Batch data not found or invalid'));
            return;
        }

        // Extract URLs from issues
        $urls = array();
        foreach ($batch_data['issues'] as $issue) {
            $page_url = '';
            
            // Extract page URL based on issue structure
            if (isset($issue['page']['path_full'])) {
                $page_url = $issue['page']['path_full'];
            } elseif (isset($issue['page']['url'])) {
                $page_url = $issue['page']['url'];
            } elseif (isset($issue['url'])) {
                $page_url = $issue['url'];
            }
            
            if (!empty($page_url)) {
                $urls[] = array(
                    'url' => $page_url,
                    'rank_id' => isset($issue['rank_id']) ? $issue['rank_id'] : '',
                    'title' => isset($issue['page']['title']) ? $issue['page']['title'] : basename($page_url)
                );
            }
        }

        // Calculate pagination
        $total = count($urls);
        $total_pages = ceil($total / $per_page);
        $offset = ($page - 1) * $per_page;
        $page_urls = array_slice($urls, $offset, $per_page);

        // Send response
        wp_send_json_success(array(
            'urls' => $page_urls,
            'total' => $total,
            'total_pages' => $total_pages,
            'current_page' => $page
        ));
    }
}