<?php
namespace IntentDeep\VirtualFiles\Controllers;

use IntentDeep\VirtualFiles\Traits\AnalyticsHelper;
use IntentDeep\VirtualFiles\Traits\SettingHelper;

class AnalyticsController {
    use AnalyticsHelper;
    use SettingHelper;

    /**
     * Add analytics page to WordPress menu
     */
    public function add_page(): void {
        add_submenu_page(
            'edit.php?post_type=idep_virtual_file',
            __('File Analytics', 'intentdeep-virtual-files'),
            __('File Analytics', 'intentdeep-virtual-files'),
            'manage_options',
            'intentdeep-vf-analytics',
            [$this, 'render_page']
        );
    }

    /**
     * Render the analytics page
     */
    public function render_page(): void {
        // Check if user is Pro
        $is_pro = function_exists('intentdeep_vf_fs') && intentdeep_vf_fs()->can_use_premium_code__premium_only();

        // Prepare data for Pro users
        $data = [];
        if ($is_pro) {
            $data = $this->prepare_analytics_data();
        }

        // Enqueue assets
        $this->enqueue_assets($is_pro);

        // Render the view
        include plugin_dir_path(dirname(__FILE__)) . 'views/analytics.php';
    }

    /**
     * Prepare analytics data for frontend
     */
    private function prepare_analytics_data(): array {
        $summary = $this->getAnalyticsSummary();
        $timeline = $this->getViewsTimeline(30);
        $top_files = $this->getTopFiles(5);
        $file_types = $this->getFileTypeDistribution();
        $hourly_views = $this->getTodayHourlyViews();

        return [
            'summary' => $summary,
            'timeline' => [
                'labels' => array_keys($timeline),
                'data' => array_values($timeline),
            ],
            'topFiles' => $top_files,
            'fileTypes' => [
                'labels' => array_keys($file_types),
                'data' => array_values($file_types),
            ],
            'hourlyViews' => [
                'labels' => array_keys($hourly_views),
                'data' => array_values($hourly_views),
            ],
        ];
    }

    /**
     * Enqueue CSS and JS assets
     */
    private function enqueue_assets(bool $is_pro): void {
        // Enqueue ApexCharts
        wp_enqueue_script(
            'apexcharts',
            plugin_dir_url(dirname(dirname(__FILE__))) . 'vendor/apexcharts.js',
            [],
            '5.3.6',
            true
        );

        // Enqueue analytics CSS
        $css_file = plugin_dir_path(dirname(__FILE__)) . 'assets/css/analytics.css';
        $css_version = file_exists($css_file) ? filemtime($css_file) : time();

        wp_enqueue_style(
            'intentdeep-vf-analytics',
            plugin_dir_url(dirname(__FILE__)) . 'assets/css/analytics.css',
            [],
            $css_version
        );

        // Enqueue analytics JS
        $js_file = plugin_dir_path(dirname(__FILE__)) . 'assets/js/analytics.js';
        $js_version = file_exists($js_file) ? filemtime($js_file) : time();

        wp_enqueue_script(
            'intentdeep-vf-analytics',
            plugin_dir_url(dirname(__FILE__)) . 'assets/js/analytics.js',
            ['jquery', 'apexcharts'],
            $js_version,
            true
        );

        // Localize script with data
        $data = $is_pro ? $this->prepare_analytics_data() : [];

        wp_localize_script('intentdeep-vf-analytics', 'intentdeepVfAnalyticsData', [
            'isPro' => $is_pro,
            'data' => $data,
            'nonce' => wp_create_nonce('intentdeep_vf_analytics'),
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'upgradeUrl' => function_exists('intentdeep_vf_fs')
                ? intentdeep_vf_fs()->get_upgrade_url()
                : admin_url('edit.php?post_type=idep_virtual_file&page=intentdeep_vf_settings-pricing'),
        ]);
    }

    /**
     * AJAX handler for refreshing analytics data
     */
    public function ajax_refresh_analytics(): void {
        check_ajax_referer('vf_analytics', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'intentdeep-virtual-files')]);
        }

        if (!function_exists('intentdeep_vf_fs') || !intentdeep_vf_fs()->can_use_premium_code__premium_only()) {
            wp_send_json_error(['message' => __('Pro feature only', 'intentdeep-virtual-files')]);
        }

        $days = isset($_POST['days']) ? intval($_POST['days']) : 30;
        $days = min(max($days, 7), 90); // Limit between 7 and 90 days

        $timeline = $this->getViewsTimeline($days);
        $top_files = $this->getTopFiles(5, $days);

        wp_send_json_success([
            'timeline' => [
                'labels' => array_keys($timeline),
                'data' => array_values($timeline),
            ],
            'topFiles' => $top_files,
        ]);
    }
}
