<?php

namespace WPD_Platform\Services;

use WPD_Platform\Singleton;

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

/**
 * ActivityTrackerService class
 *
 * Captures WordPress admin actions and dispatches them as browser CustomEvents
 * for the Dollie Chrome extension to consume.
 *
 * @package WPD_Platform\Services
 */
class ActivityTrackerService extends Singleton
{
    /**
     * Queued events to dispatch via inline script at admin_footer.
     *
     * @var array
     */
    private $queuedEvents = [];

    /**
     * Options worth tracking changes for.
     *
     * @var array
     */
    private $trackedOptions = [
        'blogname',
        'blogdescription',
        'siteurl',
        'home',
        'admin_email',
        'permalink_structure',
        'default_role',
        'timezone_string',
        'WPLANG',
    ];

    protected function __construct()
    {
        if (!is_admin() || !is_user_logged_in()) {
            return;
        }

        $this->setupHooks();
    }

    /**
     * Register all WordPress hooks.
     */
    private function setupHooks()
    {
        // Plugin lifecycle
        add_action('activated_plugin', [$this, 'hooksActivatedPlugin']);
        add_action('deactivated_plugin', [$this, 'hooksDeactivatedPlugin']);
        add_action('deleted_plugin', [$this, 'hooksDeletedPlugin']);

        // Plugin/theme updates
        add_action('upgrader_process_complete', [$this, 'hooksUpgraderComplete'], 10, 2);

        // Theme switch
        add_action('after_switch_theme', [$this, 'hooksThemeSwitch'], 10, 2);

        // Content lifecycle
        add_action('save_post', [$this, 'hooksSavePost'], 10, 3);
        add_action('wp_trash_post', [$this, 'hooksTrashedPost']);
        add_action('before_delete_post', [$this, 'hooksDeletePost']);

        // User events
        add_action('user_register', [$this, 'hooksUserRegister']);
        add_action('wp_login', [$this, 'hooksUserLogin'], 10, 2);

        // Option changes
        add_action('updated_option', [$this, 'hooksUpdatedOption'], 10, 3);

        // Enqueue JS tracker
        add_action('admin_enqueue_scripts', [$this, 'enqueueScripts']);

        // Inject queued events at footer
        add_action('admin_footer', [$this, 'renderQueuedEvents'], 99);
    }

    /**
     * Queue an event for dispatch.
     *
     * @param string $type     Event type identifier.
     * @param string $category Event category.
     * @param string $label    Human-readable description.
     * @param array  $meta     Additional metadata.
     */
    private function queueEvent($type, $category, $label, $meta = [])
    {
        $this->queuedEvents[] = [
            'type'      => $type,
            'category'  => $category,
            'label'     => $label,
            'url'       => $this->getCurrentAdminUrl(),
            'adminPage' => $this->getCurrentAdminPage(),
            'meta'      => $meta,
            'timestamp' => round(microtime(true) * 1000),
        ];
    }

    /**
     * Get the current admin URL.
     *
     * @return string
     */
    private function getCurrentAdminUrl()
    {
        $protocol = is_ssl() ? 'https' : 'http';
        return $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    }

    /**
     * Get the current admin page filename.
     *
     * @return string
     */
    private function getCurrentAdminPage()
    {
        global $pagenow;
        return $pagenow ?: '';
    }

    // -------------------------------------------------------------------------
    // Hook handlers
    // -------------------------------------------------------------------------

    public function hooksActivatedPlugin($pluginFile)
    {
        $pluginPath = WP_PLUGIN_DIR . '/' . $pluginFile;
        $data = get_plugin_data($pluginPath, true, false);
        $name = !empty($data['Name']) ? $data['Name'] : dirname($pluginFile);

        $this->queueEvent('plugin.activated', 'admin_action', "Activated plugin: {$name}", [
            'plugin' => $pluginFile,
            'name'   => $name,
        ]);
    }

    public function hooksDeactivatedPlugin($pluginFile)
    {
        $pluginPath = WP_PLUGIN_DIR . '/' . $pluginFile;
        $data = get_plugin_data($pluginPath, true, false);
        $name = !empty($data['Name']) ? $data['Name'] : dirname($pluginFile);

        $this->queueEvent('plugin.deactivated', 'admin_action', "Deactivated plugin: {$name}", [
            'plugin' => $pluginFile,
            'name'   => $name,
        ]);
    }

    public function hooksDeletedPlugin($pluginFile)
    {
        $slug = dirname($pluginFile);

        $this->queueEvent('plugin.deleted', 'admin_action', "Deleted plugin: {$slug}", [
            'plugin' => $pluginFile,
            'slug'   => $slug,
        ]);
    }

