<?php
/**
 * TrackSharp Admin
 * 
 * Handles admin menu registration, asset enqueuing, and notices.
 *
 * @package TrackSharp
 */

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

class TrackSharp_Admin
{
    /** @var TrackSharp_Events_Log */
    private $events_log;

    /** @var TrackSharp_Settings */
    private $settings;

    /** @var TrackSharp_Wizard */
    private $wizard;

    /** @var TrackSharp_Dashboard */
    private $dashboard;

    /** @var TrackSharp_Events_Page */
    private $events_page;

    /**
     * Constructor.
     *
     * @param TrackSharp_Events_Log  $events_log  Events logger.
     * @param TrackSharp_Settings    $settings    Settings page handler.
     * @param TrackSharp_Wizard      $wizard      Wizard page handler.
     * @param TrackSharp_Dashboard   $dashboard   Dashboard page handler.
     * @param TrackSharp_Events_Page $events_page Events page handler.
     */
    public function __construct(
        TrackSharp_Events_Log $events_log,
        TrackSharp_Settings $settings,
        TrackSharp_Wizard $wizard,
        TrackSharp_Dashboard $dashboard,
        TrackSharp_Events_Page $events_page
    ) {
        $this->events_log = $events_log;
        $this->settings = $settings;
        $this->wizard = $wizard;
        $this->dashboard = $dashboard;
        $this->events_page = $events_page;
    }

