<?php
/**
 * AuctionForge Site Statistics - Initialization
 * Loads all stats classes, registers hooks, enqueues tracker script.
 */

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

class AF_Stats_Init {

    private static $initialized = false;

    public static function init() {
        if (self::$initialized) return;
        self::$initialized = true;

        $dir = plugin_dir_path(__FILE__);
        require_once $dir . 'class-stats-database.php';
        require_once $dir . 'class-stats-tracker.php';
        require_once $dir . 'class-stats-ajax.php';

        // Register AJAX handlers
        AF_Stats_Ajax::init();

        // Enqueue frontend tracker on non-admin pages
        add_action('wp_enqueue_scripts', array(__CLASS__, 'enqueue_tracker'));

        // Track 404 errors server-side
        add_action('template_redirect', array(__CLASS__, 'track_404'));

        // Admin menu
        if (is_admin()) {
            add_action('admin_menu', array(__CLASS__, 'register_admin_menu'));
        }

        // Auto-create tables if they don't exist (handles updates, not just activation)
        add_action('plugins_loaded', array(__CLASS__, 'maybe_create_tables'), 20);

        // Data retention cron
        add_action('af_stats_daily_purge', array('AF_Stats_Database', 'purge_old_data'));
        if (!wp_next_scheduled('af_stats_daily_purge')) {
            wp_schedule_event(time(), 'daily', 'af_stats_daily_purge');
        }
    }

    /**
     * Enqueue the lightweight tracker JS on the frontend
     */
    public static function enqueue_tracker() {
        if (get_option('af_stats_enabled', 'on') !== 'on') return;

        // Check if should skip (excluded roles, IPs)
        if (AF_Stats_Tracker::should_skip()) return;

        // Check bot
        $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        if (AF_Stats_Tracker::is_bot($ua)) return;

        $plugin_url = plugin_dir_url(dirname(dirname(__FILE__)));
        $version = defined('AUCTIONFORGE_VERSION') ? AUCTIONFORGE_VERSION : '1.0';

        wp_enqueue_script(
            'af-stats-tracker',
            $plugin_url . 'assets/js/af-stats-tracker.js',
            array(),
            $version,
            true
        );

        wp_add_inline_script('af-stats-tracker', 'window.af_stats_config = ' . wp_json_encode(array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('af_stats_nonce'),
        )) . ';', 'before');
    }

    /**
     * Track 404 errors server-side
     */
    public static function track_404() {
        if (!is_404()) return;
        if (get_option('af_stats_enabled', 'on') !== 'on') return;

        $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        if (AF_Stats_Tracker::is_bot($ua)) return;

        $url = (is_ssl() ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        $ip = AF_Stats_Tracker::get_client_ip();
        $ip = AF_Stats_Tracker::maybe_anonymize_ip($ip);

        // We don't have visitor_hash server-side, use IP hash
        $visitor_hash = md5($ip . $ua);

        AF_Stats_Tracker::record_404($url, $referrer, $visitor_hash, $ip);
    }

    /**
     * Register admin menu page
     */
    public static function register_admin_menu() {
        add_submenu_page(
            'edit.php?post_type=lot',
            __('Site Statistics', 'auctionforge'),
            __('Site Statistics', 'auctionforge'),
            'manage_options',
            'auctionforge-stats',
            array(__CLASS__, 'render_admin_page')
        );
    }

    /**
     * Render admin dashboard
     */
    public static function render_admin_page() {
        require_once plugin_dir_path(dirname(dirname(__FILE__))) . 'admin/view/stats/dashboard.php';
    }

    /**
     * Auto-create tables if they don't exist (runs on plugins_loaded)
     */
    public static function maybe_create_tables() {
        if (!is_admin()) return;
        $db_version = get_option('af_stats_db_version', 0);
        if (intval($db_version) < 1) {
            self::activate();
        }
    }

    /**
     * Run on plugin activation - create tables
     */
    public static function activate() {
        $dir = plugin_dir_path(__FILE__);
        require_once $dir . 'class-stats-database.php';
        AF_Stats_Database::create_tables();
    }
}
