<?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/admin/insights/insights-helpers.php';
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/admin/insights/insights-filters.php';
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/admin/insights/insights-query-builder.php';
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/admin/insights/snapshot-service.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;

    /**
     * Snapshot orchestrator service.
     *
     * @var LinkCentral_Insights_Snapshot_Service
     */
    private $snapshot_service;

    /**
     * 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);
        $this->snapshot_service = new LinkCentral_Insights_Snapshot_Service(
            $this->total_clicks,
            $this->most_popular_links,
            $this->recent_clicks,
            ( isset( $this->top_countries ) ? $this->top_countries : null ),
            ( isset( $this->user_agents ) ? $this->user_agents : null ),
            ( isset( $this->top_referrers ) ? $this->top_referrers : null )
        );
    }

    /**
     * Initialize the class and set up WordPress hooks.
     */
    public function init() {
        add_action( 'wp_ajax_linkcentral_get_insights_snapshot', array($this, 'ajax_get_insights_snapshot') );
        // 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
            );
            $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() {
        // Placeholder pagination state — JS overwrites these immediately on AJAX return.
        $initial_top_links_data = array(
            'current_page'   => 1,
            'total_pages'    => 1,
            'total_items'    => 0,
            'items_per_page' => 10,
        );
        $initial_recent_clicks_data = array(
            'current_page'   => 1,
            'total_pages'    => 1,
            'total_items'    => 0,
            'items_per_page' => 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';
    }

    /**
     * Batched Insights data for all dashboard widgets.
     */
    public function ajax_get_insights_snapshot() {
        check_ajax_referer( 'linkcentral_admin_nonce', 'nonce' );
        $filters = LinkCentral_Insights_Filters::from_request( wp_unslash( $_POST ) );
        if ( isset( $_POST['widgets'] ) ) {
            if ( is_array( $_POST['widgets'] ) ) {
                $widgets_raw = array_map( 'sanitize_key', wp_unslash( $_POST['widgets'] ) );
            } else {
                $widgets_raw = sanitize_text_field( wp_unslash( (string) $_POST['widgets'] ) );
            }
        } else {
            $widgets_raw = 'all';
        }
        $widgets = LinkCentral_Insights_Snapshot_Service::parse_requested_widgets( $widgets_raw );
        $pagination = LinkCentral_Insights_Snapshot_Service::parse_pagination( wp_unslash( $_POST ) );
        $snapshot = $this->snapshot_service->build( $filters, $widgets, $pagination );
        wp_send_json_success( $snapshot );
    }

    /**
     * AJAX handler for searching links in the Insights page.
     */
    public function ajax_insights_search_links() {
        check_ajax_referer( 'linkcentral_admin_nonce', 'nonce' );
        wp_send_json_error( array(
            'message' => __( 'This is a Premium feature.', 'linkcentral' ),
        ), 403 );
        $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' );
        wp_send_json_error( array(
            'message' => __( 'This is a Premium feature.', 'linkcentral' ),
        ), 403 );
        $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 );
    }

}