    /**
     * Register admin hooks.
     *
     * @return void
     */
    public function register_hooks()
    {
        add_action('admin_menu', [$this, 'add_menu'], 9);
        add_action('admin_menu', [$this, 'add_wizard_menu'], 10);
        add_action('admin_init', [$this, 'maybe_redirect_to_wizard']);
        add_action('admin_init', [$this->settings, 'register_settings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
        add_action('admin_notices', [$this, 'maybe_notice_missing_consent_api']);
        add_action('admin_notices', [$this, 'maybe_notice_trial_expired']);
        add_action('admin_notices', [$this, 'render_notice_spacer'], 1000);
        add_action('add_meta_boxes', [$this, 'add_order_meta_box']);
        add_filter('plugin_action_links_' . TRACKSHARP_PLUGIN_BASENAME, [$this, 'plugin_row_links']);
    }

    /**
     * Add admin menu pages.
     *
     * @return void
     */
    public function add_menu()
    {
        add_menu_page(
            'TrackSharp-audit',
            'TrackSharp',
            'manage_options',
            'tracksharp-audit',
            [$this->dashboard, 'render'],
            'dashicons-chart-line',
            58
        );

        add_submenu_page(
            'tracksharp-audit',
            'Dashboard',
            __('Dashboard', 'tracksharp'),
            'manage_options',
            'tracksharp-audit',
            [$this->dashboard, 'render']
        );

        add_submenu_page(
            'tracksharp-audit',
            'TrackSharp-events',
            __('Events (log)', 'tracksharp'),
            'manage_options',
            'tracksharp-events',
            [$this->events_page, 'render']
        );

        add_submenu_page(
            'tracksharp-audit',
            __('Settings', 'tracksharp'),
            __('Settings', 'tracksharp'),
            'manage_options',
            'tracksharp-settings',
            [$this->settings, 'render']
        );
    }

    /**
     * Add wizard submenu.
     *
     * @return void
     */
    public function add_wizard_menu()
    {
        add_submenu_page(
            'tracksharp-audit',
            __('Setup Wizard', 'tracksharp'),
            __('Setup Wizard', 'tracksharp'),
            'manage_options',
            'tracksharp-setup',
            [$this->wizard, 'render']
        );
    }

    /**
     * Enqueue admin assets.
     *
     * @param string $hook Current admin page hook.
     * @return void
     */
    public function enqueue_assets($hook)
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only access to current admin page slug for conditional enqueues.
        $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
        $allowed_pages = [
            'tracksharp-audit',
            'tracksharp-events',
            'tracksharp-settings',
            'tracksharp-setup',
            'tracksharp-audit-pricing',
            'tracksharp-audit-account',
        ];

        if (!in_array($page, $allowed_pages, true) && $hook !== 'settings_page_tracksharp-tracker') {
            return;
        }

        // Enqueue CSS
        wp_enqueue_style(
            'tracksharp-admin',
            TRACKSHARP_PLUGIN_URL . 'assets/css/tracksharp-admin.css',
            [],
            TRACKSHARP_VERSION
        );

        if ($page === 'tracksharp-audit-pricing' || $page === 'tracksharp-audit-account') {
            wp_enqueue_style(
                'tracksharp-freemius-pricing',
                TRACKSHARP_PLUGIN_URL . 'assets/freemius-pricing/freemius-pricing.css',
                [],
                TRACKSHARP_VERSION
            );
        }

        if ($page === 'tracksharp-audit-pricing' || $page === 'tracksharp-audit-account') {
            wp_enqueue_script(
                'tracksharp-freemius-pricing',
                TRACKSHARP_PLUGIN_URL . 'assets/freemius-pricing/freemius-pricing.js',
                [],
                TRACKSHARP_VERSION,
                true
            );

            $is_trial = function_exists('tracksharp_fs') && is_object(tracksharp_fs())
                && method_exists(tracksharp_fs(), 'is_trial') && tracksharp_fs()->is_trial();

            $currency = (function_exists('tracksharp_is_dutch_locale') && tracksharp_is_dutch_locale()) ? 'eur' : 'usd';

            wp_localize_script('tracksharp-freemius-pricing', 'TRACKSHARP_PRICING', [
                'is_trial' => (bool) $is_trial,
                'currency' => $currency,
            ]);
        }

        // Enqueue JS
        wp_enqueue_script(
            'tracksharp-admin',
            TRACKSHARP_PLUGIN_URL . 'assets/js/tracksharp-admin.js',
            ['jquery'],
            TRACKSHARP_VERSION,
            true
        );
    }

    /**
     * Maybe redirect to wizard after activation.
     *
     * @return void
     */
    public function maybe_redirect_to_wizard()
    {
        if (!get_option('ws_do_activation_redirect')) {
            return;
        }

        delete_option('ws_do_activation_redirect');

        if (wp_doing_ajax()) {
            return;
        }
        if (!current_user_can('manage_options')) {
            return;
        }

        wp_safe_redirect(admin_url('admin.php?page=tracksharp-setup'));
        exit;
    }

    /**
     * Show notice if WP Consent API is missing.
     *
     * @return void
     */
    public function maybe_notice_missing_consent_api()
    {
        if (!current_user_can('manage_options')) {
            return;
        }
        if (function_exists('wp_has_consent')) {
            return;
        }

        // Only show this notice on TrackSharp admin pages to avoid spamming all of wp-admin.
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only access to current admin page slug for conditional UI.
        $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
        if (!in_array($page, ['tracksharp-setup', 'tracksharp-audit', 'tracksharp-events', 'tracksharp-settings'], true)) {
            return;
        }

        $fallback = (string) get_option('tracksharp_consent_fallback', 'grant_immediately');
        $fallback_is_deny = ($fallback === 'deny');

        $install_url = admin_url('plugin-install.php?s=WP%20Consent%20API&tab=search&type=term');
        $settings_url = admin_url('admin.php?page=tracksharp-settings');

        $notice_class = $fallback_is_deny ? 'notice notice-error is-dismissible' : 'notice notice-warning is-dismissible';
        $message = $fallback_is_deny
            ? esc_html__(
                'the WP Consent API is not active. Your current fallback is set to deny, so TrackSharp will not send events until consent can be determined. Install the WP Consent API plugin with a compatible CMP (e.g. Complianz) or adjust your fallback in TrackSharp -> Settings.',
                'tracksharp'
            )
            : esc_html__(
                'the WP Consent API is not active. TrackSharp will use your configured fallback to decide whether events can be sent. For stricter compliance: install the WP Consent API plugin with a compatible CMP (e.g. Complianz) or adjust your fallback in TrackSharp -> Settings.',
                'tracksharp'
            );

        echo '<div class="' . esc_attr($notice_class) . '">
            <p><strong>TrackSharp:</strong> ' . $message . '</p>
            <p>
                <a class="button button-primary" href="' . esc_url($install_url) . '">' . esc_html__('Install WP Consent API', 'tracksharp') . '</a>
                <a class="button" href="' . esc_url($settings_url) . '">' . esc_html__('Open TrackSharp Settings', 'tracksharp') . '</a>
            </p>
        </div>';
    }

    /**
     * Show notice when trial has expired to guide users toward upgrading.
     *
     * @return void
     */
    public function maybe_notice_trial_expired()
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        // Only show on TrackSharp pages.
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only access to current admin page slug for conditional UI.
        $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
        if (strpos($page, 'tracksharp') !== 0) {
            return;
        }

        if (!function_exists('tracksharp_fs')) {
            return;
        }

        $fs = tracksharp_fs();
        if (!is_object($fs)) {
            return;
        }

        // If Pro is active, no need for the notice.
        if (TrackSharp_Features::is_pro_active()) {
            return;
        }

        // Only show if user had a trial that is no longer active.
        if (!method_exists($fs, 'is_trial_utilized') || !$fs->is_trial_utilized()) {
            return;
        }

        // Don't show if already paying.
        if (method_exists($fs, 'is_paying') && $fs->is_paying()) {
            return;
        }

        $pricing_url = TrackSharp_Features::get_upgrade_url();

        echo '<div class="notice notice-warning is-dismissible">';
        echo '<p><strong>TrackSharp:</strong> ';
        echo esc_html__('Your Pro trial has expired. Pro features (Meta CAPI, Google Ads attribution, Enhanced Conversions) are now disabled. Your GA4 server-side tracking continues to work.', 'tracksharp');
        echo '</p>';
        echo '<p>';
        echo '<a class="button button-primary" href="' . esc_url($pricing_url) . '" style="background:#158a5f;border-color:#127a54;">';
        echo esc_html__('Upgrade to Pro', 'tracksharp');
        echo '</a>';
        echo '</p>';
        echo '</div>';
    }