    public function hooksUpgraderComplete($upgrader, $extra)
    {
        if (!isset($extra['type'])) {
            return;
        }

        if ($extra['type'] === 'plugin' && $extra['action'] === 'update') {
            $plugins = isset($extra['plugins']) ? $extra['plugins'] : [];
            if (isset($extra['plugin'])) {
                $plugins = [$extra['plugin']];
            }

            foreach ($plugins as $pluginFile) {
                $data = get_plugin_data(WP_PLUGIN_DIR . '/' . $pluginFile, true, false);
                $name = !empty($data['Name']) ? $data['Name'] : dirname($pluginFile);
                $version = !empty($data['Version']) ? $data['Version'] : '';

                $this->queueEvent('plugin.updated', 'system', "Updated plugin: {$name} to v{$version}", [
                    'plugin'  => $pluginFile,
                    'name'    => $name,
                    'version' => $version,
                ]);
            }
        }

        if ($extra['type'] === 'theme' && $extra['action'] === 'update') {
            $themes = isset($extra['themes']) ? $extra['themes'] : [];
            if (isset($extra['theme'])) {
                $themes = [$extra['theme']];
            }

            foreach ($themes as $themeSlug) {
                $theme = wp_get_theme($themeSlug);
                $name = $theme->exists() ? $theme->get('Name') : $themeSlug;
                $version = $theme->exists() ? $theme->get('Version') : '';

                $this->queueEvent('theme.updated', 'system', "Updated theme: {$name} to v{$version}", [
                    'theme'   => $themeSlug,
                    'name'    => $name,
                    'version' => $version,
                ]);
            }
        }
    }

    public function hooksThemeSwitch($newName, $newTheme)
    {
        $this->queueEvent('theme.switched', 'admin_action', "Switched theme to: {$newName}", [
            'theme' => $newTheme instanceof \WP_Theme ? $newTheme->get_stylesheet() : $newName,
            'name'  => $newName,
        ]);
    }

    public function hooksSavePost($postId, $post, $update)
    {
        // Skip autosaves, revisions, and auto-drafts
        if (
            defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ||
            wp_is_post_revision($postId) ||
            $post->post_status === 'auto-draft'
        ) {
            return;
        }

        $action = $update ? 'content.updated' : 'content.created';
        $label = $update
            ? "Updated {$post->post_type}: {$post->post_title}"
            : "Created {$post->post_type}: {$post->post_title}";

        $this->queueEvent($action, 'content_edit', $label, [
            'post_id'   => $postId,
            'post_type' => $post->post_type,
            'title'     => $post->post_title,
            'status'    => $post->post_status,
        ]);
    }

    public function hooksTrashedPost($postId)
    {
        $post = get_post($postId);
        if (!$post) {
            return;
        }

        $this->queueEvent('content.trashed', 'content_edit', "Trashed {$post->post_type}: {$post->post_title}", [
            'post_id'   => $postId,
            'post_type' => $post->post_type,
            'title'     => $post->post_title,
        ]);
    }

    public function hooksDeletePost($postId)
    {
        $post = get_post($postId);
        if (!$post || wp_is_post_revision($postId)) {
            return;
        }

        $this->queueEvent('content.deleted', 'content_edit', "Deleted {$post->post_type}: {$post->post_title}", [
            'post_id'   => $postId,
            'post_type' => $post->post_type,
            'title'     => $post->post_title,
        ]);
    }

    public function hooksUserRegister($userId)
    {
        $user = get_user_by('id', $userId);
        if (!$user) {
            return;
        }

        $this->queueEvent('user.registered', 'admin_action', "New user registered: {$user->user_login}", [
            'user_id' => $userId,
            'login'   => $user->user_login,
            'role'    => implode(', ', $user->roles),
        ]);
    }

    public function hooksUserLogin($userLogin, $user)
    {
        $this->queueEvent('user.login', 'system', "User logged in: {$userLogin}", [
            'user_id' => $user->ID,
            'login'   => $userLogin,
        ]);
    }

    public function hooksUpdatedOption($option, $oldValue, $newValue)
    {
        if (!in_array($option, $this->trackedOptions, true)) {
            return;
        }

        $this->queueEvent('option.updated', 'admin_action', "Updated option: {$option}", [
            'option'    => $option,
            'old_value' => is_scalar($oldValue) ? $oldValue : '(complex)',
            'new_value' => is_scalar($newValue) ? $newValue : '(complex)',
        ]);
    }

    // -------------------------------------------------------------------------
    // Script enqueuing & event dispatch
    // -------------------------------------------------------------------------

    /**
     * Enqueue the client-side activity tracker.
     */
    public function enqueueScripts()
    {
        wp_enqueue_script(
            'dollie-activity-tracker',
            PLATFORM_PLUGIN_URL . 'assets/js/activity-tracker.js',
            [],
            PLATFORM_VERSION,
            true
        );

        wp_localize_script('dollie-activity-tracker', 'dollieActivityConfig', [
            'adminUrl'  => admin_url(),
            'restUrl'   => rest_url(),
            'ajaxUrl'   => admin_url('admin-ajax.php'),
            'pagenow'   => $this->getCurrentAdminPage(),
        ]);
    }

    /**
     * Render queued PHP-captured events as inline script at admin_footer.
     */
    public function renderQueuedEvents()
    {
        if (empty($this->queuedEvents)) {
            return;
        }

        $events = wp_json_encode($this->queuedEvents);
        ?>
        <script>
        (function() {
            var events = <?php echo $events; ?>;
            for (var i = 0; i < events.length; i++) {
                window.postMessage({ source: 'dollie-activity', payload: events[i] }, '*');
            }
        })();
        </script>
        <?php
    }
}
