<?php
/**
 * Global Admin Header Partial
 *
 * Renders the shared branded header used on all SiteStaffr admin pages.
 * Displays the SiteStaffr logo (left), page title (center), and status
 * badge (right) derived from the current billing/subscription state.
 *
 * Also renders a global low-balance alert banner (between header and
 * page content) when the AI minute balance drops below threshold.
 * Dismissible via user meta — stays hidden until balance is replenished
 * and drops low again.
 *
 * Usage: set $sitestaffr_page_title before including this partial.
 *
 * @link       https://github.com/sitestaffr/sitestaffr-plugin
 * @since      0.14.49
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/partials
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

// Page title passed by the including view; fall back to empty string.
$sitestaffr_page_title = isset( $sitestaffr_page_title ) ? $sitestaffr_page_title : '';

// -------------------------------------------------------------------------
// Resolve subscription status from billing cache.
// -------------------------------------------------------------------------
$header_status_key = '';
if ( class_exists( 'SiteStaffr_Billing_State' ) ) {
	$header_cache      = SiteStaffr_Billing_State::get_cache();
	$header_status_key = isset( $header_cache['subscription_status'] )
		? sanitize_key( $header_cache['subscription_status'] )
		: '';
}

// Map subscription status keys to human-readable labels.
$header_status_labels = array(
	'trial_active'  => __( 'Trial', 'sitestaffr' ),
	'active'        => __( 'Active', 'sitestaffr' ),
	'past_due'      => __( 'Past Due', 'sitestaffr' ),
	'canceled'      => __( 'Canceled', 'sitestaffr' ),
	'trial_expired' => __( 'Expired', 'sitestaffr' ),
	'unpaid'        => __( 'Payment Failed', 'sitestaffr' ),
);

// Map subscription status keys to badge modifier CSS classes.
$header_status_classes = array(
	'trial_active'  => 'status-trial',
	'active'        => 'status-active',
	'past_due'      => 'status-warning',
	'canceled'      => 'status-canceled',
	'trial_expired' => 'status-canceled',
	'unpaid'        => 'status-warning',
);

$header_label = isset( $header_status_labels[ $header_status_key ] )
	? $header_status_labels[ $header_status_key ]
	: __( 'Active', 'sitestaffr' );

$header_badge_class = isset( $header_status_classes[ $header_status_key ] )
	? $header_status_classes[ $header_status_key ]
	: 'status-active';
?>
<div class="sitestaffr-page-header">

	<!-- Left: Logo (links to Dashboard) -->
	<div class="sitestaffr-header-logo">
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=sitestaffr' ) ); ?>">
			<img
				src="<?php echo esc_url( SITESTAFFR_PLUGIN_URL . 'assets/images/logo.png?v=' . SITESTAFFR_VERSION ); ?>"
				alt="<?php esc_attr_e( 'SiteStaffr', 'sitestaffr' ); ?>"
				class="sitestaffr-logo-image"
			/>
		</a>
	</div>

	<!-- Center: Page title -->
	<?php if ( ! empty( $sitestaffr_page_title ) ) : ?>
	<h2 class="sitestaffr-header-page-title"><?php echo esc_html( $sitestaffr_page_title ); ?></h2>
	<?php endif; ?>

	<!-- Right: Status badge -->
	<div class="sitestaffr-header-actions">
		<span class="sitestaffr-header-status <?php echo esc_attr( $header_badge_class ); ?>">
			<?php echo esc_html( $header_label ); ?>
		</span>
	</div>

</div>
<hr class="wp-header-end" style="display:none;">
<?php
// -------------------------------------------------------------------------
// Global Low Balance Alert Banner
// Rendered between header and page content on ALL SiteStaffr admin pages.
// Dismissible per billing cycle via user meta.
// -------------------------------------------------------------------------
$_pe_show_global_alert = false;
$_pe_alert_level       = 'none';
$_pe_alert_dismiss_key = 'none';
$_pe_alert_title       = '';
$_pe_alert_message     = '';
$_pe_alert_button_text = '';
$_pe_total_minutes     = 0;
$_pe_show_upgrade_cta  = false;
$_pe_upgrade_url       = admin_url( 'admin.php?page=sitestaffr-usage#purchase-minutes' );

// Allow individual pages to suppress the alert (e.g. Dashboard has its own inline CTA).
$_pe_suppress_alert = ! empty( $sitestaffr_suppress_low_balance_alert );
// Allow focused onboarding pages to skip rendering unrelated purchase UI.
$_pe_suppress_buy_modal = ! empty( $sitestaffr_suppress_buy_minutes_modal );

if ( ! $_pe_suppress_alert && class_exists( 'SiteStaffr_Usage_Manager' ) && class_exists( 'SiteStaffr_Billing_State' ) ) {
	$_pe_usage   = SiteStaffr_Usage_Manager::get_instance();
	$_pe_balance = $_pe_usage->get_minutes_balance();
	$_pe_total_minutes = (int) $_pe_balance['total'];

	$_pe_bcache  = isset( $header_cache ) ? $header_cache : SiteStaffr_Billing_State::get_cache();
	$_pe_plan    = isset( $_pe_bcache['plan_name'] ) ? sanitize_key( $_pe_bcache['plan_name'] ) : 'starter';
	$_pe_quotas  = array( 'trial' => 30, 'starter' => 60, 'business' => 300, 'pro' => 700 );
	$_pe_iq      = isset( $_pe_quotas[ $_pe_plan ] ) ? (int) $_pe_quotas[ $_pe_plan ] : 60;
	$_pe_tq      = $_pe_iq + (int) $_pe_balance['purchased'];
	$_pe_pct     = ( $_pe_tq > 0 ) ? ( $_pe_total_minutes / $_pe_tq ) * 100 : 0;

	// Determine alert level.
	if ( $_pe_pct < 5 || $_pe_total_minutes < 2 ) {
		$_pe_alert_level = 'critical';
		if ( $_pe_total_minutes <= 0 ) {
			$_pe_alert_dismiss_key = 'exhausted';
			$_pe_alert_title = __( 'AI Minutes Exhausted', 'sitestaffr' );
			$_pe_alert_message = __( 'Your AI voice agent is paused because your minute balance is 0 — visitors still get text chat. Add minutes or upgrade your plan to restore voice.', 'sitestaffr' );
		} else {
			$_pe_alert_dismiss_key = 'critical';
			$_pe_alert_title = __( 'Almost out of AI minutes', 'sitestaffr' );
			$_pe_alert_message = sprintf(
				// translators: %1$d: remaining minutes, %2$d: total quota, %3$d: percentage remaining.
				__( 'Only %1$d of %2$d AI minutes left (%3$d%%). Voice conversations pause when the balance reaches zero.', 'sitestaffr' ),
				$_pe_total_minutes, $_pe_tq, round( $_pe_pct )
			);
		}
		$_pe_alert_button_text = __( 'Purchase AI Minutes', 'sitestaffr' );
	} elseif ( $_pe_pct < 15 || $_pe_total_minutes < 5 ) {
		$_pe_alert_level = 'low';
		$_pe_alert_dismiss_key = 'low';
		$_pe_alert_title = __( 'Low minute balance', 'sitestaffr' );
		$_pe_alert_message = sprintf(
			// translators: %1$d: remaining minutes, %2$d: total quota, %3$d: percentage remaining.
			__( 'Only %1$d of %2$d AI minutes remaining (%3$d%%). Voice conversations pause if your balance runs out.', 'sitestaffr' ),
			$_pe_total_minutes, $_pe_tq, round( $_pe_pct )
		);
		$_pe_alert_button_text = __( 'Purchase More AI Minutes', 'sitestaffr' );
	} elseif ( $_pe_pct < 25 || $_pe_total_minutes < 15 ) {
		$_pe_alert_level = 'warning';
		$_pe_alert_dismiss_key = 'warning';
		$_pe_alert_title = __( 'Approaching Low Balance', 'sitestaffr' );
		$_pe_alert_message = sprintf(
			// translators: %1$d: remaining minutes, %2$d: total quota, %3$d: percentage remaining.
			__( 'You have %1$d of %2$d AI minutes remaining (%3$d%%). Consider purchasing more to avoid interruption.', 'sitestaffr' ),
			$_pe_total_minutes, $_pe_tq, round( $_pe_pct )
		);
		$_pe_alert_button_text = __( 'Purchase AI Minutes', 'sitestaffr' );
	}

	$_pe_show_upgrade_cta = ( 'critical' === $_pe_alert_level )
		&& in_array( $_pe_plan, array( 'trial', 'starter', 'business' ), true );

	if ( 'none' !== $_pe_alert_level ) {
		$_pe_show_global_alert = true;

		// One-time migration: remove old balance-based dismiss meta if present.
		$_pe_user_id = get_current_user_id();
		if ( '' !== get_user_meta( $_pe_user_id, 'sitestaffr_alert_dismissed_balance', true ) ) {
			delete_user_meta( $_pe_user_id, 'sitestaffr_alert_dismissed_balance' );
		}

		// Check timestamp-based dismiss: suppress only for the same alert level.
		// This allows escalation paths (warning -> low -> critical) to re-surface immediately.
		$_pe_dismissed_until = get_user_meta( $_pe_user_id, 'sitestaffr_alert_dismissed_until', true );
		$_pe_dismissed_level = get_user_meta( $_pe_user_id, 'sitestaffr_alert_dismissed_level', true );
		if ( '' !== $_pe_dismissed_until && time() < (int) $_pe_dismissed_until ) {
			if ( empty( $_pe_dismissed_level ) ) {
				// Legacy dismiss entries had no level metadata. Clear them so banners render again.
				delete_user_meta( $_pe_user_id, 'sitestaffr_alert_dismissed_until' );
				delete_user_meta( $_pe_user_id, 'sitestaffr_alert_dismissed_level' );
			} elseif ( $_pe_dismissed_level === $_pe_alert_dismiss_key ) {
				$_pe_show_global_alert = false;
			}
		}
	}
}

if ( $_pe_show_global_alert ) : ?>
<!-- Global Low Balance Alert (between header and content) -->
<div class="sitestaffr-alert sitestaffr-alert-global sitestaffr-alert-<?php echo esc_attr( $_pe_alert_level ); ?>" id="sitestaffr-global-low-balance-alert" data-alert-level="<?php echo esc_attr( $_pe_alert_dismiss_key ); ?>">
	<div class="sitestaffr-alert-content">
		<span class="sitestaffr-alert-icon dashicons dashicons-warning"></span>
		<div class="sitestaffr-alert-text">
			<strong class="sitestaffr-alert-title"><?php echo esc_html( $_pe_alert_title ); ?></strong>
			<p class="sitestaffr-alert-message"><?php echo esc_html( $_pe_alert_message ); ?></p>
		</div>
		<div class="sitestaffr-alert-actions">
			<button type="button" class="sitestaffr-alert-button" data-open-buy-modal>
				<?php echo esc_html( $_pe_alert_button_text ); ?>
			</button>
			<?php if ( $_pe_show_upgrade_cta ) : ?>
				<a href="<?php echo esc_url( $_pe_upgrade_url ); ?>" class="sitestaffr-alert-button sitestaffr-alert-button-secondary">
					<?php esc_html_e( 'Upgrade Plan', 'sitestaffr' ); ?>
				</a>
			<?php endif; ?>
		</div>
		<button type="button" class="sitestaffr-alert-dismiss" title="<?php esc_attr_e( 'Dismiss', 'sitestaffr' ); ?>" aria-label="<?php esc_attr_e( 'Dismiss alert', 'sitestaffr' ); ?>">
			<span class="dashicons dashicons-no-alt"></span>
		</button>
	</div>
</div>
<!-- Alert dismiss JS enqueued via class-sitestaffr-admin.php (wp_add_inline_script on tooltips) -->
<?php endif; ?>
<?php // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>

<?php
if ( ! $_pe_suppress_buy_modal && ! defined( 'SITESTAFFR_BUY_MODAL_RENDERED' ) ) {
	define( 'SITESTAFFR_BUY_MODAL_RENDERED', true );
	include SITESTAFFR_PLUGIN_DIR . 'admin/partials/buy-minutes-modal.php';
}
?>
