<?php

/**
 * SocialPromoter - Post History admin page (free).
 *
 * A paginated log of everything sent and any failures, grouped into sends,
 * with per-channel status, error messages and delete. Engagement statistics
 * are a Pro feature: their column, refresh controls and notes are pulled in
 * from premium-only partials and are absent from the free build.
 *
 * @package PublisherKits_SocialPromoter
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
$queue = new PKITS_SP_Queue();
$per_page = 50;
$paged = ( isset( $_GET['paged'] ) ? max( 1, absint( wp_unslash( $_GET['paged'] ) ) ) : 1 );
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only pagination.
$offset = ($paged - 1) * $per_page;
$total = $queue->count_history();
$items = $queue->get_history( $per_page, $offset );
$pages = max( 1, (int) ceil( $total / $per_page ) );
// Engagement stats are Pro; the free build never loads the stats map.
$stats_map = array();
$total_sent = 0;
$total_failed = 0;
$by_platform = array();
foreach ( $items as $item ) {
    if ( 'sent' === $item->status ) {
        $total_sent++;
        $by_platform[$item->platform] = ($by_platform[$item->platform] ?? 0) + 1;
    } elseif ( 'failed' === $item->status ) {
        $total_failed++;
    }
}
?>
<div class="wrap pkits-sp-wrap">

	<h1 class="pkits-sp-page-title">
		<span class="pkits-sp-logo-mark">SP</span>
		<?php 
esc_html_e( 'SocialPromoter &mdash; Post History', 'publisherkits-socialpromoter' );
?>
		<?php 
if ( !empty( $items ) ) {
    ?>
			<button type="button" class="pkits-sp-clear-all-history-btn page-title-action" style="margin-left:12px;"><?php 
    esc_html_e( 'Clear all history', 'publisherkits-socialpromoter' );
    ?></button>
		<?php 
}
?>
	</h1>

	<?php 
if ( empty( $items ) ) {
    ?>
		<div class="pkits-sp-empty-state">
			<p><?php 
    esc_html_e( 'No posts sent yet.', 'publisherkits-socialpromoter' );
    ?></p>
		</div>
	<?php 
} else {
    ?>

	<div id="pkits-sp-history-notice" style="display:none;margin-bottom:12px;padding:10px 14px;border-radius:5px;font-size:12px;max-width:1100px;"></div>

	<div class="pkits-sp-page-layout">
		<div class="pkits-sp-page-main">

			<div class="pkits-sp-send-cards">
				<?php 
    // Cluster rows into sends: rows belong to one send when they share
    // a post (and campaign) and were sent within a few minutes.
    $cards = array();
    $prev_ts = null;
    $prev_key = null;
    foreach ( $items as $c_item ) {
        $c_ts = strtotime( ($c_item->sent_at ?? $c_item->scheduled_at) . ' UTC' );
        $c_key = (int) $c_item->post_id . '|' . (int) ($c_item->campaign_id ?? 0);
        $c_new = empty( $cards ) || $c_key !== $prev_key || null !== $prev_ts && false !== $c_ts && abs( $prev_ts - $c_ts ) > 180;
        if ( $c_new ) {
            $cards[] = array();
        }
        $cards[count( $cards ) - 1][] = $c_item;
        $prev_ts = $c_ts;
        $prev_key = $c_key;
    }
    foreach ( $cards as $card ) {
        $head = $card[0];
        ?>
					<div class="pkits-sp-send-card">
						<div class="pkits-sp-send-card-head">
							<div class="pkits-sp-send-card-title">
								<?php 
        if ( $head->post_id ) {
            ?>
									<a href="<?php 
            echo esc_url( get_edit_post_link( $head->post_id ) );
            ?>"><?php 
            echo esc_html( ( get_the_title( $head->post_id ) ?: '#' . (int) $head->post_id ) );
            ?></a>
								<?php 
        } elseif ( $head->campaign_id ) {
            ?>
									<span class="pkits-sp-send-card-kind"><?php 
            esc_html_e( 'Campaign', 'publisherkits-socialpromoter' );
            ?></span>
								<?php 
        } else {
            ?>
									<span class="pkits-sp-send-card-kind"><?php 
            esc_html_e( 'Standalone', 'publisherkits-socialpromoter' );
            ?></span>
								<?php 
        }
        ?>
								<span class="pkits-sp-send-card-time"><?php 
        echo esc_html( $head->sent_at ?? $head->scheduled_at );
        ?> <?php 
        esc_html_e( 'UTC', 'publisherkits-socialpromoter' );
        ?></span>
							</div>
							<?php 
        if ( '' !== trim( (string) $head->copy_text ) ) {
            ?>
								<div class="pkits-sp-send-card-copy"><?php 
            echo esc_html( mb_substr( $head->copy_text, 0, 140 ) . (( mb_strlen( $head->copy_text ) > 140 ? chr( 226 ) . chr( 128 ) . chr( 166 ) : '' )) );
            ?></div>
							<?php 
        }
        ?>
						</div>
						<div class="pkits-sp-send-card-channels">
							<?php 
        foreach ( $card as $item ) {
            $is_sent = 'sent' === $item->status;
            ?>
								<div class="pkits-sp-send-channel" data-queue-id="<?php 
            echo (int) $item->id;
            ?>">
									<span class="pkits-sp-platform-badge pkits-sp-badge-<?php 
            echo esc_attr( $item->platform );
            ?>"><?php 
            echo esc_html( strtoupper( $item->platform ) );
            ?></span>
									<span class="pkits-sp-status-pill pkits-sp-status-<?php 
            echo esc_attr( $item->status );
            ?>"><?php 
            echo esc_html( ucfirst( $item->status ) );
            ?></span>
									<?php 
            if ( !empty( $item->error_message ) ) {
                ?>
										<span class="pkits-sp-send-channel-err" title="<?php 
                echo esc_attr( $item->error_message );
                ?>"><?php 
                echo esc_html( mb_substr( $item->error_message, 0, 60 ) );
                ?></span>
									<?php 
            }
            ?>
									<?php 
            ?>
									<div class="pkits-sp-send-channel-actions">
										<button type="button" class="pkits-sp-delete-history-row button button-small" data-queue-id="<?php 
            echo (int) $item->id;
            ?>"><?php 
            esc_html_e( 'Delete', 'publisherkits-socialpromoter' );
            ?></button>
									</div>
								</div>
							<?php 
        }
        ?>
						</div>
					</div>
				<?php 
    }
    ?>
			</div>

			<?php 
    if ( $pages > 1 ) {
        ?>
				<?php 
        /* translators: %s: number of history items */
        $sp_count_label = sprintf( _n(
            '%s item',
            '%s items',
            $total,
            'publisherkits-socialpromoter'
        ), number_format_i18n( $total ) );
        ?>
				<div class="tablenav"><div class="tablenav-pages" style="margin:12px 0;">
					<span class="displaying-num"><?php 
        echo esc_html( $sp_count_label );
        ?></span>
					<?php 
        echo wp_kses_post( paginate_links( array(
            'base'      => add_query_arg( 'paged', '%#%' ),
            'format'    => '',
            'current'   => $paged,
            'total'     => $pages,
            'prev_text' => '&laquo;',
            'next_text' => '&raquo;',
        ) ) );
        ?>
				</div></div>
			<?php 
    }
    ?>

		</div>

		<div class="pkits-sp-page-aside">

			<div class="pkits-sp-widget">
				<div class="pkits-sp-widget-header">
					<div class="pkits-sp-widget-icon">&#9783;</div>
					<h3 class="pkits-sp-widget-title"><?php 
    esc_html_e( 'Summary', 'publisherkits-socialpromoter' );
    ?></h3>
				</div>
				<div class="pkits-sp-widget-body">
					<div class="pkits-sp-summary-row">
						<div class="pkits-sp-summary-label"><?php 
    esc_html_e( 'On this page', 'publisherkits-socialpromoter' );
    ?></div>
						<div class="pkits-sp-summary-value"><?php 
    echo (int) $total_sent;
    ?></div>
					</div>
					<?php 
    if ( $total_failed ) {
        ?>
					<div class="pkits-sp-summary-row">
						<div class="pkits-sp-summary-label" style="color:#d63638;"><?php 
        esc_html_e( 'Failed', 'publisherkits-socialpromoter' );
        ?></div>
						<div class="pkits-sp-summary-value" style="color:#d63638;"><?php 
        echo (int) $total_failed;
        ?></div>
					</div>
					<?php 
    }
    ?>
					<?php 
    foreach ( $by_platform as $platform => $count ) {
        ?>
					<div class="pkits-sp-summary-row">
						<div class="pkits-sp-summary-label">
							<span class="pkits-sp-platform-badge pkits-sp-badge-<?php 
        echo esc_attr( $platform );
        ?>" style="font-size:9px;"><?php 
        echo esc_html( strtoupper( $platform ) );
        ?></span>
						</div>
						<div class="pkits-sp-summary-value"><?php 
        echo (int) $count;
        ?></div>
					</div>
					<?php 
    }
    ?>
					<div class="pkits-sp-summary-row">
						<div class="pkits-sp-summary-label"><?php 
    esc_html_e( 'Total logged', 'publisherkits-socialpromoter' );
    ?></div>
						<div class="pkits-sp-summary-value"><?php 
    echo esc_html( number_format_i18n( $total ) );
    ?></div>
					</div>
				</div>
			</div>

			<?php 
    ?>

		</div>
	</div>

	<?php 
}
?>

	<?php 
?>

</div>
