<?php
/**
 * Admin analytics page view.
 *
 * @package    100Prints
 */

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

$analytics_service = new Hundred_Prints_Analytics_Service();

$total_generations = $analytics_service->get_total_generations();
$generations_30_days = $analytics_service->get_generations_last_30_days();
$success_rate = $analytics_service->get_success_rate();
$daily_counts = $analytics_service->get_daily_counts_30_days();
$template_breakdown = $analytics_service->get_template_breakdown();
$recent_activity = $analytics_service->get_recent_activity( 20 );
$export_activity = $analytics_service->get_recent_activity(1000);

// Calculate daily average
$daily_avg = count( $daily_counts ) ? round( array_sum( $daily_counts ) / count( $daily_counts ), 1 ) : 0;

// Chart Analytics Logic
$actual_max = ! empty( $daily_counts ) ? max( $daily_counts ) : 0;
// Force a minimum Y-axis ceiling of 10 so small numbers don't stretch to 100% height
$y_max = max( $actual_max, 10 );
// Round up to the nearest multiple of 10 for clean grid lines if the number is large
if ( $y_max > 10 ) {
    $y_max = ceil( $y_max / 10 ) * 10; 
}

// Register the downloadAnalyticsCSV function via WP enqueue system.
$export_data_json = wp_json_encode( $export_activity );
$analytics_inline_js = "
function downloadAnalyticsCSV() {
    var rawData = {$export_data_json};
    if (!rawData || rawData.length === 0) {
        alert('No analytics data available to export yet.');
        return;
    }
    var csvString = 'Date & Time,Template Name,Template ID,Status\\n';
    rawData.forEach(function(row) {
        var date   = '\"' + row.created_at + '\"';
        var name   = '\"' + (row.template_name ? row.template_name.replace(/\"/g, '\"\"') : 'Unknown') + '\"';
        var id     = '\"' + row.template_id + '\"';
        var status = '\"' + row.status.toUpperCase() + '\"';
        csvString += date + ',' + name + ',' + id + ',' + status + '\\n';
    });
    var blob = new Blob(['\\ufeff' + csvString], { type: 'text/csv;charset=utf-8;' });
    var url  = URL.createObjectURL(blob);
    var link = document.createElement('a');
    link.href = url;
    var today = new Date().toISOString().split('T')[0];
    link.setAttribute('download', '100prints-analytics-' + today + '.csv');
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
";
wp_add_inline_script( '100prints-admin-js', $analytics_inline_js );
?>

<div class="wrap hundredp-wrap" style="background: #F8FAFC; min-height: 100vh; padding-bottom: 60px;">

	<?php
	$args = [ 'title' => 'Analytics' ];
	require HUNDRED_PRINTS_PATH . 'admin/partials/header.php';
	?>

	<div style="padding: 10px 32px; max-width: 1200px; margin: 0 auto;">
		
		<section style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 16px; margin-bottom: 24px;">
			<div style="background: #FFFFFF; border: 1px solid #EAEAEA; border-radius: 8px; padding: 20px; box-shadow: 0 1px 2px rgba(0,0,0,0.02); display: flex; align-items: center; justify-content: space-between;">
				<div>
					<h3 style="margin: 0 0 6px 0; font-size: 12px; font-weight: 600; color: #64748B; text-transform: uppercase; letter-spacing: 0.05em;">Total Vol.</h3>
					<p style="margin: 0; font-size: 24px; font-weight: 700; color: #0F172A; line-height: 1;"><?php echo esc_html( $total_generations ); ?></p>
				</div>
                <i class="ph-bold ph-stack" style="font-size: 24px; color: #94A3B8;"></i>
			</div>
			<div style="background: #FFFFFF; border: 1px solid #EAEAEA; border-radius: 8px; padding: 20px; box-shadow: 0 1px 2px rgba(0,0,0,0.02); display: flex; align-items: center; justify-content: space-between;">
				<div>
					<h3 style="margin: 0 0 6px 0; font-size: 12px; font-weight: 600; color: #64748B; text-transform: uppercase; letter-spacing: 0.05em;">30-Day Trend</h3>
					<p style="margin: 0; font-size: 24px; font-weight: 700; color: #0F172A; line-height: 1;"><?php echo esc_html( $generations_30_days ); ?></p>
				</div>
                <i class="ph-bold ph-calendar-blank" style="font-size: 24px; color: #94A3B8;"></i>
			</div>
			<div style="background: #FFFFFF; border: 1px solid #EAEAEA; border-radius: 8px; padding: 20px; box-shadow: 0 1px 2px rgba(0,0,0,0.02); display: flex; align-items: center; justify-content: space-between;">
				<div>
					<h3 style="margin: 0 0 6px 0; font-size: 12px; font-weight: 600; color: #64748B; text-transform: uppercase; letter-spacing: 0.05em;">Success Rate</h3>
					<p style="margin: 0; font-size: 24px; font-weight: 700; color: #0F172A; line-height: 1;"><?php echo esc_html( $success_rate ); ?>%</p>
				</div>
                <i class="ph-bold ph-check-circle" style="font-size: 24px; color: <?php echo $success_rate > 90 ? '#16A34A' : '#D97706'; ?>;"></i>
			</div>
			<div style="background: #FFFFFF; border: 1px solid #EAEAEA; border-radius: 8px; padding: 20px; box-shadow: 0 1px 2px rgba(0,0,0,0.02); display: flex; align-items: center; justify-content: space-between;">
				<div>
					<h3 style="margin: 0 0 6px 0; font-size: 12px; font-weight: 600; color: #64748B; text-transform: uppercase; letter-spacing: 0.05em;">Daily Avg</h3>
					<p style="margin: 0; font-size: 24px; font-weight: 700; color: #0F172A; line-height: 1;"><?php echo esc_html( $daily_avg ); ?></p>
				</div>
                <i class="ph-bold ph-trend-up" style="font-size: 24px; color: #94A3B8;"></i>
			</div>
		</section>

		<?php if ( $total_generations === 0 ) : ?>
			<section style="background: #FFFFFF; border: 1px dashed #CBD5E1; border-radius: 8px; padding: 64px 24px; text-align: center;">
				<div style="width: 48px; height: 48px; background: #F8FAFC; color: #94A3B8; border: 1px solid #EAEAEA; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 20px; margin: 0 auto 16px auto;">
					<i class="ph-bold ph-chart-line-down"></i>
				</div>
				<h2 style="font-size: 16px; font-weight: 600; color: #0F172A; margin: 0 0 8px 0;">Awaiting Data</h2>
				<p style="font-size: 13px; color: #64748B; margin: 0 auto 24px auto; max-width: 400px; line-height: 1.5;">Analytics will populate automatically once visitors begin generating documents from your blocks.</p>
			</section>
		<?php return; endif; ?>

		<div style="display: flex; flex-direction: column; gap: 24px;">
			
			<section style="background: #FFFFFF; border: 1px solid #EAEAEA; border-radius: 8px; padding: 24px; box-shadow: 0 1px 2px rgba(0,0,0,0.02);">
				<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 32px;">
					<div>
						<h2 style="font-size: 15px; font-weight: 600; color: #0F172A; margin: 0 0 4px 0;">Generation Volume</h2>
						<p style="font-size: 12px; color: #64748B; margin: 0;">Rolling 30-day activity.</p>
					</div>
					<button type="button" onclick="downloadAnalyticsCSV()" style="display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border: 1px solid #EAEAEA; border-radius: 6px; color: #0F172A; text-decoration: none; font-size: 12px; font-weight: 500; background: #FFFFFF; box-shadow: 0 1px 2px rgba(0,0,0,0.02); cursor: pointer; transition: background 150ms ease;" onmouseover="this.style.background='#F8FAFC'" onmouseout="this.style.background='#FFFFFF'">
						<i class="ph-bold ph-download-simple"></i> Export CSV
					</button>
				</div>
				
				<div style="position: relative; width: 100%; height: 260px; padding-left: 30px; box-sizing: border-box;">
					
                    <div style="position: absolute; top: 0; left: 0; right: 0; bottom: 20px; display: flex; flex-direction: column; justify-content: space-between; z-index: 0;">
                        <div style="border-top: 1px dashed #EAEAEA; height: 100%; position: relative;">
                            <span style="position: absolute; top: -7px; left: 0; font-size: 10px; color: #94A3B8; font-family: 'Geist Mono', monospace; line-height: 1;"><?php echo esc_html($y_max); ?></span>
                        </div>
                        <div style="border-top: 1px dashed #EAEAEA; height: 100%; position: relative;">
                            <span style="position: absolute; top: -7px; left: 0; font-size: 10px; color: #94A3B8; font-family: 'Geist Mono', monospace; line-height: 1;"><?php echo esc_html(ceil($y_max / 2)); ?></span>
                        </div>
                        <div style="border-top: 1px solid #CBD5E1; position: relative;">
                            <span style="position: absolute; top: -7px; left: 0; font-size: 10px; color: #94A3B8; font-family: 'Geist Mono', monospace; line-height: 1;">0</span>
                        </div>
                    </div>

                    <div style="position: absolute; top: 0; left: 40px; right: 0; bottom: 0; display: flex; align-items: flex-end; gap: 4px; z-index: 1;">
                        <?php
                        $day_counter = 0;
                        foreach ( $daily_counts as $date => $count ) :
                            $height_percent = ( $count / $y_max ) * 100;
                            $day = date( 'd', strtotime( $date ) );
                            
                            // Only show every 3rd date label to prevent crowding on small screens, but always show the first and last
                            $show_label = ($day_counter % 3 === 0 || $day_counter === 0 || $day_counter === count($daily_counts) - 1);
                        ?>
                            <div style="flex: 1; display: flex; flex-direction: column; align-items: center; height: 100%; justify-content: flex-end; cursor: crosshair; min-width: 4px;" title="<?php echo esc_attr( date( 'M j, Y', strtotime( $date ) ) . ' — ' . $count . ' generations' ); ?>">
                                <div class="hundredp-chart-bar" style="width: 100%; max-width: 24px; height: calc(100% - 20px); display: flex; align-items: flex-end; padding-bottom: 0px;">
                                    <div style="width: 100%; height: <?php echo esc_attr( $height_percent ); ?>%; background: <?php echo $count > 0 ? '#0369A1' : 'transparent'; ?>; border-radius: 2px 2px 0 0; min-height: <?php echo $count > 0 ? '2px' : '0'; ?>;"></div>
                                </div>
                                <div style="height: 20px; display: flex; align-items: flex-end;">
                                    <span style="font-size: 10px; color: #94A3B8; font-family: 'Geist Mono', monospace; opacity: <?php echo $show_label ? '1' : '0'; ?>;"><?php echo esc_html( $day ); ?></span>
                                </div>
                            </div>
                        <?php 
                            $day_counter++;
                        endforeach; 
                        ?>
                    </div>
				</div>
			</section>

			<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(450px, 1fr)); gap: 24px;">
				
				<section style="background: #FFFFFF; border: 1px solid #EAEAEA; border-radius: 8px; box-shadow: 0 1px 2px rgba(0,0,0,0.02); overflow: hidden;">
					<div style="padding: 16px 20px; border-bottom: 1px solid #EAEAEA; background: #F8FAFC;">
						<h2 style="font-size: 14px; font-weight: 600; color: #0F172A; margin: 0;">Template Performance</h2>
					</div>
					
					<?php if ( ! empty( $template_breakdown ) ) : ?>
						<div style="overflow-x: auto;">
							<table style="width: 100%; border-collapse: collapse; text-align: left;">
								<thead>
									<tr>
										<th style="padding: 12px 20px; font-size: 11px; font-weight: 600; color: #64748B; border-bottom: 1px solid #EAEAEA; text-transform: uppercase; letter-spacing: 0.05em;">Template ID</th>
										<th style="padding: 12px 20px; font-size: 11px; font-weight: 600; color: #64748B; border-bottom: 1px solid #EAEAEA; text-transform: uppercase; letter-spacing: 0.05em; text-align: right;">Total Hits</th>
										<th style="padding: 12px 20px; font-size: 11px; font-weight: 600; color: #64748B; border-bottom: 1px solid #EAEAEA; text-transform: uppercase; letter-spacing: 0.05em; text-align: right;">Last Active</th>
									</tr>
								</thead>
								<tbody>
									<?php foreach ( $template_breakdown as $row ) : ?>
										<tr class="hundredp-table-row">
											<td style="padding: 14px 20px; font-size: 13px; font-weight: 500; color: #0F172A; border-bottom: 1px solid #F1F5F9;">
												<?php echo esc_html( $row->template_name ); ?>
											</td>
											<td style="padding: 14px 20px; font-size: 13px; color: #334155; text-align: right; border-bottom: 1px solid #F1F5F9; font-family: 'Geist Mono', monospace;">
												<?php echo esc_html( number_format( $row->count ) ); ?>
											</td>
											<td style="padding: 14px 20px; font-size: 12px; color: #64748B; text-align: right; border-bottom: 1px solid #F1F5F9;">
												<?php echo esc_html( human_time_diff( strtotime( $row->last_used ), current_time( 'timestamp' ) ) . ' ago' ); ?>
											</td>
										</tr>
									<?php endforeach; ?>
								</tbody>
							</table>
						</div>
					<?php else : ?>
						<div style="padding: 40px 20px; text-align: center;">
							<p style="color: #94A3B8; font-size: 13px; margin: 0;">No template data available.</p>
						</div>
					<?php endif; ?>
				</section>

				<section style="background: #FFFFFF; border: 1px solid #EAEAEA; border-radius: 8px; box-shadow: 0 1px 2px rgba(0,0,0,0.02); overflow: hidden;">
					<div style="padding: 16px 20px; border-bottom: 1px solid #EAEAEA; background: #F8FAFC;">
						<h2 style="font-size: 14px; font-weight: 600; color: #0F172A; margin: 0;">Live Event Log</h2>
					</div>
					
					<?php if ( ! empty( $recent_activity ) ) : ?>
						<div style="overflow-x: auto;">
							<table style="width: 100%; border-collapse: collapse; text-align: left;">
								<thead>
									<tr>
										<th style="padding: 12px 20px; font-size: 11px; font-weight: 600; color: #64748B; border-bottom: 1px solid #EAEAEA; text-transform: uppercase; letter-spacing: 0.05em;">Timestamp</th>
										<th style="padding: 12px 20px; font-size: 11px; font-weight: 600; color: #64748B; border-bottom: 1px solid #EAEAEA; text-transform: uppercase; letter-spacing: 0.05em;">Resource</th>
										<th style="padding: 12px 20px; font-size: 11px; font-weight: 600; color: #64748B; border-bottom: 1px solid #EAEAEA; text-transform: uppercase; letter-spacing: 0.05em; text-align: right;">Status</th>
									</tr>
								</thead>
								<tbody>
									<?php foreach ( $recent_activity as $row ) : ?>
										<tr class="hundredp-table-row">
											<td style="padding: 14px 20px; font-size: 12px; color: #64748B; border-bottom: 1px solid #F1F5F9; font-family: 'Geist Mono', monospace;">
												<?php echo esc_html( mysql2date( 'M j, H:i', $row->created_at ) ); ?>
											</td>
											<td style="padding: 14px 20px; font-size: 13px; font-weight: 500; color: #0F172A; border-bottom: 1px solid #F1F5F9;">
												<?php echo esc_html( $row->template_name ); ?>
											</td>
											<td style="padding: 14px 20px; text-align: right; border-bottom: 1px solid #F1F5F9;">
												<?php if ( $row->status === 'success' ) : ?>
													<span style="display: inline-flex; align-items: center; gap: 4px; color: #16A34A; font-size: 12px; font-weight: 500;">
														<i class="ph-fill ph-check-circle"></i> OK
													</span>
												<?php else : ?>
													<span style="display: inline-flex; align-items: center; gap: 4px; color: #DC2626; font-size: 12px; font-weight: 500;">
														<i class="ph-fill ph-warning-circle"></i> ERR
													</span>
												<?php endif; ?>
											</td>
										</tr>
									<?php endforeach; ?>
								</tbody>
							</table>
						</div>
					<?php else : ?>
						<div style="padding: 40px 20px; text-align: center;">
							<p style="color: #94A3B8; font-size: 13px; margin: 0;">No events logged.</p>
						</div>
					<?php endif; ?>
				</section>
				
			</div>
		</div>
	</div>
</div>
