<?php

/**
 * LinkCentral Insights Class
 *
 * This class manages the Insights functionality of the plugin,
 * including total clicks, most popular clicks, and recent clicks.
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Exit if accessed directly
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/utils/user-agent-parser.php';
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/utils/insights-helpers.php';
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/admin/insights/total-clicks.php';
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/admin/insights/most-popular-links.php';
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/admin/insights/recent-clicks.php';
class LinkCentral_Insights {
    /**
     * The main admin object.
     */
    private $admin;

    /**
     * The total clicks object.
     */
    private $total_clicks;

    /**
     * The most popular clicks object.
     */
    private $most_popular_links;

    /**
     * The recent clicks object.
     */
    private $recent_clicks;

    /**
     * The top countries object.
     */
    private $top_countries;

    /**
     * The user agents object.
     */
    private $user_agents;

    /**
     * The top referrers object.
     */
    private $top_referrers;

    /**
     * Constructor.
     *
     * @param LinkCentral_Admin $admin The main admin object.
     */
    public function __construct( $admin ) {
        $this->admin = $admin;
        $this->total_clicks = new LinkCentral_Total_Clicks($admin);
        $this->most_popular_links = new LinkCentral_Most_Popular_Links($admin);
        $this->recent_clicks = new LinkCentral_Recent_Clicks($admin);
    }

    /**
     * Initialize the class and set up WordPress hooks.
     */
    public function init() {
        $this->total_clicks->init();
        $this->most_popular_links->init();
        $this->recent_clicks->init();
        // Add AJAX action for link search in Insights
        add_action( 'wp_ajax_linkcentral_insights_search_links', array($this, 'ajax_insights_search_links') );
        // Add AJAX action for category search in Insights
        add_action( 'wp_ajax_linkcentral_insights_search_categories', array($this, 'ajax_insights_search_categories') );
        // Enqueue scripts for insights page
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_insights_scripts') );
    }

    /**
     * Enqueue scripts for the insights page.
     *
     * @param string $hook The current admin page.
     */
    public function enqueue_insights_scripts( $hook ) {
        // Only load insights scripts on the insights page
        if ( $hook === 'linkcentral_page_linkcentral-insights' ) {
            // Enqueue main script
            wp_enqueue_script(
                'linkcentral-admin-insights',
                LINKCENTRAL_PLUGIN_URL . 'assets/js/admin/insights.js',
                array('jquery'),
                LINKCENTRAL_VERSION,
                true
            );
            // Register script translations for insights
            wp_set_script_translations( 'linkcentral-admin-insights', 'linkcentral' );
            // Enqueue vendor chunks
            $vendor_chunks = glob( LINKCENTRAL_PLUGIN_DIR . 'assets/js/vendor.*.js' );
            foreach ( $vendor_chunks as $chunk ) {
                $chunk_name = basename( $chunk, '.js' );
                wp_enqueue_script(
                    "linkcentral-{$chunk_name}",
                    LINKCENTRAL_PLUGIN_URL . "assets/js/{$chunk_name}.js",
                    array(),
                    LINKCENTRAL_VERSION,
                    true
                );
            }
            // Enqueue the vendor CSS that contains Air Datepicker styles
            wp_enqueue_style(
                'linkcentral-vendor-css',
                LINKCENTRAL_PLUGIN_URL . 'assets/css/vendor.common.css',
                array(),
                LINKCENTRAL_VERSION
            );
            // Add localized script data
            $track_unique_visitors = get_option( 'linkcentral_track_unique_visitors', false );
            $localized_data = array(
                'can_use_premium_code__premium_only' => linkcentral_fs()->can_use_premium_code__premium_only(),
                'track_unique_visitors'              => ( $track_unique_visitors ? '1' : '0' ),
                'date_format'                        => $this->convert_to_unicode_date_format( get_option( 'date_format', 'F j, Y' ) ),
                'start_of_week'                      => get_option( 'start_of_week', 0 ),
            );
            wp_localize_script( 'linkcentral-admin-insights', 'linkcentral_insights_data', $localized_data );
        }
    }

    /**
     * Render the insights page.
     */
    public function render_insights_page() {
        // Get initial data for Recent Clicks
        $initial_recent_clicks_data = $this->recent_clicks->get_recent_clicks_data( 1 );
        $initial_top_links_data = $this->most_popular_links->get_top_links_data( '7', 1, 10 );
        // Check if user agent tracking is enabled
        $track_user_agent = get_option( 'linkcentral_track_user_agent', true );
        // Check if unique visitors tracking is enabled
        $track_unique_visitors = get_option( 'linkcentral_track_unique_visitors', false );
        // Check if geolocation tracking is enabled
        $geolocation_service = get_option( 'linkcentral_geolocation_service', false );
        // Pass this data to the template
        include LINKCENTRAL_PLUGIN_DIR . 'views/insights-page.php';
    }

    /**
     * AJAX handler for searching links in the Insights page.
     */
    public function ajax_insights_search_links() {
        check_ajax_referer( 'linkcentral_admin_nonce', 'nonce' );
        $search_term = ( isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '' );
        $links = $this->admin->get_links_for_search( $search_term, array('publish', 'private') );
        wp_send_json_success( $links );
    }

    /**
     * AJAX handler for searching categories in the Insights page.
     */
    public function ajax_insights_search_categories() {
        check_ajax_referer( 'linkcentral_admin_nonce', 'nonce' );
        $search_term = ( isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '' );
        $categories = $this->admin->get_categories_for_search( $search_term );
        wp_send_json_success( $categories );
    }

    /**
     * Convert PHP date format to Unicode Technical Standard #35 format
     * Used for date formatting in the insights date picker which follows UTS #35
     * 
     * @param string $php_format PHP date format
     * @return string UTS #35 date format
     */
    private function convert_to_unicode_date_format( $php_format ) {
        // Default format to return if conversion fails
        $default_format = 'MMMM d, yyyy';
        // Remove escaped characters from PHP date format
        $php_format = preg_replace( '/\\\\[a-zA-Z]/', '', $php_format );
        // Define supported format characters and their UTS #35 equivalents
        $format_map = array(
            'j' => 'd',
            'd' => 'dd',
            'D' => 'E',
            'l' => 'EEEE',
            'F' => 'MMMM',
            'M' => 'MMM',
            'n' => 'M',
            'm' => 'MM',
            'Y' => 'yyyy',
            'y' => 'yy',
        );
        // Allowed separators
        $allowed_separators = array(
            ' ',
            ',',
            '.',
            '/',
            '-'
        );
        // Check if any unsupported characters exist
        for ($i = 0; $i < strlen( $php_format ); $i++) {
            $char = $php_format[$i];
            if ( !isset( $format_map[$char] ) && !in_array( $char, $allowed_separators ) ) {
                return $default_format;
            }
        }
        // Convert the format
        $result = '';
        for ($i = 0; $i < strlen( $php_format ); $i++) {
            $char = $php_format[$i];
            $result .= ( isset( $format_map[$char] ) ? $format_map[$char] : $char );
        }
        return ( empty( trim( $result ) ) ? $default_format : $result );
    }

}
