<?php
/**
 * File Path: templates/admin/dashboard-status.php
 *
 * Admin Dashboard — Status partial (GC3-3 + GC3-4, UX rev 1)
 *
 * Center column. Contains:
 *   - Catalog Health score bar
 *   - System Status table (license, file integrity, ping, PA-API, WooCommerce)
 *
 * @package MyBookShowroom
 * @since   1.1.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- template-scope variables injected by mbs_get_template_part(); not global vars

$dash   = MBS_Admin_Dashboard::get_instance();
$stats  = $dash->get_catalog_stats();
$health = $dash->get_aggregate_health();
?>
<?php $is_pro = mbs_is_pro(); ?>
<!-- ── Catalog Health Score (GC3-3) ──────────────────────────────────────── -->
<div class="mbs-dashboard-card">
	<h2><?php esc_html_e( 'Catalog Health', 'my-book-showroom' ); ?></h2>

	<?php if ( 0 === $stats['total'] ) : ?>
		<p class="description">
			<?php esc_html_e( 'Add books to see a health score.', 'my-book-showroom' ); ?>
		</p>
	<?php else : ?>
		<?php
		$score_pct   = (int) $health['score'];
		$fill_mod    = $score_pct >= 80 ? 'mbs-health-bar-fill--green'
			: ( $score_pct >= 50 ? 'mbs-health-bar-fill--amber' : 'mbs-health-bar-fill--red' );
		?>
		<div class="mbs-health-bar-wrap">
			<div class="mbs-health-bar-fill <?php echo esc_attr( $fill_mod ); ?>"
			     style="width:<?php echo (int) $score_pct; ?>%;"
			     role="progressbar"
			     aria-valuenow="<?php echo (int) $score_pct; ?>"
			     aria-valuemin="0"
			     aria-valuemax="100">
			</div>
		</div>
		<p class="mbs-health-summary">
			<?php
			printf(
				/* translators: 1: score percent, 2: number of books scored */
				esc_html__( '%1$d%% average — %2$d book(s) scored', 'my-book-showroom' ),
				(int) $score_pct,
				(int) $health['scored']
			);
			?>
		</p>
		<?php if ( ! $is_pro ) : ?>
			<p class="description" style="font-size:12px;margin-top:6px;">
				<?php esc_html_e( 'PRO adds audio sample, PA-API, and newsletter dimensions.', 'my-book-showroom' ); ?>
			</p>
		<?php endif; ?>
	<?php endif; ?>
</div><!-- catalog health card -->

<!-- ── System Status (GC3-4) ────────────────────────────────────────────── -->
<?php
$tamper_flag = (int) get_option( 'mbs_tamper_flag', MBS_TAMPER_CLEAN );
$license_reg = (bool) get_option( 'mbs_license_registered', false );
$is_keyless  = mbs_is_keyless(); // WO-002: no key stored on this install
$last_ping   = (int) get_option( 'mbs_license_last_ping', 0 );
$wc_active   = class_exists( 'WooCommerce' );
$wc_enabled  = '1' === get_option( 'mbs_setting_general_wc_enabled', '0' );
$paapi_tag   = (string) get_option( 'mbs_setting_amazon_partner_tag', '' );

// Dot color helpers.
$GREEN = 'mbs-dot-green';
$AMBER = 'mbs-dot-amber';
$RED   = 'mbs-dot-red';
$GRAY  = 'mbs-dot-gray';

// License — 3 states: keyless / key-stored-unactivated / activated (WO-002).
if ( $is_keyless ) {
	$lic_dot = $GRAY;
	$lic_txt = __( 'Unregistered — FREE tier', 'my-book-showroom' );
} elseif ( ! $license_reg ) {
	$lic_dot = $RED;
	$lic_txt = __( 'Not activated', 'my-book-showroom' );
} else {
	$lic_dot = $GREEN;
	$lic_txt = sprintf(
		/* translators: %s: license tier */
		__( 'Active — %s', 'my-book-showroom' ),
		ucfirst( mbs_get_license_tier_label() )
	);
}

// File integrity.
$fi_dot = MBS_TAMPER_CLEAN === $tamper_flag ? $GREEN
	: ( MBS_TAMPER_WARN === $tamper_flag ? $AMBER : $RED );
$fi_txt = MBS_TAMPER_CLEAN === $tamper_flag
	? __( 'OK', 'my-book-showroom' )
	: ( MBS_TAMPER_WARN === $tamper_flag
		? __( 'Warning — mismatch detected', 'my-book-showroom' )
		: __( 'Tamper detected', 'my-book-showroom' ) );

