<?php
/**
 * Admin Class
 *
 * @package InsightPress
 */

if (!defined('ABSPATH')) {
    exit;
}

class InsightPress_Admin
{

    /**
     * Constructor.
     */
    public function __construct()
    {
        add_action('admin_menu', array($this, 'add_menu_page'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_styles'));

        // Add columns to WC Product List
        add_filter('manage_edit-product_columns', array($this, 'add_analytics_column'));
        add_action('manage_product_posts_custom_column', array($this, 'render_analytics_column'), 10, 2);

        // Usage tracking notice on dashboard
        add_action('admin_notices', array($this, 'render_tracking_notice'));
    }

    /**
     * Add Analytics column to product list.
     */
    public function add_analytics_column($columns)
    {
        $new_columns = array();
        foreach ($columns as $key => $column) {
            $new_columns[$key] = $column;
            if ($key === 'name') {
                $new_columns['ip_analytics_action'] = __('Engagement', 'insightpress-advanced-analytics-for-woocommerce');
            }
        }
        return $new_columns;
    }

    /**
     * Render Analytics column content.
     */
    public function render_analytics_column($column, $post_id)
    {
        if ($column !== 'ip_analytics_action')
            return;

        global $wpdb;

        // Detect HPOS (WooCommerce High-Performance Order Storage)
        $use_hpos = class_exists('Automattic\WooCommerce\Utilities\OrderUtil')
            && \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled();

        $statuses = array('wc-completed', 'wc-processing', 'wc-on-hold');
        $placeholders = implode(',', array_fill(0, count($statuses), '%s'));

        if ($use_hpos) {
            // HPOS: orders are in wc_orders table
            $query = $wpdb->prepare(
                "SELECT
                    COUNT(DISTINCT oi.order_id)                        AS total_orders,
                    SUM(CAST(oim_line.meta_value AS DECIMAL(10,2)))    AS total_revenue
                FROM {$wpdb->prefix}woocommerce_order_items AS oi
                INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS oim_product
                    ON oi.order_item_id = oim_product.order_item_id
                    AND oim_product.meta_key IN ('_product_id','_variation_id')
                    AND oim_product.meta_value = %d
                LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS oim_line
                    ON oi.order_item_id = oim_line.order_item_id
                    AND oim_line.meta_key = '_line_total'
                INNER JOIN {$wpdb->prefix}wc_orders AS o
                    ON o.id = oi.order_id
                    AND o.status IN ($placeholders)
                WHERE oi.order_item_type = 'line_item'",
                array_merge(array($post_id), $statuses)
            );
        } else {
            // Legacy: orders are in wp_posts
            $query = $wpdb->prepare(
                "SELECT
                    COUNT(DISTINCT oi.order_id)                        AS total_orders,
                    SUM(CAST(oim_line.meta_value AS DECIMAL(10,2)))    AS total_revenue
                FROM {$wpdb->prefix}woocommerce_order_items AS oi
                INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS oim_product
                    ON oi.order_item_id = oim_product.order_item_id
                    AND oim_product.meta_key IN ('_product_id','_variation_id')
                    AND oim_product.meta_value = %d
                LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS oim_line
                    ON oi.order_item_id = oim_line.order_item_id
                    AND oim_line.meta_key = '_line_total'
                INNER JOIN {$wpdb->prefix}posts AS p
                    ON p.ID = oi.order_id
                    AND p.post_type   = 'shop_order'
                    AND p.post_status IN ($placeholders)
                WHERE oi.order_item_type = 'line_item'",
                array_merge(array($post_id), $statuses)
            );
        }

        $row = $wpdb->get_row($query);


        // Fetch total product views from InsightPress tracker table
        $tracker_table = InsightPress_Product_Tracker::get_table_name();
        $views = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $tracker_table WHERE product_id = %d AND event_type = 'view'",
            $post_id
        ));

        $total_orders = $row ? intval($row->total_orders) : 0;
        $total_revenue = $row ? floatval($row->total_revenue) : 0.0;
        $symbol = get_woocommerce_currency_symbol();

        $is_pro = function_exists('insightpress_pro_fs') && insightpress_pro_fs()->can_use_premium_code__premium_only();

        $stats = array(
            array('dashicons-visibility', '#7c3aed', __('Total Views', 'insightpress-advanced-analytics-for-woocommerce'), number_format($views)),
            array('dashicons-cart', '#1d4ed8', __('Total Orders', 'insightpress-advanced-analytics-for-woocommerce'), number_format($total_orders)),
            array('dashicons-money-alt', '#15803d', __('Total Revenue', 'insightpress-advanced-analytics-for-woocommerce'), $symbol . number_format($total_revenue, 2)),
        );

        $blur_style = !$is_pro ? 'filter:blur(3px);user-select:none;pointer-events:none;opacity:0.7;' : '';

        echo '<div style="margin-bottom:10px;position:relative;">';

        if (!$is_pro) {
            echo '<div style="position:absolute;top:0;left:0;width:100%;height:100%;display:flex;align-items:center;justify-content:center;z-index:10;color:#7c3aed;font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:1px;pointer-events:none;">';
            echo '<span class="dashicons dashicons-lock" style="font-size:12px;width:12px;height:12px;margin-right:4px;"></span> PRO';
            echo '</div>';
        }

        echo '<div style="' . $blur_style . '">';
        foreach ($stats as $stat) {
            list($icon, $color, $label, $value) = $stat;
            echo '<div style="display:flex;align-items:center;justify-content:space-between;gap:8px;padding:2px 0;">';
            echo '<span style="display:inline-flex;align-items:center;gap:5px;font-size:12px;font-weight:500;color:#6b7280;">';
            echo '<span class="dashicons ' . esc_attr($icon) . '" style="font-size:13px;width:13px;height:13px;color:' . esc_attr($color) . ';"></span>';
            echo esc_html($label) . ':';
            echo '</span>';
            echo '<span style="font-size:12px;font-weight:700;color:#111827;">' . esc_html($value) . '</span>';
            echo '</div>';
        }
        echo '</div>'; // End blur wrapper
        echo '</div>'; // End relative wrapper

        // View Analytics button - FREE
        $url = admin_url('admin.php?page=insightpress-product#/product/' . $post_id);
        echo '<a href="' . esc_url($url) . '" class="insightpress-analytics-button">';
        echo '<span class="dashicons dashicons-chart-area"></span> ' . __('View Analytics', 'insightpress-advanced-analytics-for-woocommerce');
        echo '</a>';

    }

