<?php

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

add_action( 'admin_bar_menu', 'fense_bpvt_admin_bar_items', 100 );

function fense_bpvt_admin_bar_items( WP_Admin_Bar $wp_admin_bar )
{
	
	if ( !current_user_can( 'manage_options' ) ) {
		return;
	}
	
	$settings = FENSE_BPVT_plugin_settings( new FENSE_BPVT_FUN() );
	$is_enabled = (bool)$settings->enable;
	$is_daily_limit = (bool)FENSE_BPVT_FUN::IsDailyLimitReached();  // fix: was $daily_limit
	$is_key_valid = (bool)FENSE_BPVT_FUN::IsKeyValid();            // fix: was ignored
	
	$is_active = $is_enabled && $is_key_valid && !$is_daily_limit;        // fix: all 3 conditions
	
	
	// Determine tooltip label in priority order
	if ( $is_active ) {
		$dot_tooltip = __( 'Active', 'fense-block-vpn-proxy' );
	} elseif ( !$is_enabled ) {
		$dot_tooltip = __( 'Disabled', 'fense-block-vpn-proxy' );
	} elseif ( !$is_key_valid ) {
		$dot_tooltip = __( 'Invalid API Key', 'fense-block-vpn-proxy' );
	} else {
		$dot_tooltip = __( 'API Limit Reached', 'fense-block-vpn-proxy' );
	}
	
	$dot_color = $is_active ? '#22c55e' : '#ef4444';
	
	$dot = sprintf(
		'<span style="
            display:inline-block;
            width:15px;
            height:15px;
            border-radius:50%%;
            background:%s;
            margin-right:5px;
            vertical-align:middle;
            box-shadow:0 0 4px %s;
        " title="%s"></span>',
		esc_attr( $dot_color ),
		esc_attr( $dot_color ),
		esc_attr( $dot_tooltip )
	);
	
	// Root node — dot + label
	$wp_admin_bar->add_node( [
		'id' => 'fense-bpvt-root',
		'title' => $dot . 'Fense',
		'href' => admin_url( 'admin.php?page=fense-bpvt' ),
		'meta' => [
			'title' => __( 'Fense Block VPN & Proxy', 'fense-block-vpn-proxy' ),
		],
	] );
	
	// Child — Dashboard
	$wp_admin_bar->add_node( [
		'parent' => 'fense-bpvt-root',
		'id' => 'fense-bpvt-dashboard',
		'title' => __( 'Dashboard', 'fense-block-vpn-proxy' ),
		'href' => admin_url( 'admin.php?page=fense-bpvt' ),
	] );
	
	// Child — Settings
	$wp_admin_bar->add_node( [
		'parent' => 'fense-bpvt-root',
		'id' => 'fense-bpvt-settings',
		'title' => __( 'Statistics', 'fense-block-vpn-proxy' ),
		'href' => admin_url( 'admin.php?page=fense-bpvt-statistics' ),
	] );
	
	// Child — Status (non-clickable info row)
	$status_dot = sprintf(
		'<span style="
            display:inline-block;
            width:15px;
            height:15px;
            border-radius:50%%;
            background:%s;
            margin-right:6px;
            vertical-align:middle;
        "></span>%s',
		esc_attr( $dot_color ),
		esc_html( $dot_tooltip )
	);
	
	$wp_admin_bar->add_node( [
		'parent' => 'fense-bpvt-root',
		'id' => 'fense-bpvt-status',
		'title' => $status_dot,
		'href' => false,
		'meta' => [ 'class' => 'fense-bpvt-status-node' ],
	] );
}