// License ping.
$ping_age = $last_ping > 0 ? ( time() - $last_ping ) : PHP_INT_MAX;
$ping_dot = $last_ping > 0 ? ( $ping_age < WEEK_IN_SECONDS ? $GREEN : $AMBER ) : $GRAY;
$ping_txt = $last_ping > 0
	? sprintf(
		/* translators: %s: human time diff */
		__( '%s ago', 'my-book-showroom' ),
		human_time_diff( $last_ping, time() )
	)
	: __( 'Never', 'my-book-showroom' );

// PA-API.
$pa_dot = ! empty( $paapi_tag ) ? $GREEN : $GRAY;
$pa_txt = ! empty( $paapi_tag )
	? sprintf(
		/* translators: %s: Amazon partner tag */
		__( 'Tag: %s', 'my-book-showroom' ),
		$paapi_tag
	)
	: __( 'Not configured', 'my-book-showroom' );

// WooCommerce.
$wc_dot = $wc_active ? ( $wc_enabled ? $GREEN : $AMBER ) : $GRAY;
$wc_txt = $wc_active
	? ( $wc_enabled ? __( 'Active', 'my-book-showroom' ) : __( 'Installed, not enabled', 'my-book-showroom' ) )
	: __( 'Not installed', 'my-book-showroom' );
?>
<div class="mbs-dashboard-card">
	<h2><?php esc_html_e( 'System Status', 'my-book-showroom' ); ?></h2>
	<table class="mbs-status-table">
		<tbody>
			<tr>
				<td class="mbs-status-label"><?php esc_html_e( 'License', 'my-book-showroom' ); ?></td>
				<td>
					<span class="mbs-status-dot <?php echo esc_attr( $lic_dot ); ?>"></span>
					<?php echo esc_html( $lic_txt ); ?>
					<?php if ( $is_keyless ) : ?>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=my-book-showroom-settings&tab=license' ) ); ?>"
						   class="button button-small" style="margin-left:6px;">
							<?php esc_html_e( 'Register →', 'my-book-showroom' ); ?>
						</a>
					<?php elseif ( ! $license_reg ) : ?>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=my-book-showroom-settings&tab=license' ) ); ?>"
						   class="button button-small" style="margin-left:6px;">
							<?php esc_html_e( 'Activate', 'my-book-showroom' ); ?>
						</a>
					<?php endif; ?>
				</td>
			</tr>
			<tr>
				<td class="mbs-status-label"><?php esc_html_e( 'File Integrity', 'my-book-showroom' ); ?></td>
				<td>
					<span class="mbs-status-dot <?php echo esc_attr( $fi_dot ); ?>"></span>
					<?php echo esc_html( $fi_txt ); ?>
				</td>
			</tr>
			<tr>
				<td class="mbs-status-label"><?php esc_html_e( 'License Ping', 'my-book-showroom' ); ?></td>
				<td>
					<span class="mbs-status-dot <?php echo esc_attr( $ping_dot ); ?>"></span>
					<?php echo esc_html( $ping_txt ); ?>
				</td>
			</tr>
			<tr>
				<td class="mbs-status-label"><?php esc_html_e( 'PA-API', 'my-book-showroom' ); ?></td>
				<td>
					<span class="mbs-status-dot <?php echo esc_attr( $pa_dot ); ?>"></span>
					<?php echo esc_html( $pa_txt ); ?>
				</td>
			</tr>
			<tr>
				<td class="mbs-status-label"><?php esc_html_e( 'WooCommerce', 'my-book-showroom' ); ?></td>
				<td>
					<span class="mbs-status-dot <?php echo esc_attr( $wc_dot ); ?>"></span>
					<?php echo esc_html( $wc_txt ); ?>
				</td>
			</tr>
		</tbody>
	</table>
</div><!-- system status card -->


<!-- ── ARC Publisher Campaign Overview (DASH-2B) ──────────────────────── -->
<?php
if ( mbs_is_pub() ) :
	// Active campaigns only -- not-started and closed are not actionable on the dashboard.
	$arc_active_stats = array_values( array_filter(
		MBS_Arc_Recipient_DAO::get_all_arc_books_with_stats(),
		function( $_s ) { return 'active' === $_s->arc_status; }
	) );
	if ( ! empty( $arc_active_stats ) ) :
		$_arc_overdue = 0;
		foreach ( $arc_active_stats as $_as ) {
			if ( $_as->is_overdue ) { ++$_arc_overdue; }
		}
