<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.WP.EnqueuedResourceParameters
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.PreparedSQLPlaceholders
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable PluginCheck.Security.DirectDB
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum

/**
 * GT BOGO Engine — PDF Export (Enterprise) v3.12.0
 * Generates fully branded downloadable PDF campaign reports via jsPDF.
 * Sections: cover, KPIs, revenue trend chart, rule leaderboard,
 *           rules config, customer overview, audit log.
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_options' ) ) {
	return;
}

$is_pro       = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
$message      = '';
$message_type = '';

global $wpdb;
$rtbl = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_rules' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
$atbl = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_analytics' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
$ltbl = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_licenses' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
$ctbl = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_customers' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare

$rules = $rtbl ? $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}gtbogo_rules ORDER BY priority ASC, name ASC" ) : array(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare

// ── Date range ─────────────────────────────────────────────────────────────
$days_opt = isset( $_GET['pdf_days'] ) ? (int) $_GET['pdf_days'] : 30;
$days_opt = in_array( $days_opt, array( 7, 14, 30, 60, 90 ), true ) ? $days_opt : 30;
$start    = gmdate( 'Y-m-d H:i:s', strtotime( "-{$days_opt} days" ) );
$prev     = gmdate( 'Y-m-d H:i:s', strtotime( '-' . ( $days_opt * 2 ) . ' days' ) );

// ── Analytics ──────────────────────────────────────────────────────────────
$analytics_summary = array(
	'revenue'   => 0,
	'orders'    => 0,
	'discounts' => 0,
	'aov'       => 0,
);
$prev_summary      = array(
	'revenue' => 0,
	'orders'  => 0,
);
$daily_data        = array();
$top_rules_data    = array();
if ( $atbl ) {
	$analytics_summary = $wpdb->get_row(
		$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
			"SELECT COUNT(DISTINCT order_id) AS orders,
                COALESCE(SUM(order_total),0)    AS revenue,
                COALESCE(SUM(discount_amount),0) AS discounts,
                COALESCE(AVG(order_total),0)     AS aov
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s",
			$start
		),
		ARRAY_A
	) ?? $analytics_summary;
	$prev_summary      = $wpdb->get_row(
		$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
			"SELECT COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s AND date_created<%s",
			$prev,
			$start
		),
		ARRAY_A
	) ?? $prev_summary;
	$daily_data        = $wpdb->get_results(
		$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
			"SELECT DATE(date_created) AS d, COALESCE(SUM(order_total),0) AS revenue, COUNT(DISTINCT order_id) AS orders
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s GROUP BY DATE(date_created) ORDER BY d ASC LIMIT 90",
			$start
		)
	);
	$top_rules_data    = $wpdb->get_results(
		$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
			"SELECT COALESCE(r.name, CONCAT('Rule #',a.rule_id)) AS rule_name,
                r.pack_source,
                COUNT(DISTINCT a.order_id)        AS fires,
                COALESCE(SUM(a.order_total),0)    AS revenue,
                COALESCE(SUM(a.discount_amount),0) AS discount
         FROM {$wpdb->prefix}gtbogo_analytics a
         LEFT JOIN {$wpdb->prefix}gtbogo_rules r ON a.rule_id=r.id
         WHERE a.date_created>=%s GROUP BY a.rule_id ORDER BY fires DESC LIMIT 10",
			$start
		)
	);
}

// ── Customer / License stats ───────────────────────────────────────────────
$cust_total = $ctbl ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}gtbogo_customers" ) : 0; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
$cust_new   = $ctbl ? (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}gtbogo_customers WHERE first_purchase>=%s", $start ) ) : 0; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
$vip_count  = (int) get_transient( 'gtbogo_vip_count_cache' );
if ( ! $vip_count ) {
	$vip_count = (int) $wpdb->get_var(
		$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
			"SELECT COUNT(*) FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value != '' AND meta_value != 'none' AND meta_value != 'lapsed_vip'",
			'_gtbogo_vip_tier'
		)
	);
	if ( $vip_count > 0 ) {
		set_transient( 'gtbogo_vip_count_cache', $vip_count, 6 * HOUR_IN_SECONDS );
	}
}
$lic_active = $ltbl ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}gtbogo_licenses WHERE status='active' AND (expires_date IS NULL OR expires_date>UTC_TIMESTAMP())" ) : 0; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare

// ── Derived metrics ────────────────────────────────────────────────────────
$rev        = (float) ( $analytics_summary['revenue'] ?? 0 );
$disc       = (float) ( $analytics_summary['discounts'] ?? 0 );
$prev_rev   = (float) ( $prev_summary['revenue'] ?? 0 );
$efficiency = $rev > 0 ? round( ( ( $rev - $disc ) / $rev ) * 100, 1 ) : 0;
$rev_change = $prev_rev > 0 ? round( ( ( $rev - $prev_rev ) / $prev_rev ) * 100, 1 ) : ( $rev > 0 ? 100 : 0 );
$disc_pct   = $rev > 0 ? round( ( $disc / $rev ) * 100, 1 ) : 0;

// ── Daily chart arrays ─────────────────────────────────────────────────────
$chart_labels = array();
$chart_rev    = array();
$daily_map    = array();
foreach ( $daily_data as $row ) {
	$daily_map[ $row->d ] = $row; }
for ( $i = $days_opt - 1; $i >= 0; $i-- ) {
	$d              = gmdate( 'Y-m-d', strtotime( "-{$i} days" ) );
	$chart_labels[] = gmdate( 'M j', strtotime( $d ) );
	$chart_rev[]    = isset( $daily_map[ $d ] ) ? round( (float) $daily_map[ $d ]->revenue, 2 ) : 0;
}

// ── Rules breakdown ────────────────────────────────────────────────────────
$active_rules   = array_filter( $rules, fn( $r ) => $r->status === 'active' );
$inactive_rules = array_filter( $rules, fn( $r ) => $r->status !== 'active' );

// ── Audit log ──────────────────────────────────────────────────────────────
$audit_log    = get_option( 'gtbogo_audit_log', array() );
$audit_recent = array_slice( array_reverse( $audit_log ), 0, 25 );

// ── Save settings ──────────────────────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_save_pdf_settings'] ) && check_admin_referer( 'gtbogo_pdf_settings' ) ) {
	update_option(
		'gtbogo_pdf_settings',
		array(
			'company_name'      => sanitize_text_field( $_POST['company_name'] ?? get_bloginfo( 'name' ) ),
			'company_logo'      => esc_url_raw( $_POST['company_logo'] ?? '' ),
			'report_footer'     => sanitize_text_field( $_POST['report_footer'] ?? '' ),
			'include_rules'     => isset( $_POST['include_rules'] ),
			'include_analytics' => isset( $_POST['include_analytics'] ),
			'include_customers' => isset( $_POST['include_customers'] ),
			'include_roi'       => isset( $_POST['include_roi'] ),
			'include_audit'     => isset( $_POST['include_audit'] ),
			'accent_color'      => sanitize_hex_color( $_POST['accent_color'] ?? '#E10000' ),
			'watermark'         => isset( $_POST['watermark'] ),
			'report_title'      => sanitize_text_field( $_POST['report_title'] ?? 'Campaign Performance Report' ),
		)
	);
	$message      = 'Report settings saved.';
	$message_type = 'success';
}
$pdf_s  = get_option(
	'gtbogo_pdf_settings',
	array(
		'company_name'      => get_bloginfo( 'name' ),
		'company_logo'      => '',
		'report_footer'     => '',
		'include_rules'     => true,
		'include_analytics' => true,
		'include_customers' => true,
		'include_roi'       => true,
		'include_audit'     => false,
		'accent_color'      => '#E10000',
		'watermark'         => false,
		'report_title'      => 'Campaign Performance Report',
	)
);
$pdf_s += array(
	'include_customers' => true,
	'report_title'      => 'Campaign Performance Report',
);

// ── Email PDF AJAX handler ────────────────────────────────────────────────
add_action(
	'wp_ajax_gtbogo_email_pdf',
	function () {
		if ( ! current_user_can( 'manage_options' ) || ! check_ajax_referer( 'gtbogo_email_pdf', 'nonce', false ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorised.' ) );
			return;
		}
		$pdf_b64  = isset( $_POST['pdf'] ) ? sanitize_text_field( $_POST['pdf'] ) : '';
		$filename = sanitize_file_name( $_POST['filename'] ?? 'bogo-report.pdf' );
		if ( empty( $pdf_b64 ) ) {
			wp_send_json_error( array( 'message' => 'No PDF data received.' ) );
			return;
		}
		$pdf_data = base64_decode( preg_replace( '#^data:application/pdf;base64,#', '', $pdf_b64 ) );
		if ( ! $pdf_data ) {
			wp_send_json_error( array( 'message' => 'PDF decode failed.' ) );
			return;
		}
		$tmp = wp_tempnam( $filename );
		file_put_contents( $tmp, $pdf_data );

		$user        = wp_get_current_user();
		$to          = $user->user_email;
		$store_name  = get_bloginfo( 'name' );
		$report_date = gmdate( 'F j, Y' );
		$subject     = 'Campaign Report — ' . esc_html( $store_name ) . ' — ' . $report_date;

		// ── Branded HTML email ────────────────────────────────────────────────
		$bg1   = '#070C1C';
		$bg2   = '#0d1426';
		$bg3   = '#050a14';
		$acc   = '#E10000';
		$bdr   = '#0f1a30';
		$logo  = 'https://graphictshirts.shop/bogo/icon-256x256.png';
		$fname = esc_html( $user->display_name ?: $user->user_login );
		$sname = esc_html( $store_name );
		$surl  = esc_url( home_url() );

		$body = '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="x-apple-disable-message-reformatting">
<title>' . esc_html( $subject ) . '</title>
<!--[if mso]><xml><o:OfficeDocumentSettings><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml><![endif]-->
</head>
<body style="margin:0;padding:0;background-color:' . esc_html( $bg3 ) . ';font-family:\'Helvetica Neue\',Helvetica,Arial,sans-serif;">
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background-color:' . esc_html( $bg3 ) . ';padding:40px 0;">
<tr><td align="center">
<table role="presentation" cellpadding="0" cellspacing="0" width="600" style="max-width:600px;width:100%;">

  <!-- LOGO HEADER -->
  <tr><td style="background-color:' . esc_html( $bg1 ) . ';border-radius:12px 12px 0 0;border:1px solid ' . esc_html( $bdr ) . ';border-bottom:none;padding:32px 48px 24px;text-align:center;">
    <a href="https://graphictshirts.shop/bogo/" style="text-decoration:none;display:inline-block;">
      <table role="presentation" cellpadding="0" cellspacing="0" style="margin:0 auto 16px;">
        <tr>
          <td style="background-color:' . esc_html( $acc ) . ';border-radius:12px;padding:0;width:56px;height:56px;text-align:center;vertical-align:middle;">
            <img src="' . esc_html( $logo ) . '" alt="GT BOGO Engine" width="56" height="56" style="display:block;border-radius:12px;border:0;width:56px;height:56px;" />
          </td>
        </tr>
      </table>
      <div style="color:#ffffff;font-size:18px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;margin-bottom:4px;">GT BOGO ENGINE PRO</div>
      <div style="color:' . esc_html( $acc ) . ';font-size:10px;font-weight:600;letter-spacing:2px;text-transform:uppercase;">Campaign Performance Report</div>
    </a>
    <div style="height:1px;background:linear-gradient(90deg,' . esc_html( $bdr ) . ',' . $acc . ',' . esc_html( $bdr ) . ');margin:20px 0 0;"></div>
  </td></tr>

  <!-- INTRO -->
  <tr><td style="background-color:' . esc_html( $bg1 ) . ';border-left:1px solid ' . esc_html( $bdr ) . ';border-right:1px solid ' . esc_html( $bdr ) . ';padding:32px 48px;">
    <p style="color:#8899bb;font-size:13px;margin:0 0 8px;">Hi ' . esc_html( $fname ) . ',</p>
    <p style="color:#ffffff;font-size:20px;font-weight:700;margin:0 0 12px;line-height:1.3;">Your campaign report is ready.</p>
    <p style="color:#8899bb;font-size:14px;line-height:1.7;margin:0 0 24px;">Your GT BOGO Engine PRO performance report for <strong style="color:#c8cde0;">' . esc_html( $sname ) . '</strong> is attached as a PDF. It covers your active BOGO rules, revenue analytics, discount data, and campaign efficiency for the selected report period.</p>
    <table role="presentation" cellpadding="0" cellspacing="0" style="margin:0 0 24px;">
      <tr>
        <td style="background-color:' . esc_html( $bg2 ) . ';border:1px solid ' . esc_html( $bdr ) . ';border-radius:8px;padding:16px 20px;">
          <table role="presentation" cellpadding="0" cellspacing="0">
            <tr>
              <td style="padding-right:24px;">
                <div style="color:#4a6a8a;font-size:10px;font-weight:700;letter-spacing:1px;text-transform:uppercase;margin-bottom:4px;">Report Date</div>
                <div style="color:#ffffff;font-size:14px;font-weight:600;">' . esc_html( $report_date ) . '</div>
              </td>
              <td style="border-left:1px solid ' . esc_html( $bdr ) . ';padding-left:24px;">
                <div style="color:#4a6a8a;font-size:10px;font-weight:700;letter-spacing:1px;text-transform:uppercase;margin-bottom:4px;">Store</div>
                <div style="color:#ffffff;font-size:14px;font-weight:600;">' . esc_html( $sname ) . '</div>
              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
    <p style="color:#4a6a8a;font-size:12px;margin:0;">The PDF is attached to this email. Open it with any PDF viewer.</p>
  </td></tr>

  <!-- CTA -->
  <tr><td style="background-color:' . esc_html( $bg1 ) . ';border-left:1px solid ' . esc_html( $bdr ) . ';border-right:1px solid ' . esc_html( $bdr ) . ';padding:0 48px 32px;text-align:center;">
    <a href="' . esc_html( $surl ) . '/wp-admin/admin.php?page=gt-bogo-engine&tab=pdf-export" style="display:inline-block;padding:14px 40px;background-color:' . esc_html( $acc ) . ';color:#ffffff;text-decoration:none;font-size:12px;font-weight:700;letter-spacing:2px;text-transform:uppercase;border-radius:4px;">View PDF Export Page</a>
  </td></tr>

  <!-- DIVIDER -->
  <tr><td style="background-color:' . esc_html( $bg1 ) . ';border-left:1px solid ' . esc_html( $bdr ) . ';border-right:1px solid ' . esc_html( $bdr ) . ';padding:0 48px;">
    <div style="height:1px;background:' . esc_html( $bdr ) . ';"></div>
  </td></tr>

  <!-- FOOTER -->
  <tr><td style="background-color:' . esc_html( $bg1 ) . ';border-radius:0 0 12px 12px;border:1px solid ' . esc_html( $bdr ) . ';border-top:none;padding:24px 48px;text-align:center;">
    <p style="color:#4a6a8a;font-size:11px;margin:0 0 6px;">Powered by <a href="https://graphictshirts.shop/bogo/" style="color:' . esc_html( $acc ) . ';text-decoration:none;font-weight:700;">GT BOGO ENGINE PRO</a></p>
    <p style="color:#2a3a5a;font-size:11px;margin:0;">Built by <a href="https://graphictshirts.shop" style="color:#4a6a8a;text-decoration:none;font-weight:600;">GRAPHIC T-SHIRTS</a> &mdash; Luxury Urban Couture for the Bold</p>
  </td></tr>

</table>
</td></tr>
</table>
</body>
</html>';

		$headers = array(
			'Content-Type: text/html; charset=UTF-8',
			'From: GT BOGO Engine <bogo@graphictshirts.shop>',
			'Reply-To: support@graphictshirts.shop',
			'X-Mailer: GT BOGO Engine PRO',
		);

		$sent = wp_mail( $to, $subject, $body, $headers, array( $tmp ) );
		@wp_delete_file( $tmp );

		if ( $sent ) {
			wp_send_json_success( array( 'message' => 'Report sent to ' . esc_html( $to ) ) );
		} else {
			wp_send_json_error( array( 'message' => 'Mail failed. Check your WordPress SMTP settings.' ) );
		}
	}
);

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div id="gtb-pdfexport-content">
<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">📄 PDF Export</h1>
		<p class="gt-page-subtitle">Generate branded, downloadable campaign performance reports — rules, analytics, customers, and audit trail</p>
	</div>
	<div style="display:flex;gap:8px;align-items:center">
		<span class="gt-badge gt-badge-active"><?php echo esc_html( count( $rules ) ); ?> rules · <?php echo esc_html( count( $active_rules ) ); ?> active</span>
	</div>
</div>
<?php
if ( $message ) :
	?>
	<div class="gt-notice gt-notice-<?php echo esc_attr( $message_type ); ?> gt-animate-in">✓ <?php echo esc_html( $message ); ?></div><?php endif; ?>

<?php if ( ! $is_pro ) : ?>
<div class="gt-pro-gate gt-animate-in">
	<span class="gt-pro-gate-icon">📄</span>
	<h2>PRO License Required</h2>
	<p>PDF Export generates professional, downloadable campaign reports with your branding — shareable with clients, stakeholders, or archived for compliance.</p>
	<div style="margin-top:24px;display:flex;justify-content:center">
		<a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO — $499/yr</a>
	</div>
</div>
<?php else : ?>

<!-- KPI METRICS -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:20px;grid-template-columns:repeat(6,1fr)">
	<?php
	$pct_arrow = fn( $v ) => ( $v >= 0 ? '▲ ' : '▼ ' ) . abs( $v ) . '%';
	$pct_col   = fn( $v ) => $v >= 0 ? '#22c55e' : '#ef4444';
	foreach ( array(
		array( 'Revenue', '$' . number_format( $rev, 0 ), $pct_arrow( $rev_change ), $pct_col( $rev_change ), '#E10000' ),
		array( 'BOGO Orders', number_format( $analytics_summary['orders'] ?? 0 ), 'Last ' . $days_opt . 'd', '#94a3b8', '#3b82f6' ),
		array( 'Discounts', '$' . number_format( $disc, 0 ), $disc_pct . '% of rev', '#94a3b8', '#f59e0b' ),
		array( 'Efficiency', $efficiency . '%', $efficiency >= 80 ? 'On target' : 'Review deals', '#94a3b8', '#22c55e' ),
		array( 'Customers', number_format( $cust_total ), $cust_new . ' new this period', '#94a3b8', '#8b5cf6' ),
		array( 'Active Rules', count( $active_rules ) . ' / ' . count( $rules ), count( $inactive_rules ) . ' inactive', '#94a3b8', '#06b6d4' ),
	) as $m ) :
		?>
	<div class="gt-metric" style="--gt-metric-c:<?php echo esc_html( $m[4] ); ?>">
		<div class="gt-metric-label"><?php echo esc_html( $m[0] ); ?></div>
		<div class="gt-metric-value" style="font-size:18px"><?php echo esc_html( $m[1] ); ?></div>
		<div class="gt-metric-trend" style="color:<?php echo esc_html( $m[3] ); ?>"><?php echo esc_html( $m[2] ); ?></div>
	</div>
	<?php endforeach; ?>
</div>

<div style="display:grid;grid-template-columns:280px 1fr;gap:20px;margin-bottom:20px">

<!-- SETTINGS PANEL -->
<div class="gt-card gt-animate-in" style="align-self:start">
	<div class="gt-card-header"><h2 class="gt-card-title">⚙️ Report Settings</h2></div>
	<form method="post">
		<?php wp_nonce_field( 'gtbogo_pdf_settings' ); ?>
		<div class="gt-form-group">
			<label class="gt-form-label">Report Title</label>
			<input type="text" name="report_title" class="gt-input" value="<?php echo esc_attr( $pdf_s['report_title'] ); ?>" id="gtbogo_report_title" aria-label="Report Title">
		</div>
		<div class="gt-form-group">
			<label class="gt-form-label">Company / Store Name</label>
			<input type="text" name="company_name" class="gt-input" value="<?php echo esc_attr( $pdf_s['company_name'] ); ?>" id="gtbogo_company_name" aria-label="Company Name">
		</div>
		<div class="gt-form-group">
			<label class="gt-form-label">Logo URL</label>
			<input type="url" name="company_logo" class="gt-input" value="<?php echo esc_attr( $pdf_s['company_logo'] ); ?>" placeholder="https://..." id="gtbogo_company_logo" aria-label="Company Logo">
			<div class="gt-form-hint">PNG or JPG, publicly accessible</div>
		</div>
		<div class="gt-form-group">
			<label class="gt-form-label">Footer Text</label>
			<input type="text" name="report_footer" class="gt-input" value="<?php echo esc_attr( $pdf_s['report_footer'] ); ?>" placeholder="Confidential — Internal Use Only" id="gtbogo_report_footer" aria-label="Report Footer">
		</div>
		<div class="gt-form-group">
			<label class="gt-form-label">Accent Colour</label>
			<div style="display:flex;align-items:center;gap:10px">
				<input type="color" name="accent_color" value="<?php echo esc_attr( $pdf_s['accent_color'] ); ?>" style="width:44px;height:34px;border:none;border-radius:6px;cursor:pointer;background:none" id="gtbogo_accent_color" aria-label="Accent Color">
				<input type="text" id="gtbogo_accent_preview" aria-label="Accent color preview" class="gt-input" style="width:90px" value="<?php echo esc_attr( $pdf_s['accent_color'] ); ?>" oninput="document.querySelector('[name=accent_color]').value=this.value">
			</div>
		</div>
		<div style="font-size:11px;font-weight:800;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:1px;margin:12px 0 8px">Include Sections</div>
		<?php
		foreach ( array(
			array( 'include_analytics', '📈 Analytics Summary', true ),
			array( 'include_roi', '🏆 Rule Leaderboard', true ),
			array( 'include_rules', '📋 Rules Configuration', true ),
			array( 'include_customers', '👥 Customer Overview', true ),
			array( 'include_audit', '🔍 Audit Log', false ),
			array( 'watermark', '🔒 Confidential Watermark', false ),
		) as $s ) :
			?>
		<div class="gt-setting-row" style="padding:7px 0;border-bottom:1px solid var(--gt-border)">
			<div class="gt-setting-label" style="font-size:13px"><?php echo esc_html( $s[1] ); ?></div>
			<label class="gt-toggle"><input type="checkbox" name="<?php echo esc_html( $s[0] ); ?>" value="1" <?php checked( ! empty( $pdf_s[ $s[0] ] ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
		</div>
		<?php endforeach; ?>
		<button type="submit" name="gtbogo_save_pdf_settings" class="gt-btn gt-btn-primary" style="width:100%;margin-top:14px">💾 Save Settings</button>
	</form>
</div>

<!-- REPORT AREA -->
<div>
	<!-- Period + Download Bar -->
	<div class="gt-card gt-animate-in" style="margin-bottom:16px">
		<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:12px">
			<div style="display:flex;gap:8px;flex-wrap:wrap">
				<?php
				foreach ( array(
					7  => '7 Days',
					14 => '14 Days',
					30 => '30 Days',
					60 => '60 Days',
					90 => '90 Days',
				) as $d => $l ) :
					?>
				<a href="?page=gt-bogo-engine&tab=pdf-export&pdf_days=<?php echo esc_html( $d ); ?>" class="gt-btn <?php echo $days_opt === $d ? 'gt-btn-primary' : 'gt-btn-ghost'; ?> gt-btn-sm gtb-inline-link"><?php echo esc_html( $l ); ?></a>
				<?php endforeach; ?>
			</div>
			<div style="display:flex;gap:10px">
				<button onclick="window.print()" class="gt-btn gt-btn-ghost gt-btn-sm">🖨 Print</button>
				<button id="gtb-download-pdf" onclick="generatePDF()" class="gt-btn gt-btn-primary" style="padding:10px 24px;font-size:14px;font-weight:700">⬇ Download PDF</button>
				<button id="gtb-email-pdf" onclick="emailPDF()" class="gt-btn gt-btn-ghost" style="padding:10px 20px;font-size:14px">✉ Email to Me</button>
			</div>
		</div>
	</div>

</div><!-- end right column -->
</div><!-- end grid -->

<!-- GUIDE -->
<div class="gt-card gt-animate-in" style="background:linear-gradient(135deg,rgba(59,130,246,0.06),transparent);border-color:rgba(59,130,246,0.15)">
	<div class="gt-card-header"><h2 class="gt-card-title">🧠 Usage Guide</h2></div>
	<div class="gt-feature-grid gt-feature-grid--2col">
		<?php
		foreach ( array(
			array( 'Download PDF', 'Click "Download PDF" to generate and download a .pdf file directly — no server processing, no print dialog. Works in Chrome, Edge, and Firefox.' ),
			array( 'Monthly Client Reports', 'Generate on the 1st of each month at Last 30 Days. Save as CLIENT_BOGO_Report_YYYY_MM.pdf alongside your WooCommerce performance summary.' ),
			array( 'Stakeholder Presentations', 'Enable Audit Log for accountability — every rule activation and change is timestamped, demonstrating controlled, deliberate campaign management.' ),
			array( 'Compliance Archiving', 'Archive quarterly for regulated markets. The report documents active rules, discount amounts, and a full audit trail meeting most promotional compliance requirements.' ),
		) as $g ) :
			?>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px"><?php echo esc_html( $g[0] ); ?></div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7"><?php echo esc_html( $g[1] ); ?></div></div>
		<?php endforeach; ?>
	</div>
</div>

<?php endif; // PRO ?>
</div><!-- #gtb-pdfexport-content -->

<style>
@media print {
	#adminmenumain,#wpadminbar,#wpfooter,.gt-page-header,.gt-metrics,
	.gt-card:not(#gt-pdf-report),#gt-pdf-report .gt-card-header { display:none !important; }
	#gt-pdf-report,#gt-report-body { border:none !important; box-shadow:none !important; padding:0 !important; }
	body { background:#fff !important; }
	* { -webkit-print-color-adjust:exact !important; print-color-adjust:exact !important; }
	<?php if ( ! empty( $pdf_s['watermark'] ) ) : ?>
	#gt-report-body::before { content:"CONFIDENTIAL"; position:fixed; top:50%; left:50%; transform:translate(-50%,-50%) rotate(-45deg); font-size:72px; font-weight:900; letter-spacing:8px; color:rgba(0,0,0,0.05); pointer-events:none; z-index:9999; white-space:nowrap; }
	<?php endif; ?>
}
</style>

<?php
$_pi = array(
	'page'              => __( 'Page', 'gt-bogo-engine' ),
	'confidential'      => __( gtBogoPdfI18n . confidential, 'gt-bogo-engine' ), // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
	'report_period'     => __( gtBogoPdfI18n . report_period, 'gt-bogo-engine' ), // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
	'last_days'         => sprintf( // translators: %d is the number of days.
		__( 'Last %d days', 'gt-bogo-engine' ),
		$days_opt
	),
	'report_dot'        => __( 'Report', 'gt-bogo-engine' ),
	'daily_revenue'     => sprintf( // translators: %d is the number of days.
		__( 'Daily Revenue - Last %d Days', 'gt-bogo-engine' ),
		$days_opt
	),
	'campaign_summary'  => __( 'Campaign Performance Summary', 'gt-bogo-engine' ),
	'rule_leaderboard'  => __( 'Rule Performance Leaderboard', 'gt-bogo-engine' ),
	'rules_config'      => __( 'Rules Configuration', 'gt-bogo-engine' ),
	'active'            => __( 'Active', 'gt-bogo-engine' ),
	'total'             => __( 'Total', 'gt-bogo-engine' ),
	'customer_overview' => __( 'Customer Overview', 'gt-bogo-engine' ),
	'audit_log'         => __( 'Audit Log', 'gt-bogo-engine' ),
	'events'            => __( 'Events', 'gt-bogo-engine' ),
	'revenue'           => __( 'Revenue', 'gt-bogo-engine' ),
	'orders'            => __( 'Orders', 'gt-bogo-engine' ),
	'discounts'         => __( 'Discounts', 'gt-bogo-engine' ),
	'active_rules'      => __( 'Active Rules', 'gt-bogo-engine' ),
	'aov'               => __( 'AOV', 'gt-bogo-engine' ),
	'slogan'            => __( 'Luxury Urban Couture for the Bold', 'gt-bogo-engine' ),
	'days_opt'          => (int) $days_opt,
	'active_count'      => (int) count( $active_rules ),
	'total_count'       => (int) count( $rules ?? array() ),
	'audit_count'       => (int) count( $audit_recent ?? array() ),
	'report_date'       => date_i18n( get_option( 'date_format' ) ),
);
?>
<script>var gtBogoPdfI18n = <?php echo wp_json_encode( $_pi, JSON_UNESCAPED_UNICODE ); ?>;</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script> <?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript, PluginCheck.CodeAnalysis.Offloading.OffloadedContent ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.31/jspdf.plugin.autotable.min.js"></script> <?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript, PluginCheck.CodeAnalysis.Offloading.OffloadedContent ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@5.0.0/dist/chart.umd.min.js"></script> <?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript, PluginCheck.CodeAnalysis.Offloading.OffloadedContent ?>
<script>
(function() {
	var labels  = <?php echo wp_json_encode( array_values( $chart_labels ) ); ?>;
	var revData = <?php echo wp_json_encode( array_values( $chart_rev ) ); ?>;
	var accent  = '<?php echo esc_js( $pdf_s['accent_color'] ); ?>';
	var chartConfig = {
		type:'bar',
		data:{ labels:labels, datasets:[{ data:revData, backgroundColor:accent+'99', borderColor:accent, borderWidth:1, borderRadius:2 }] },
		options:{ responsive:true, animation:false, plugins:{legend:{display:false}},
			scales:{ x:{ticks:{color:'#9ca3af',font:{size:10},maxTicksLimit:12},grid:{display:false}},
					y:{ticks:{color:'#9ca3af',callback:function(v){return '$'+v.toLocaleString();}},grid:{color:'#f3f4f6'},beginAtZero:true} } }
	};
	var prev = document.getElementById('gtb-preview-chart');
	if (prev) new Chart(prev, JSON.parse(JSON.stringify(chartConfig)));
	var hidden = document.getElementById('gtb-pdf-chart-canvas');
	if (hidden) { hidden.style.display='block'; new Chart(hidden, JSON.parse(JSON.stringify(chartConfig))); }
})();

function generatePDF() {
	var btn = document.getElementById('gtb-download-pdf');
	if (btn) { btn.textContent='⏳ Generating…'; btn.disabled=true; }
	setTimeout(function() {
		try { _buildPDF(); }
		catch(e) { console.error('PDF error:',e); alert('PDF generation failed. Use the Print button as a fallback.'); }
		finally { if(btn){btn.textContent='⬇ Download PDF';btn.disabled=false;} }
	}, 150);
}

function emailPDF() {
	var btn = document.getElementById('gtb-email-pdf');
	if (btn) { btn.textContent='⏳ Generating…'; btn.disabled=true; }
	setTimeout(function() {
		try {
			var jsPDF = window.jspdf.jsPDF;
			// Build a temporary doc just to get the base64 — reuse _buildPDF logic via flag
			_buildPDF('email');
		} catch(e) {
			console.error('Email PDF error:', e);
			alert('PDF generation failed.');
			if (btn) { btn.textContent='✉ Email to Me'; btn.disabled=false; }
		}
	}, 150);
}

function _buildPDF(mode) {
	var jsPDF = window.jspdf.jsPDF;
	var doc   = new jsPDF({orientation:'portrait',unit:'mm',format:'a4'});
	var ah    = '<?php echo esc_js( $pdf_s['accent_color'] ); ?>';
	var aR=parseInt(ah.slice(1,3),16)||225, aG=parseInt(ah.slice(3,5),16)||0, aB=parseInt(ah.slice(5,7),16)||0;
	var W=210, H=297, M=15, y=M;
	var footer_text = <?php echo wp_json_encode( $pdf_s['report_footer'] ?: $pdf_s['company_name'] . ' — GT BOGO Engine PRO' ); ?>;
	var company     = <?php echo wp_json_encode( $pdf_s['company_name'] ); ?>;
	var rptTitle    = <?php echo wp_json_encode( $pdf_s['report_title'] ); ?>;
	var watermark   = <?php echo ! empty( $pdf_s['watermark'] ) ? 'true' : 'false'; ?>;

	function addFooter() {
		var pn = doc.internal.getNumberOfPages();
		// Dark footer band
		doc.setFillColor(7,12,28); doc.rect(0,H-14,W,14,'F');
		doc.setFillColor(aR,aG,aB); doc.rect(0,H-14,W,0.5,'F');
		// Left: custom footer text
		doc.setFontSize(7); doc.setFont('helvetica','normal'); doc.setTextColor(100,110,130);
		doc.text(footer_text, M, H-6);
		// Centre: GRAPHIC T-SHIRTS branding
		doc.setFontSize(7); doc.setFont('helvetica','bold'); doc.setTextColor(aR,aG,aB);
		var gtsLabel = 'GRAPHIC T-SHIRTS';
		var gtsW = doc.getTextWidth(gtsLabel);
		var slogan = '  ·  '+gtBogoPdfI18n.slogan;
		var gtsCx = W/2 - (gtsW + doc.getTextWidth(slogan))/2;
		doc.text(gtsLabel, gtsCx, H-6);
		doc.link(gtsCx-1, H-12, gtsW+2, 8, {url:'https://graphictshirts.shop'});
		doc.setFont('helvetica','normal'); doc.setTextColor(160,165,180);
		doc.text(slogan, gtsCx + gtsW, H-6);
		// Right: page number
		doc.setFontSize(7); doc.setTextColor(100,110,130);
		doc.text(gtBogoPdfI18n.page+' '+pn, W-M, H-6, {align:'right'});
		// Watermark
		if (watermark) {
			doc.setFontSize(52); doc.setTextColor(30,35,55);
			doc.text('CONFIDENTIAL',W/2,H/2,{align:'center',angle:45});
		}
	}
	// ── Page header for all non-cover pages ─────────────────────────────────
	function addPageHeader() {
		// Full navy page background
		doc.setFillColor(7,12,28); doc.rect(0,0,W,H,'F');
		// Red header band on top
		doc.setFillColor(aR,aG,aB); doc.rect(0,0,W,11,'F');
		// GT logo mark — small white square
		doc.setFillColor(255,255,255); doc.roundedRect(M,1.5,8,8,0.5,0.5,'F');
		doc.setFontSize(5.5); doc.setFont('helvetica','bold'); doc.setTextColor(aR,aG,aB);
		doc.text('GT',M+4,7.2,{align:'center'});
		// GT BOGO ENGINE PRO
		doc.setFontSize(8); doc.setFont('helvetica','bold'); doc.setTextColor(255,255,255);
		doc.text('GT BOGO ENGINE PRO', M+11, 7.5);
		doc.link(M-1,0,doc.getTextWidth('GT BOGO ENGINE PRO')+16,11,{url:'https://graphictshirts.shop/bogo/'});
		// Sales page link right
		doc.setFont('helvetica','normal'); doc.setFontSize(6.5); doc.setTextColor(255,220,220);
		doc.text('graphictshirts.shop/bogo', W-M, 7.5, {align:'right'});
		doc.link(W-M-doc.getTextWidth('graphictshirts.shop/bogo')-2,0,doc.getTextWidth('graphictshirts.shop/bogo')+4,11,{url:'https://graphictshirts.shop/bogo/'});
	}
	function checkY(n) { if(y+n>H-20){addFooter();doc.addPage();addPageHeader();y=M+14;} }
	function sectionHdr(t) {
		checkY(16);
		doc.setFontSize(9.5); doc.setFont('helvetica','bold'); doc.setTextColor(255,255,255);
		doc.text(t.toUpperCase(),M,y);
		doc.setDrawColor(aR,aG,aB); doc.setLineWidth(0.6); doc.line(M,y+2,W-M,y+2);
		doc.setDrawColor(20,28,55); y+=10;
	}

	// ── COVER ──────────────────────────────────────────────────────────────
	// Full navy background
	doc.setFillColor(7,12,28); doc.rect(0,0,W,H,'F');
	// Red top stripe
	doc.setFillColor(aR,aG,aB); doc.rect(0,0,W,3,'F');
	// Subtle grid pattern (decorative dots)
	doc.setFillColor(15,22,50);
	for(var gx=0;gx<W;gx+=12){for(var gy=3;gy<H-20;gy+=12){doc.circle(gx,gy,0.3,'F');}}
	// GT logo mark — centered white square
	var lx=W/2-16, ly=72;
	doc.setFillColor(255,255,255); doc.roundedRect(lx,ly,32,32,3,3,'F');
	doc.setFontSize(17); doc.setFont('helvetica','bold'); doc.setTextColor(aR,aG,aB);
	doc.text('GT',W/2,ly+21,{align:'center'});
	// GT BOGO ENGINE PRO — centred
	doc.setFontSize(18); doc.setFont('helvetica','bold'); doc.setTextColor(255,255,255);
	doc.text('GT BOGO ENGINE PRO',W/2,122,{align:'center'});
	doc.link(W/2-50,115,100,10,{url:'https://graphictshirts.shop/bogo/'});
	// Red divider
	doc.setFillColor(aR,aG,aB); doc.rect(W/2-25,127,50,0.8,'F');
	// Report title in accent red
	doc.setFontSize(9); doc.setFont('helvetica','bold'); doc.setTextColor(aR,aG,aB);
	doc.text(rptTitle.toUpperCase(),W/2,136,{align:'center'});
	// "for [store name]" — white, large
	doc.setFontSize(16); doc.setFont('helvetica','bold'); doc.setTextColor(255,255,255);
	var compLines = doc.splitTextToSize('for '+company, W-M*4);
	doc.text(compLines, W/2, 148, {align:'center'});
	// Generated date — muted
	doc.setFontSize(9); doc.setFont('helvetica','normal'); doc.setTextColor(100,110,140);
	doc.text(gtBogoPdfI18n.report_dot+' · '+gtBogoPdfI18n.report_date, W/2, 158+(compLines.length-1)*8, {align:'center'});
	// Period box — lighter navy card
	var py = 168+(compLines.length-1)*8;
	doc.setFillColor(13.23.32); doc.roundedRect(M,py,W-M*2,28,3,3,'F');
	doc.setDrawColor(30,40,80); doc.setLineWidth(0.4); doc.roundedRect(M,py,W-M*2,28,3,3,'S');
	doc.setFontSize(8); doc.setFont('helvetica','bold'); doc.setTextColor(aR,aG,aB);
	doc.text('REPORT PERIOD',W/2,py+10,{align:'center'});
	doc.setFont('helvetica','normal'); doc.setTextColor(200,205,220); doc.setFontSize(10);
	doc.text(gtBogoPdfI18n.last_days,W/2,py+19,{align:'center'});
	doc.setFontSize(8); doc.setTextColor(80,90,120);
	doc.text('<?php echo esc_js( home_url() ); ?>',W/2,py+26,{align:'center'});
	// Bottom: GT BOGO branding band
	doc.setFillColor(aR,aG,aB); doc.rect(0,H-22,W,22,'F');
	doc.setFontSize(10); doc.setFont('helvetica','bold'); doc.setTextColor(255,255,255);
	doc.text('GT BOGO ENGINE PRO',W/2,H-13,{align:'center'});
	doc.link(W/2-40,H-22,80,22,{url:'https://graphictshirts.shop/bogo/'});
	doc.setFontSize(7.5); doc.setFont('helvetica','normal'); doc.setTextColor(255,220,220);
	doc.text('graphictshirts.shop/bogo',W/2,H-6,{align:'center'});
	// No addFooter() on cover — it has its own bottom band

	// ── ANALYTICS SUMMARY ─────────────────────────────────────────────────
	<?php if ( ! empty( $pdf_s['include_analytics'] ) ) : ?>
	doc.addPage(); addPageHeader(); y=M+14;
	sectionHdr(gtBogoPdfI18n.campaign_summary);
	var kpis=[
		['Revenue Influenced','$<?php echo esc_html( number_format( $rev, 2 ) ); ?>','<?php echo esc_html( ( $rev_change >= 0 ? '+' : '' ) . $rev_change ); ?>% vs prior period'],
		['BOGO Orders','<?php echo esc_html( number_format( $analytics_summary['orders'] ?? 0 ) ); ?>','Last <?php echo esc_html( $days_opt ); ?> days'],
		['Discounts Given','$<?php echo esc_html( number_format( $disc, 2 ) ); ?>','<?php echo esc_html( $disc_pct ); ?>% of revenue'],
		['Avg Order Value','$<?php echo esc_html( number_format( $analytics_summary['aov'] ?? 0, 2 ) ); ?>','BOGO orders only'],
		['Efficiency Score','<?php echo esc_html( $efficiency ); ?>%','<?php echo $efficiency >= 80 ? 'On target' : ( $efficiency >= 60 ? 'Review deals' : 'Adjust strategy' ); ?>'],
		['Active Rules','<?php echo esc_html( count( $active_rules ) ); ?> / <?php echo esc_html( count( $rules ) ); ?>','<?php echo esc_html( count( $inactive_rules ) ); ?> inactive'],
	];
	var bW=(W-M*2-10)/3, bH=22;
	kpis.forEach(function(k,i){
		var col=i%3,row=Math.floor(i/3),bx=M+col*(bW+5),by=y+row*(bH+5);
		doc.setFillColor(13.23.32); doc.roundedRect(bx,by,bW,bH,2,2,'F');
		doc.setDrawColor(30,40,80); doc.setLineWidth(0.3); doc.roundedRect(bx,by,bW,bH,2,2,'S');
		doc.setFontSize(7); doc.setFont('helvetica','bold'); doc.setTextColor(80,90,130);
		doc.text(k[0].toUpperCase(),bx+4,by+8);
		doc.setFontSize(12); doc.setFont('helvetica','bold'); doc.setTextColor(255,255,255);
		doc.text(k[1],bx+4,by+17);
		doc.setFontSize(7); doc.setFont('helvetica','normal'); doc.setTextColor(aR,aG,aB);
		doc.text(k[2],bx+bW-4,by+8,{align:'right'});
	});
	y+=2*(bH+5)+8;
	// Chart
	var cv=document.getElementById('gtb-pdf-chart-canvas');
	if(cv){try{var img=cv.toDataURL('image/png'); checkY(55);
		doc.setFontSize(9);doc.setFont('helvetica','bold');doc.setTextColor(180,185,210);
		doc.text(gtBogoPdfI18n.daily_revenue,M,y);y+=4;
		doc.setFillColor(13.23.32);doc.roundedRect(M,y,W-M*2,48,2,2,'F');doc.setDrawColor(30,40,80);doc.setLineWidth(0.3);doc.roundedRect(M,y,W-M*2,48,2,2,'S');
		doc.addImage(img,'PNG',M+2,y+2,W-M*2-4,44);y+=52;
	}catch(e){}}
	addFooter();
	<?php endif; ?>

	// ── RULE LEADERBOARD ───────────────────────────────────────────────────
	<?php if ( ! empty( $pdf_s['include_roi'] ) && ! empty( $top_rules_data ) ) : ?>
	doc.addPage(); addPageHeader(); y=M+14;
	sectionHdr(gtBogoPdfI18n.rule_leaderboard);
	var lbBody=
		<?php
		$rows = array();
		foreach ( $top_rules_data as $i => $tr ) {
			$eff    = $tr->revenue > 0 ? round( ( ( $tr->revenue - $tr->discount ) / $tr->revenue ) * 100, 1 ) : 0;
			$rows[] = array( strval( $i + 1 ), $tr->rule_name . ( $tr->pack_source ? ' [' . $tr->pack_source . ']' : '' ), number_format( $tr->fires ), '$' . number_format( $tr->revenue, 2 ), '-$' . number_format( $tr->discount, 2 ), $eff . '%' );
		}
		echo wp_json_encode( $rows );
		?>
	;
	doc.autoTable({startY:y,head:[['#','Rule','Fires','Revenue','Discount','Efficiency']],body:lbBody,theme:'striped',
		headStyles:{fillColor:[aR,aG,aB],fontStyle:'bold',fontSize:9,textColor:[255,255,255]},bodyStyles:{fontSize:9,fillColor:[13.23.32],textColor:[210,215,230]},alternateStyles:{fillColor:[7,12,28]},
		columnStyles:{0:{cellWidth:8,halign:'center'},2:{halign:'right'},3:{halign:'right',textColor:[21,128,61]},4:{halign:'right',textColor:[220,38,38]},5:{halign:'right',fontStyle:'bold'}},
		margin:{left:M,right:M}});
	y=doc.lastAutoTable.finalY+10; addFooter();
	<?php endif; ?>

	// ── RULES CONFIGURATION ────────────────────────────────────────────────
	<?php if ( ! empty( $pdf_s['include_rules'] ) && ! empty( $rules ) ) : ?>
	doc.addPage(); addPageHeader(); y=M+14;
	sectionHdr(gtBogoPdfI18n.rules_config+' — '+gtBogoPdfI18n.active_count+' '+gtBogoPdfI18n.active+' / '+gtBogoPdfI18n.total_count+' '+gtBogoPdfI18n.total);
	var rulesBody=
		<?php
		$rows = array();
		foreach ( $rules as $r ) {
			$rows[] = array( $r->name . ( $r->pack_source ? ' [' . $r->pack_source . ']' : '' ), $r->type ?? 'bogo', strval( $r->buy_quantity ), strval( $r->get_quantity ), $r->discount_value == 100 ? 'FREE' : $r->discount_value . '%', strval( $r->priority ), ucfirst( $r->status ) );
		}
		echo wp_json_encode( $rows );
		?>
	;
	doc.autoTable({startY:y,head:[['Rule Name','Type','Buy','Get','Discount','Priority','Status']],body:rulesBody,theme:'striped',
		headStyles:{fillColor:[aR,aG,aB],fontStyle:'bold',fontSize:8.5,textColor:[255,255,255]},bodyStyles:{fontSize:8.5,fillColor:[13.23.32],textColor:[210,215,230]},alternateStyles:{fillColor:[7,12,28]},
		columnStyles:{1:{halign:'center',cellWidth:20},2:{halign:'center',cellWidth:12},3:{halign:'center',cellWidth:12},4:{halign:'center',cellWidth:20},5:{halign:'center',cellWidth:16},6:{halign:'center',cellWidth:18}},
		margin:{left:M,right:M}});
	y=doc.lastAutoTable.finalY+10; addFooter();
	<?php endif; ?>

	// ── CUSTOMER OVERVIEW ──────────────────────────────────────────────────
	<?php if ( ! empty( $pdf_s['include_customers'] ) ) : ?>
	checkY(50); sectionHdr(gtBogoPdfI18n.customer_overview);
	var ck=[['Total Customers','<?php echo esc_html( number_format( $cust_total ) ); ?>'],['New This Period','<?php echo esc_html( number_format( $cust_new ) ); ?>'],['VIP Members','<?php echo esc_html( number_format( $vip_count ) ); ?>'],['Active Licenses','<?php echo esc_html( number_format( $lic_active ) ); ?>']];
	var ckW=(W-M*2-15)/4;
	ck.forEach(function(k,i){
		var bx=M+i*(ckW+5);
		doc.setFillColor(13.23.32);doc.roundedRect(bx,y,ckW,22,2,2,'F');
		doc.setDrawColor(30,40,80);doc.setLineWidth(0.3);doc.roundedRect(bx,y,ckW,22,2,2,'S');
		doc.setFontSize(7);doc.setFont('helvetica','bold');doc.setTextColor(80,90,130);
		doc.text(k[0].toUpperCase(),bx+4,y+9);
		doc.setFontSize(13);doc.setFont('helvetica','bold');doc.setTextColor(255,255,255);
		doc.text(k[1],bx+4,y+19);
	});
	y+=30; addFooter();
	<?php endif; ?>

	// ── AUDIT LOG ──────────────────────────────────────────────────────────
	<?php if ( ! empty( $pdf_s['include_audit'] ) && ! empty( $audit_recent ) ) : ?>
	doc.addPage(); addPageHeader(); y=M+14;
	sectionHdr(gtBogoPdfI18n.audit_log+' — '+gtBogoPdfI18n.audit_count+' '+gtBogoPdfI18n.events);
	var auditBody=
		<?php
		$rows = array();
		foreach ( $audit_recent as $e ) {
			$rows[] = array( $e['time'], $e['user'], $e['action'], mb_strimwidth( $e['detail'], 0, 50, '…' ), strtoupper( $e['level'] ) );
		}
		echo wp_json_encode( $rows );
		?>
	;
	doc.autoTable({startY:y,head:[['Time','User','Action','Detail','Level']],body:auditBody,theme:'striped',
		headStyles:{fillColor:[aR,aG,aB],fontStyle:'bold',fontSize:8,textColor:[255,255,255]},bodyStyles:{fontSize:8,fillColor:[13.23.32],textColor:[210,215,230]},alternateStyles:{fillColor:[7,12,28]},
		columnStyles:{0:{cellWidth:32},1:{cellWidth:22},4:{halign:'center',cellWidth:14,fontStyle:'bold'}},
		margin:{left:M,right:M}});
	addFooter();
	<?php endif; ?>

	// ── SAVE or EMAIL ──────────────────────────────────────────────────────
	var slug=company.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'');
	var filename = slug+'-bogo-report-<?php echo esc_js( gmdate( 'Y-m-d' ) ); ?>.pdf';
	if (mode === 'email') {
		var pdfBase64 = doc.output('datauristring');
		var btn = document.getElementById('gtb-email-pdf');
		var data = new FormData();
		data.append('action',   'gtbogo_email_pdf');
		data.append('nonce',    '<?php echo esc_js( wp_create_nonce( 'gtbogo_email_pdf' ) ); ?>');
		data.append('pdf',      pdfBase64);
		data.append('filename', filename);
		fetch('<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>', {method:'POST', body:data, credentials:'same-origin'})
			.then(function(r){return r.json();})
			.then(function(res){
				if (res.success) {
					alert(res.data.message);
				} else {
					alert('Error: '+(res.data ? res.data.message : 'Unknown error'));
				}
			})
			.catch(function(e){ alert('Request failed: '+e); })
			.finally(function(){
				if (btn) { btn.textContent='✉ Email to Me'; btn.disabled=false; }
			});
	} else {
		doc.save(filename);
	}
}

// ── Inline nav ──────────────────────────────────────────────────────────────
(function(){
	var cid='gtb-pdfexport-content';
	function markLinks(root){
		(root||document).querySelectorAll('a[href*="tab=pdf-export"]').forEach(function(a){
			if(/pdf_days/.test(a.getAttribute('href')||'')) a.classList.add('gtb-inline-link');
		});
	}
	markLinks();
	document.addEventListener('click',function(e){
		var link=e.target.closest('a.gtb-inline-link');
		if(!link) return;
		var href=link.getAttribute('href')||'';
		if(!href||href.charAt(0)==='#') return;
		e.preventDefault();
		var content=document.getElementById(cid);
		if(!content){window.location.href=href;return;}
		content.style.opacity='0.5';content.style.transition='opacity 0.1s ease';
		fetch(href,{credentials:'same-origin'}).then(function(r){return r.text();}).then(function(html){
			var d2=new DOMParser().parseFromString(html,'text/html');
			var nc=d2.getElementById(cid);
			if(nc){content.innerHTML=nc.innerHTML;content.style.opacity='1';history.pushState(null,'',href);markLinks(content);}
			else{window.location.href=href;}
		}).catch(function(){window.location.href=href;});
	});
})();
</script>
<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
