<?php
/**
 * Tam Rank™ Admin Bar Notifications
 *
 * Toont 404 waarschuwingen in de WordPress admin bar
 * met per-gebruiker tracking (dismissable)
 */

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

class TamRank_Admin_Bar_Notifications {

    /**
     * User meta key voor laatste bekeken timestamp
     */
    const META_LAST_SEEN = 'tam_rank_last_seen_404';

    /**
     * Constructor
     */
    public function __construct() {
        // Admin bar node toevoegen
        add_action('admin_bar_menu', array($this, 'add_admin_bar_node'), 100);

        // CSS + JS voor admin bar (enqueued, niet inline — wp.org compliance)
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_bar_assets'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_admin_bar_assets'));

        // AJAX handlers
        add_action('wp_ajax_tam_rank_mark_404_seen', array($this, 'ajax_mark_404_seen'));

        // Update last seen wanneer 404 Monitor pagina wordt bezocht
        add_action('admin_init', array($this, 'maybe_update_last_seen'));
    }

    /**
     * Voeg node toe aan admin bar
     */
    public function add_admin_bar_node($wp_admin_bar) {
        // Alleen voor admins
        if (!current_user_can('manage_options')) {
            return;
        }

        // Haal nieuwe 404's op
        $new_404_count = $this->get_new_404_count();

        // Altijd de parent node tonen (met of zonder badge)
        if ($new_404_count > 0) {
            $count_text = $new_404_count === 1
                ? sprintf(tamrank__('admin_bar_404_count_one', '%d new 404'), $new_404_count)
                : sprintf(tamrank__('admin_bar_404_count_many', '%d new 404s'), $new_404_count);

            $title = sprintf(
                '<span class="tam-admin-bar-icon">%s</span><span class="tam-admin-bar-text">%s</span>',
                $this->get_warning_icon(),
                esc_html($count_text)
            );

            $wp_admin_bar->add_node(array(
                'id'    => 'tam-rank-404-alert',
                'title' => $title,
                'href'  => admin_url('admin.php?page=tam-rank-404'),
                'meta'  => array(
                    'class' => 'tam-admin-bar-alert tam-has-alerts',
                    'title' => sprintf(tamrank__('admin_bar_404_detected', '%d new 404 errors detected'), $new_404_count),
                ),
            ));

            // Submenu items
            $wp_admin_bar->add_node(array(
                'id'     => 'tam-rank-404-view',
                'parent' => 'tam-rank-404-alert',
                'title'  => tamrank__('admin_bar_404_view', 'View 404 Monitor'),
                'href'   => admin_url('admin.php?page=tam-rank-404'),
            ));

            $wp_admin_bar->add_node(array(
                'id'     => 'tam-rank-404-dismiss',
                'parent' => 'tam-rank-404-alert',
                'title'  => tamrank__('admin_bar_404_dismiss', 'Mark as seen'),
                'href'   => '#',
                'meta'   => array(
                    'class' => 'tam-dismiss-404-alerts',
                ),
            ));
        }
    }

    /**
     * Get warning icon SVG
     */
    private function get_warning_icon() {
        return '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>';
    }

    /**
     * Haal aantal nieuwe 404's op sinds laatste keer bekeken
     */
    public function get_new_404_count() {
        global $wpdb;

        $user_id = get_current_user_id();
        if (!$user_id) {
            return 0;
        }

        // Haal laatste bekeken timestamp op
        $last_seen = get_user_meta($user_id, self::META_LAST_SEEN, true);

        // Als nooit bekeken, toon alle 404's van de afgelopen 7 dagen
        if (empty($last_seen)) {
            $last_seen = gmdate('Y-m-d H:i:s', strtotime('-7 days'));
        }

        $table_name = $wpdb->prefix . 'tam_rank_404_log';

        // Check of tabel bestaat
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- only table/column identifiers are interpolated (tam_rank_404_log); admin-context read, caching not applicable
        if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
            return 0;
        }

        // Tel unieke URLs sinds laatste keer bekeken
        // phpcs:disable WordPress.DB.PreparedSQL, WordPress.DB.DirectDatabaseQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter -- only the table identifier $table_name (tam_rank_404_log) is interpolated; user value $last_seen is bound via prepare() %s; admin-context read, caching not applicable
        $count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(DISTINCT url) FROM $table_name WHERE timestamp > %s",
            $last_seen
        ));
        // phpcs:enable WordPress.DB.PreparedSQL, WordPress.DB.DirectDatabaseQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter

        return intval($count);
    }

    /**
     * Update last seen wanneer 404 Monitor pagina wordt bezocht
     */
    public function maybe_update_last_seen() {
        // Check of we op de 404 Monitor pagina zijn
        if (!isset($_GET['page'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only request inspection (admin page / OAuth callback / menu detection); no state-changing action to protect.
            return;
        }

        // Update wanneer we op de 404 Monitor pagina zijn
        if (sanitize_text_field(wp_unslash($_GET['page'])) === 'tam-rank-404') { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only request inspection (admin page / OAuth callback / menu detection); no state-changing action to protect.
            $this->update_last_seen();
            return;
        }

        // Of op de redirects tab (voor backward compatibility)
        if (sanitize_text_field(wp_unslash($_GET['page'])) === 'tam-rank-settings' && isset($_GET['tab']) && sanitize_text_field(wp_unslash($_GET['tab'])) === 'redirects') { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only request inspection (admin page / OAuth callback / menu detection); no state-changing action to protect.
            $this->update_last_seen();
        }
    }

    /**
     * Update de last seen timestamp voor huidige gebruiker
     */
    public function update_last_seen() {
        $user_id = get_current_user_id();
        if (!$user_id) {
            return;
        }

        update_user_meta($user_id, self::META_LAST_SEEN, current_time('mysql'));
    }

    /**
     * AJAX: Markeer 404's als gezien
     */
    public function ajax_mark_404_seen() {
        check_ajax_referer('tam_rank_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => tamrank__('error_permission_denied', 'You do not have permission for this action.'), 'code' => 'permission_denied'));
        }

        $this->update_last_seen();

        wp_send_json_success(array(
            'message' => tamrank__('admin_bar_404_marked_seen', '404 alerts marked as seen'),
        ));
    }

    /**
     * Enqueue admin bar assets (CSS + dismiss JS).
     */
    public function enqueue_admin_bar_assets() {
        if (!is_admin_bar_showing() || !current_user_can('manage_options')) {
            return;
        }

        wp_enqueue_style(
            'tamrank-admin-bar',
            TAM_RANK_PLUGIN_URL . 'assets/css/admin-bar-notifications.css',
            array(),
            TAM_RANK_VERSION
        );

        wp_enqueue_script(
            'tamrank-admin-bar',
            TAM_RANK_PLUGIN_URL . 'assets/js/admin-bar-notifications.js',
            array('jquery'),
            TAM_RANK_VERSION,
            true
        );

        wp_localize_script('tamrank-admin-bar', 'tamRankAdminBar', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce('tam_rank_nonce'),
        ));
    }

}
