<?php
/**
 * LinkCentral Most Popular Links Class
 *
 * This class handles the functionality for retrieving and displaying
 * the most popular (most clicked) links.
 */
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly 

class LinkCentral_Most_Popular_Links {
    /**
     * The main admin object.
     */
    private $admin;

    /**
     * Constructor.
     */
    public function __construct($admin) {
        $this->admin = $admin;
    }

    /**
     * Initialize the class and set up WordPress hooks.
     */
    public function init() {
        // Register AJAX action for getting top links
        add_action('wp_ajax_linkcentral_get_top_links', array($this, 'ajax_get_top_links'));
    }

    /**
     * AJAX handler for retrieving top links.
     */
    public function ajax_get_top_links() {
        // Verify nonce for security
        check_ajax_referer('linkcentral_admin_nonce', 'nonce');

        // Get parameters from the AJAX request
        $timeframe = isset($_POST['timeframe']) ? sanitize_text_field(wp_unslash($_POST['timeframe'])) : '7';
        $start_date = isset($_POST['start_date']) ? sanitize_text_field(wp_unslash($_POST['start_date'])) : null;
        $end_date = isset($_POST['end_date']) ? sanitize_text_field(wp_unslash($_POST['end_date'])) : null;
        $since_start = isset($_POST['since_start']) ? filter_var($_POST['since_start'], FILTER_VALIDATE_BOOLEAN) : false;
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $per_page = 10; // Set the number of items per page
        $link_id = isset($_POST['link_id']) ? intval($_POST['link_id']) : null;
        $category_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : null;
        $is_manual_navigation = isset($_POST['is_manual_navigation']) ? filter_var($_POST['is_manual_navigation'], FILTER_VALIDATE_BOOLEAN) : false;

        // Get top links data
        $data = $this->get_top_links_data($timeframe, $page, $per_page, $start_date, $end_date, $since_start, $link_id, $category_id, $is_manual_navigation);
        wp_send_json_success($data);
    }

    /**
     * Retrieve top links data based on the given parameters.
     */
    public function get_top_links_data($timeframe, $page, $per_page, $start_date = null, $end_date = null, $since_start = false, $link_id = null, $category_id = null, $is_manual_navigation = false) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'linkcentral_stats';

        // Get link IDs that belong to the selected category (for highlighting)
        $category_link_ids = array();
        if ($category_id) {
            $category_link_ids = LinkCentral_Insights_Helpers::get_link_ids_by_category($category_id);
        }

        // Query to get click counts and unique click counts for all links (no filtering)
        $query = "
            SELECT s.link_id, 
                COUNT(*) as total_clicks,
                SUM(s.first_click) as unique_clicks
            FROM {$wpdb->prefix}linkcentral_stats s
            WHERE 1=1";

        $query_params = array();

        // Handle date filtering
        if ($since_start && linkcentral_fs()->can_use_premium_code__premium_only()) {
            // No additional date filtering for since_start
        } elseif ($start_date && $end_date) {
            // Custom date range
            $query .= " AND s.click_date >= %s AND s.click_date < DATE_ADD(%s, INTERVAL 1 DAY)";
            $query_params[] = $start_date;
            $query_params[] = $end_date;
        } elseif ($timeframe !== 'all') {
            // Preset timeframe
            if ($timeframe == '1') {
                $query .= " AND s.click_date >= DATE_SUB(NOW(), INTERVAL 24 HOUR)";
            } else {
                $query .= " AND s.click_date >= DATE_SUB(CURDATE(), INTERVAL %d DAY)";
                $query_params[] = intval($timeframe);
            }
        }

        $query .= " GROUP BY s.link_id ORDER BY total_clicks DESC";

        // Execute the query - use prepare only if there are placeholders
        if (!empty($query_params)) {
            $click_counts = $wpdb->get_results(
                $wpdb->prepare($query, $query_params),
                OBJECT_K
            );
        } else {
            $click_counts = $wpdb->get_results($query, OBJECT_K);
        }