    /**
     * Add menu page.
     */
    public function add_menu_page()
    {
        // Add top-level menu
        add_menu_page(
            __('InsightPress Analytics', 'insightpress-advanced-analytics-for-woocommerce'),
            __('InsightPress', 'insightpress-advanced-analytics-for-woocommerce'),
            'manage_woocommerce',
            'insightpress',
            array($this, 'display_dashboard_page'),
            'dashicons-chart-area',
            56
        );

        // Add submenus
        add_submenu_page(
            'insightpress',
            __('Sales & Revenue Analytics', 'insightpress-advanced-analytics-for-woocommerce'),
            __('Sales & Revenue', 'insightpress-advanced-analytics-for-woocommerce'),
            'manage_woocommerce',
            'insightpress', // Use parent slug to make it the default page
            array($this, 'display_dashboard_page')
        );

        add_submenu_page(
            'insightpress',
            __('Product & Inventory Analytics', 'insightpress-advanced-analytics-for-woocommerce'),
            __('Product & Inventory', 'insightpress-advanced-analytics-for-woocommerce'),
            'manage_woocommerce',
            'insightpress-product',
            array($this, 'display_dashboard_page')
        );

        add_submenu_page(
            'insightpress',
            __('Blog Post Engagement Analytics', 'insightpress-advanced-analytics-for-woocommerce'),
            __('Post Analytics', 'insightpress-advanced-analytics-for-woocommerce'),
            'manage_woocommerce',
            'insightpress-posts',
            array($this, 'display_dashboard_page')
        );

        add_submenu_page(
            'insightpress',
            __('Conversion & Traffic Attribution', 'insightpress-advanced-analytics-for-woocommerce'),
            __('Traffic Attribution', 'insightpress-advanced-analytics-for-woocommerce'),
            'manage_woocommerce',
            'insightpress-traffic',
            array($this, 'display_dashboard_page')
        );

    }

    /**
     * Redirect to Pro site.
     */
    public function redirect_to_pro_site()
    {
        echo '<script>window.open("https://dominopress.com/insightpress-pro", "_blank"); window.location.href="' . admin_url('admin.php?page=insightpress') . '";</script>';
    }