    /**
     * Render notice spacer.
     *
     * @return void
     */
    public function render_notice_spacer()
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only access to current admin page slug for layout tweak.
        $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
        if (!in_array($page, ['tracksharp-setup', 'tracksharp-audit', 'tracksharp-events', 'tracksharp-settings'], true)) {
            return;
        }

        echo '<div class="tracksharp-notice-spacer" aria-hidden="true"></div>';
    }

    /**
     * Add order meta box.
     *
     * @return void
     */
    public function add_order_meta_box()
    {
        add_meta_box(
            'ws_order_events',
            'TrackSharp-events',
            [$this, 'render_order_events_box'],
            'shop_order',
            'normal',
            'default'
        );
    }

    /**
     * Render order events meta box.
     *
     * @param \WP_Post $post Post object.
     * @return void
     */
    public function render_order_events_box($post)
    {
        global $wpdb;
        $table = esc_sql($wpdb->prefix . TrackSharp_Events_Log::TABLE_NAME);
        $order_id = (int) $post->ID;

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Identifiers cannot be prepared; table name is fixed and escaped.
        $sql = $wpdb->prepare("SELECT ts, channel, source, event_name, ok, http_status, event_id FROM {$table} WHERE txid = %s ORDER BY id DESC LIMIT 50", (string) $order_id);
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query prepared above.
        $rows = $wpdb->get_results($sql, ARRAY_A);

        if (!$rows) {
            echo '<p>' . esc_html__('No TrackSharp entries for this order yet.', 'tracksharp') . '</p>';
            return;
        }

        echo '<table class="widefat striped"><thead><tr>
            <th>' . esc_html__('Time', 'tracksharp') . '</th><th>' . esc_html__('Channel', 'tracksharp') . '</th><th>' . esc_html__('Source', 'tracksharp') . '</th><th>Event</th><th>OK</th><th>HTTP</th><th>Event-ID</th>
        </tr></thead><tbody>';

        foreach ($rows as $r) {
            printf(
                '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td style="max-width:260px;overflow:hidden;text-overflow:ellipsis">%s</td></tr>',
                esc_html($r['ts']),
                esc_html($r['channel']),
                esc_html($r['source']),
                esc_html($r['event_name']),
                $r['ok'] ? '✓' : '✗',
                esc_html($r['http_status']),
                esc_html($r['event_id'])
            );
        }

        echo '</tbody></table>';
    }

    /**
     * Add plugin row links.
     *
     * @param array $links Existing links.
     * @return array Modified links.
     */
    public function plugin_row_links($links)
    {
        if (function_exists('wp_has_consent')) {
            return $links;
        }

        $install_url = admin_url('plugin-install.php?s=WP%20Consent%20API&tab=search&type=term');
        $links[] = '<a href="' . esc_url($install_url) . '" style="color:#b32d2e;font-weight:600">' . esc_html__('Install WP Consent API', 'tracksharp') . '</a>';

        return $links;
    }
}