?>
<div class="mbs-dashboard-card mbs-arc-campaign-card">
	<h2><?php echo esc_html( sprintf(
		/* translators: %d: number of active ARC campaigns */
		_n( 'ARC Campaigns (%d active)', 'ARC Campaigns (%d active)', count( $arc_active_stats ), 'my-book-showroom' ),
		count( $arc_active_stats )
	) ); ?></h2>

	<?php if ( $_arc_overdue > 0 ) : ?>
	<div class="mbs-arc-summary-bar">
		<span class="mbs-arc-summary-item mbs-arc-summary-overdue">
			<strong><?php echo (int) $_arc_overdue; ?></strong>
			<?php esc_html_e( 'overdue', 'my-book-showroom' ); ?>
		</span>
	</div><!-- .mbs-arc-summary-bar -->
	<?php endif; ?>

	<table class="widefat fixed mbs-arc-campaign-table" style="margin-top:10px;">
		<thead>
			<tr>
				<th><?php esc_html_e( 'Book', 'my-book-showroom' ); ?></th>
				<th><?php esc_html_e( 'Status', 'my-book-showroom' ); ?></th>
				<th><?php esc_html_e( 'Target Date', 'my-book-showroom' ); ?></th>
				<th><?php esc_html_e( 'Sent', 'my-book-showroom' ); ?></th>
				<th><?php esc_html_e( 'Reviews', 'my-book-showroom' ); ?></th>
				<th><?php esc_html_e( 'Conversion', 'my-book-showroom' ); ?></th>
			</tr>
		</thead>
		<tbody>
		<?php foreach ( $arc_active_stats as $arc_s ) : ?>
			<?php
			// Status badge color.
			if ( $arc_s->is_overdue ) {
				$_badge_cls   = 'mbs-badge-overdue';
				$_status_lbl  = esc_html__( 'Overdue', 'my-book-showroom' );
			} elseif ( 'active' === $arc_s->arc_status ) {
				$_badge_cls   = 'mbs-badge-active';
				$_status_lbl  = esc_html__( 'Active', 'my-book-showroom' );
			} elseif ( 'closed' === $arc_s->arc_status ) {
				$_badge_cls   = 'mbs-badge-closed';
				$_status_lbl  = esc_html__( 'Closed', 'my-book-showroom' );
			} else {
				$_badge_cls   = 'mbs-badge-not-started';
				$_status_lbl  = esc_html__( 'Not Started', 'my-book-showroom' );
			}
			// Mini timeline bar (target date progress).
			$_timeline_pct = 0;
			if ( ! empty( $arc_s->target_date ) && $arc_s->copies_sent > 0 ) {
				$_timeline_pct = min( 100, (int) $arc_s->conversion_pct );
			}
			$_row_cls = $arc_s->is_overdue ? ' class="mbs-arc-overdue"' : '';
			?>
			<tr<?php echo $_row_cls; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe, constructed above ?>>
				<td>
					<a href="<?php echo esc_url( get_edit_post_link( $arc_s->post_id ) ); ?>">
						<?php echo esc_html( $arc_s->title ); ?>
					</a>
				</td>
				<td>
					<span class="mbs-badge <?php echo esc_attr( $_badge_cls ); ?>">
						<?php echo $_status_lbl; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped above ?>
					</span>
				</td>
				<td>
					<?php
					if ( ! empty( $arc_s->target_date ) ) {
						echo esc_html( date_i18n( get_option( 'date_format' ), strtotime( $arc_s->target_date ) ) );
					} else {
						echo '&mdash;';
					}
					?>
				</td>
				<td><?php echo (int) $arc_s->copies_sent; ?></td>
				<td><?php echo (int) $arc_s->reviews_received; ?></td>
				<td>
					<?php if ( $arc_s->copies_sent > 0 ) : ?>
						<div class="mbs-arc-conversion-wrap" title="<?php echo esc_attr( $arc_s->conversion_pct . '%' ); ?>">
							<div class="mbs-arc-conversion-bar" style="width:<?php echo (int) min( 100, $arc_s->conversion_pct ); ?>%;"></div>
						</div>
						<span class="mbs-arc-conversion-pct"><?php echo esc_html( $arc_s->conversion_pct . '%' ); ?></span>
					<?php else : ?>
						&mdash;
					<?php endif; ?>
				</td>
			</tr>
		<?php endforeach; ?>
		</tbody>
	</table>
</div><!-- arc campaign card -->
<?php endif; endif; ?>