    /**
     * Enqueue styles and scripts.
     */
    public function enqueue_styles($hook)
    {
        $allowed_hooks = [
            'index.php',
            'dashboard',
            'toplevel_page_insightpress',
            'insightpress_page_insightpress-sales',
            'insightpress_page_insightpress-product',
            'insightpress_page_insightpress-posts',
            'insightpress_page_insightpress-traffic',
            'insightpress_page_insightpress-post-detail',
            'settings_page_insightpress-post-detail',
            'posts_page_insightpress-post-detail',
        ];

        $is_product_list = ($hook === 'edit.php' && isset($_GET['post_type']) && $_GET['post_type'] === 'product');
        $is_post_list = ($hook === 'edit.php' && (!isset($_GET['post_type']) || $_GET['post_type'] === 'post'));

        if (!in_array($hook, $allowed_hooks) && !$is_product_list && !$is_post_list) {
            return;
        }

        $script_path = INSIGHTPRESS_ADVANCED_ANALYTICS_FOR_WOOCOMMERCE_PATH . 'assets/admin.js';
        $script_url = INSIGHTPRESS_ADVANCED_ANALYTICS_FOR_WOOCOMMERCE_URL . 'assets/admin.js';
        $vendors_path = INSIGHTPRESS_ADVANCED_ANALYTICS_FOR_WOOCOMMERCE_PATH . 'assets/vendors.js';
        $vendors_url = INSIGHTPRESS_ADVANCED_ANALYTICS_FOR_WOOCOMMERCE_URL . 'assets/vendors.js';

        if (file_exists($vendors_path)) {
            wp_enqueue_script(
                'insightpress-vendors',
                $vendors_url,
                [],
                filemtime($vendors_path),
                true
            );
        }

        if (file_exists($script_path)) {
            wp_enqueue_script(
                'insightpress-admin',
                $script_url,
                ['insightpress-vendors', 'wp-element'],
                filemtime($script_path),
                true
            );

            $currentPage = 'dashboard';
            $productId = isset($_GET['product_id']) ? (int) $_GET['product_id'] : 0;
            $postId = isset($_GET['post_id']) ? (int) $_GET['post_id'] : 0;

            if ($hook === 'toplevel_page_insightpress') {
                $currentPage = 'sales-analytics';
            } elseif ($hook === 'insightpress_page_insightpress-product') {
                $currentPage = $productId > 0 ? 'single-product-analytics' : 'product-analytics';
            } elseif ($hook === 'insightpress_page_insightpress-posts') {
                $currentPage = 'post-analytics';
            } elseif ($hook === 'insightpress_page_insightpress-traffic') {
                $currentPage = 'traffic-analytics';
            } elseif (strpos($hook, 'insightpress-post-detail') !== false) {
                $currentPage = 'single-post-analytics';
            }

            $current_user = wp_get_current_user();
            wp_localize_script('insightpress-admin', 'insightPressData', [
                'rootUrl' => home_url(),
                'apiUrl' => rest_url('insightpress/v1/'),
                'nonce' => wp_create_nonce('wp_rest'),
                'currentPage' => $currentPage,
                'productId' => $productId,
                'postId' => $postId,
                'isPro' => insightpress_is_pro(),
                'userName' => $current_user->user_firstname ? $current_user->user_firstname . ' ' . $current_user->user_lastname : $current_user->display_name,
                'userEmail' => $current_user->user_email,
                'siteUrl' => get_site_url()
            ]);
        }

        wp_enqueue_style('insightpress-admin', INSIGHTPRESS_ADVANCED_ANALYTICS_FOR_WOOCOMMERCE_URL . 'assets/css/admin.css', array(), time());
    }

    /**
     * Display dashboard page.
     */
    public function display_dashboard_page()
    {
        echo '<div id="insightpress-root"></div>';
    }

    /**
     * Render tracking notice container.
     */
    public function render_tracking_notice()
    {
        $screen = get_current_screen();
        if ($screen->id !== 'dashboard') {
            return;
        }

        if (class_exists('InsightPress_Settings_API') && InsightPress_Settings_API::is_feature_enabled('usage_tracking')) {
            return;
        }

        $settings = InsightPress_Settings_API::get_feature_settings();
        if ($settings['usage_tracking'] !== 'pending') {
            return;
        }

        echo '<div id="insightpress-tracking-notice" style="margin: 20px 20px 0 0;"></div>';
    }
}