        // If a specific link is requested and this is NOT manual navigation, find the page it belongs to
        // This ensures we navigate to the correct page on initial selection, but allow manual navigation
        if ($link_id && isset($click_counts[$link_id]) && !$is_manual_navigation) {
            $all_link_ids = array_keys($click_counts);
            $link_position = array_search($link_id, $all_link_ids);
            if ($link_position !== false) {
                $calculated_page = floor($link_position / $per_page) + 1;
                // Override page to show the selected link
                $page = $calculated_page;
            }
        }

        // Step 2: Fetch corresponding posts
        $paged_link_ids = array_slice(array_keys($click_counts), ($page - 1) * $per_page, $per_page);

        $args = array(
            'post_type' => 'linkcentral_link',
            'posts_per_page' => -1, // Get all posts
            'post_status' => array('publish', 'draft', 'private', 'trash'),
            'post__in' => $paged_link_ids,
            'orderby' => 'post__in', // Maintain the order from click counts
        );

        $query = new WP_Query($args);

        // Process the results
        $processed_results = array();
        $all_link_ids = array_keys($click_counts);
        foreach ($paged_link_ids as $current_link_id) {
            $post = $this->find_post_by_id($query->posts, $current_link_id);
            
            // Calculate global rank (position in the entire dataset)
            $global_rank = array_search($current_link_id, $all_link_ids) + 1;
            
            if ($post) {
                $dynamic_rules = get_post_meta($post->ID, '_linkcentral_dynamic_rules', true);
                $is_premium = linkcentral_fs()->can_use_premium_code__premium_only();
                
                // Check if this link belongs to the selected category
                $is_in_selected_category = in_array($post->ID, $category_link_ids);

                $processed_results[] = (object) array(
                    'ID' => $post->ID,
                    'post_title' => $post->post_title,
                    'post_status' => $post->post_status,
                    'slug' => $post->post_name,
                    'total_clicks' => isset($click_counts[$post->ID]) ? $click_counts[$post->ID]->total_clicks : 0,
                    'unique_clicks' => isset($click_counts[$post->ID]) ? $click_counts[$post->ID]->unique_clicks : 0,
                    'destination_url' => get_post_meta($post->ID, '_linkcentral_destination_url', true),
                    'destination_url_truncated' => linkcentral_truncate_url(get_post_meta($post->ID, '_linkcentral_destination_url', true)),
                    'is_deleted' => false,
                    'is_trashed' => ($post->post_status === 'trash'),
                    'is_draft' => ($post->post_status === 'draft'),
                    'is_private' => ($post->post_status === 'private'),
                    'edit_link' => get_edit_post_link($post->ID),
                    'has_dynamic_rules' => $is_premium && !empty($dynamic_rules),
                    'rank' => $global_rank,
                    'is_in_selected_category' => $is_in_selected_category
                );
            } else {
                // Handle deleted posts
                $processed_results[] = (object) array(
                    'ID' => $current_link_id,
                    'post_title' => 'Deleted Link',
                    'post_status' => 'deleted',
                    'slug' => '',
                    'total_clicks' => isset($click_counts[$current_link_id]) ? $click_counts[$current_link_id]->total_clicks : 0,
                    'unique_clicks' => isset($click_counts[$current_link_id]) ? $click_counts[$current_link_id]->unique_clicks : 0,
                    'destination_url' => '',
                    'destination_url_truncated' => linkcentral_truncate_url(''),
                    'is_deleted' => true,
                    'is_trashed' => false,
                    'is_draft' => false,
                    'is_private' => false,
                    'edit_link' => '',
                    'rank' => $global_rank,
                    'is_in_selected_category' => false
                );
            }
        }

        // Calculate pagination info
        $total_items = count($click_counts);
        $total_pages = ceil($total_items / $per_page);

        return array(
            'links' => $processed_results,
            'current_page' => $page,
            'total_pages' => $total_pages,
            'total_items' => $total_items,
            'items_per_page' => $per_page,
            'selected_link_id' => $link_id,
            'selected_category_id' => $category_id
        );
    }



    /**
     * Find a post by ID in an array of posts.
     */
    private function find_post_by_id($posts, $id) {
        foreach ($posts as $post) {
            if ($post->ID == $id) {
                return $post;
            }
        }
        return null;
    }
}
