<?php
/**
 * GT BOGO Engine — PDF Export (Enterprise)
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
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'));
$atbl = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->prefix.'gtbogo_analytics'));

$rules = $rtbl ? $wpdb->get_results("SELECT * FROM {$wpdb->prefix}gtbogo_rules ORDER BY priority DESC, name ASC") : [];

// Analytics for the report
$days_opt = isset($_GET['pdf_days']) ? (int)$_GET['pdf_days'] : 30;
$days_opt = in_array($days_opt,[7,14,30,60,90],true)?$days_opt:30;
$start    = date('Y-m-d H:i:s', strtotime("-{$days_opt} days"));

$analytics_summary = null;
$daily_data        = [];
$top_rules_data    = [];
if ($atbl) {
    $analytics_summary = $wpdb->get_row($wpdb->prepare(
        "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);
    $daily_data = $wpdb->get_results($wpdb->prepare(
        "SELECT DATE(date_created) AS d, COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s GROUP BY DATE(date_created) ORDER BY d ASC LIMIT 30", $start));
    $top_rules_data = $wpdb->get_results($wpdb->prepare(
        "SELECT rule_name, COUNT(DISTINCT order_id) AS fires, COALESCE(SUM(order_total),0) AS revenue, COALESCE(SUM(discount_amount),0) AS discount
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s GROUP BY rule_name ORDER BY fires DESC LIMIT 10", $start));
}

// Save report settings
if ($is_pro && isset($_POST['gtbogo_save_pdf_settings']) && check_admin_referer('gtbogo_pdf_settings')) {
    update_option('gtbogo_pdf_settings', [
        '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_roi'    => isset($_POST['include_roi']),
        'include_audit'  => isset($_POST['include_audit']),
        'accent_color'   => sanitize_hex_color($_POST['accent_color']    ?? '#e10000'),
        'watermark'      => isset($_POST['watermark']),
    ]);
    $message = 'Report settings saved.'; $message_type = 'success';
}

$pdf_s = get_option('gtbogo_pdf_settings', [
    'company_name' => get_bloginfo('name'), 'company_logo' => '', 'report_footer' => '',
    'include_rules' => true, 'include_analytics' => true, 'include_roi' => true, 'include_audit' => false,
    'accent_color' => '#e10000', 'watermark' => false,
]);

// Audit log for PDF
$audit_log = get_option('gtbogo_audit_log', []);
$audit_recent = array_slice(array_reverse($audit_log), 0, 20);

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

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">📄 PDF Export</h1>
        <p class="gt-page-subtitle">Generate branded performance reports — rules summary, analytics, and campaign results for clients or internal review</p>
    </div>
    <div style="display:flex;gap:8px;align-items:center">
        <span class="gt-badge gt-badge-active"><?php echo count($rules); ?> rules · <?php echo 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, branded campaign performance reports you can share with clients, stakeholders, or keep for compliance records.</p>
    <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px;max-width:480px;margin:24px auto 0">
        <?php foreach(['Rules summary with full configuration','Analytics data with daily charts','Branded with your logo and company name','Audit log snapshot for compliance'] as $f): ?>
        <div style="display:flex;align-items:flex-start;gap:8px;text-align:left"><span style="color:#e10000;font-weight:700">—</span><span style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html($f); ?></span></div>
        <?php endforeach; ?>
    </div>
    <div style="margin-top:24px;display:flex;justify-content:center;gap:12px">
        <a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO — $19.99/yr</a>
    </div>
</div>
<?php else: ?>

<!-- METRICS -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:20px">
    <div class="gt-metric" style="--gt-metric-c:#e10000">
        <span class="gt-metric-icon">📋</span>
        <div class="gt-metric-label">Total Rules</div>
        <div class="gt-metric-value"><?php echo count($rules); ?></div>
        <div class="gt-metric-trend"><?php echo count($active_rules); ?> active</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#22c55e">
        <span class="gt-metric-icon">💰</span>
        <div class="gt-metric-label">Revenue (<?php echo $days_opt; ?>d)</div>
        <div class="gt-metric-value" style="font-size:18px">$<?php echo number_format($analytics_summary['revenue']??0,0); ?></div>
        <div class="gt-metric-trend">In report period</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#3b82f6">
        <span class="gt-metric-icon">🛒</span>
        <div class="gt-metric-label">BOGO Orders</div>
        <div class="gt-metric-value"><?php echo number_format($analytics_summary['orders']??0); ?></div>
        <div class="gt-metric-trend">Last <?php echo $days_opt; ?> days</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#f59e0b">
        <span class="gt-metric-icon">🏷️</span>
        <div class="gt-metric-label">Discounts Given</div>
        <div class="gt-metric-value" style="font-size:18px">$<?php echo number_format($analytics_summary['discounts']??0,0); ?></div>
        <div class="gt-metric-trend">In report period</div>
    </div>
</div>

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

<!-- REPORT SETTINGS -->
<div class="gt-card gt-animate-in">
    <div class="gt-card-header"><h2 class="gt-card-title">⚙️ Report Settings</h2></div>
    <form method="post" action="">
        <?php wp_nonce_field('gtbogo_pdf_settings'); ?>
        <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']); ?>">
        </div>
        <div class="gt-form-group">
            <label class="gt-form-label">Company Logo URL</label>
            <input type="url" name="company_logo" class="gt-input" value="<?php echo esc_attr($pdf_s['company_logo']); ?>" placeholder="https://...">
            <div class="gt-form-hint">Must be a publicly accessible PNG or JPG (max 300px wide)</div>
        </div>
        <div class="gt-form-group">
            <label class="gt-form-label">Report Footer Text</label>
            <input type="text" name="report_footer" class="gt-input" value="<?php echo esc_attr($pdf_s['report_footer']); ?>" placeholder="e.g. Confidential — Internal Use Only">
        </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:48px;height:36px;border:none;border-radius:6px;cursor:pointer;background:none">
                <input type="text" id="accent-hex" class="gt-input" style="width:110px" value="<?php echo esc_attr($pdf_s['accent_color']); ?>" oninput="document.querySelector('[name=accent_color]').value=this.value">
            </div>
        </div>
        <div style="font-size:12px;font-weight:700;color:var(--gt-white);text-transform:uppercase;letter-spacing:1px;margin-bottom:10px;margin-top:4px">Include Sections</div>
        <?php foreach([
            ['include_rules',     '📋 Rules Summary',       'All rules with their full configuration'],
            ['include_analytics', '📈 Analytics Overview',  'Revenue, orders, discounts summary'],
            ['include_roi',       '📊 Top Rule Performance','Rule leaderboard from Analytics'],
            ['include_audit',     '🔍 Recent Audit Log',    'Last 20 audit log entries'],
            ['watermark',         '🔒 Confidential Watermark','Adds a diagonal watermark to each page'],
        ] as $s): ?>
        <div class="gt-setting-row" style="padding:8px 0">
            <div><div class="gt-setting-label" style="font-size:13px"><?php echo esc_html($s[1]); ?></div><div class="gt-setting-desc" style="font-size:11px"><?php echo esc_html($s[2]); ?></div></div>
            <label class="gt-toggle"><input type="checkbox" name="<?php echo $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; ?>
        <div style="margin-top:16px">
            <button type="submit" name="gtbogo_save_pdf_settings" class="gt-btn gt-btn-primary" style="width:100%;padding:12px">💾 Save Settings</button>
        </div>
    </form>
</div>

<!-- REPORT PREVIEW + EXPORT -->
<div>
    <!-- Period selector -->
    <div class="gt-card gt-animate-in" style="margin-bottom:16px">
        <div class="gt-card-header"><h2 class="gt-card-title">📅 Report Period</h2></div>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
            <?php foreach([7=>'Last 7 Days',14=>'Last 14 Days',30=>'Last 30 Days',60=>'Last 60 Days',90=>'Last 90 Days'] as $d=>$l): ?>
            <a href="?page=gt-bogo-engine&tab=pdf-export&pdf_days=<?php echo $d; ?>" class="gt-btn <?php echo $days_opt===$d?'gt-btn-primary':'gt-btn-ghost'; ?> gt-btn-sm"><?php echo esc_html($l); ?></a>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- REPORT PREVIEW (print-ready HTML) -->
    <div class="gt-card gt-animate-in" id="gt-pdf-report">
        <div class="gt-card-header">
            <h2 class="gt-card-title">👁 Report Preview</h2>
            <button onclick="window.print()" class="gt-btn gt-btn-primary gt-btn-sm">🖨 Print / Save as PDF</button>
        </div>
        <div id="gt-report-body" style="font-family:Georgia,serif;color:#111;padding:24px;border:1px solid rgba(255,255,255,0.06);border-radius:10px;background:#fff;color:#111">

            <!-- REPORT HEADER -->
            <div style="display:flex;align-items:center;justify-content:space-between;border-bottom:3px solid <?php echo esc_attr($pdf_s['accent_color']); ?>;padding-bottom:16px;margin-bottom:24px">
                <div>
                    <?php if ($pdf_s['company_logo']): ?>
                    <img src="<?php echo esc_url($pdf_s['company_logo']); ?>" alt="" style="max-height:48px;margin-bottom:8px;display:block">
                    <?php endif; ?>
                    <div style="font-size:22px;font-weight:800;color:#111"><?php echo esc_html($pdf_s['company_name']); ?></div>
                    <div style="font-size:13px;color:#555">GT BOGO Engine — Campaign Performance Report</div>
                </div>
                <div style="text-align:right">
                    <div style="font-size:13px;font-weight:700;color:<?php echo esc_attr($pdf_s['accent_color']); ?>">Report Period</div>
                    <div style="font-size:13px;color:#333">Last <?php echo $days_opt; ?> days</div>
                    <div style="font-size:11px;color:#888">Generated: <?php echo date('F j, Y'); ?></div>
                    <div style="font-size:11px;color:#888"><?php echo esc_html(home_url()); ?></div>
                </div>
            </div>

            <?php if (!empty($pdf_s['include_analytics']) && $analytics_summary): ?>
            <!-- ANALYTICS SUMMARY -->
            <div style="margin-bottom:24px">
                <div style="font-size:14px;font-weight:800;color:<?php echo esc_attr($pdf_s['accent_color']); ?>;text-transform:uppercase;letter-spacing:1px;margin-bottom:12px">Campaign Performance Summary</div>
                <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px">
                    <?php foreach([
                        ['Revenue Influenced', '$'.number_format($analytics_summary['revenue'],2)],
                        ['BOGO Orders',         number_format($analytics_summary['orders'])],
                        ['Discounts Given',    '$'.number_format($analytics_summary['discounts'],2)],
                        ['Avg Order Value',    '$'.number_format($analytics_summary['aov'],2)],
                    ] as $m): ?>
                    <div style="padding:14px;border:1px solid #e5e7eb;border-radius:8px;text-align:center">
                        <div style="font-size:11px;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:6px"><?php echo esc_html($m[0]); ?></div>
                        <div style="font-size:20px;font-weight:800;color:#111"><?php echo esc_html($m[1]); ?></div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <?php if (!empty($pdf_s['include_roi']) && !empty($top_rules_data)): ?>
            <!-- TOP RULES -->
            <div style="margin-bottom:24px">
                <div style="font-size:14px;font-weight:800;color:<?php echo esc_attr($pdf_s['accent_color']); ?>;text-transform:uppercase;letter-spacing:1px;margin-bottom:12px">Rule Performance Leaderboard</div>
                <table style="width:100%;border-collapse:collapse;font-size:12px">
                    <thead><tr style="background:<?php echo esc_attr($pdf_s['accent_color']); ?>;color:#fff">
                        <th style="padding:8px 10px;text-align:left">#</th><th style="padding:8px 10px;text-align:left">Rule</th>
                        <th style="padding:8px 10px;text-align:right">Fires</th><th style="padding:8px 10px;text-align:right">Revenue</th>
                        <th style="padding:8px 10px;text-align:right">Discount</th>
                    </tr></thead>
                    <tbody>
                    <?php foreach ($top_rules_data as $i => $tr): ?>
                    <tr style="background:<?php echo $i%2===0?'#f9fafb':'#fff'; ?>;border-bottom:1px solid #e5e7eb">
                        <td style="padding:7px 10px;font-weight:700"><?php echo $i+1; ?></td>
                        <td style="padding:7px 10px"><?php echo esc_html($tr->rule_name); ?></td>
                        <td style="padding:7px 10px;text-align:right;font-family:monospace"><?php echo number_format($tr->fires); ?></td>
                        <td style="padding:7px 10px;text-align:right;font-family:monospace;color:#15803d">$<?php echo number_format($tr->revenue,2); ?></td>
                        <td style="padding:7px 10px;text-align:right;font-family:monospace;color:#dc2626">-$<?php echo number_format($tr->discount,2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>

            <?php if (!empty($pdf_s['include_rules']) && !empty($rules)): ?>
            <!-- RULES SUMMARY -->
            <div style="margin-bottom:24px">
                <div style="font-size:14px;font-weight:800;color:<?php echo esc_attr($pdf_s['accent_color']); ?>;text-transform:uppercase;letter-spacing:1px;margin-bottom:12px">Active Rules Configuration (<?php echo count($active_rules); ?> active)</div>
                <table style="width:100%;border-collapse:collapse;font-size:11px">
                    <thead><tr style="background:#111;color:#fff">
                        <th style="padding:7px 8px;text-align:left">Rule Name</th><th style="padding:7px 8px">Type</th>
                        <th style="padding:7px 8px">Buy</th><th style="padding:7px 8px">Get</th>
                        <th style="padding:7px 8px">Discount</th><th style="padding:7px 8px">Priority</th><th style="padding:7px 8px">Status</th>
                    </tr></thead>
                    <tbody>
                    <?php foreach ($rules as $i => $r): ?>
                    <tr style="background:<?php echo $i%2===0?'#f9fafb':'#fff'; ?>;border-bottom:1px solid #e5e7eb">
                        <td style="padding:6px 8px;font-weight:600"><?php echo esc_html($r->name); ?></td>
                        <td style="padding:6px 8px;text-align:center;font-family:monospace;font-size:10px"><?php echo esc_html($r->type); ?></td>
                        <td style="padding:6px 8px;text-align:center"><?php echo esc_html($r->buy_quantity); ?></td>
                        <td style="padding:6px 8px;text-align:center"><?php echo esc_html($r->get_quantity); ?></td>
                        <td style="padding:6px 8px;text-align:center"><?php echo esc_html($r->discount_value).'%'; ?></td>
                        <td style="padding:6px 8px;text-align:center;font-family:monospace"><?php echo esc_html($r->priority); ?></td>
                        <td style="padding:6px 8px;text-align:center;color:<?php echo $r->status==='active'?'#15803d':'#6b7280'; ?>;font-weight:700"><?php echo esc_html(ucfirst($r->status)); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>

            <?php if (!empty($pdf_s['include_audit']) && !empty($audit_recent)): ?>
            <!-- AUDIT LOG -->
            <div style="margin-bottom:24px">
                <div style="font-size:14px;font-weight:800;color:<?php echo esc_attr($pdf_s['accent_color']); ?>;text-transform:uppercase;letter-spacing:1px;margin-bottom:12px">Recent Audit Log (Last 20 Events)</div>
                <table style="width:100%;border-collapse:collapse;font-size:11px">
                    <thead><tr style="background:#374151;color:#fff">
                        <th style="padding:6px 8px;text-align:left">Time</th><th style="padding:6px 8px">User</th>
                        <th style="padding:6px 8px;text-align:left">Action</th><th style="padding:6px 8px;text-align:left">Detail</th><th style="padding:6px 8px">Level</th>
                    </tr></thead>
                    <tbody>
                    <?php foreach ($audit_recent as $i => $e): ?>
                    <tr style="background:<?php echo $i%2===0?'#f9fafb':'#fff'; ?>;border-bottom:1px solid #e5e7eb">
                        <td style="padding:5px 8px;font-family:monospace;font-size:10px;color:#6b7280"><?php echo esc_html($e['time']); ?></td>
                        <td style="padding:5px 8px;text-align:center;font-size:10px"><?php echo esc_html($e['user']); ?></td>
                        <td style="padding:5px 8px;font-weight:600"><?php echo esc_html($e['action']); ?></td>
                        <td style="padding:5px 8px;color:#6b7280"><?php echo esc_html($e['detail']); ?></td>
                        <td style="padding:5px 8px;text-align:center;font-size:10px;font-weight:700;color:<?php
                            echo ['error'=>'#dc2626','warn'=>'#d97706','success'=>'#15803d','info'=>'#1d4ed8'][$e['level']]??'#6b7280';
                        ?>"><?php echo esc_html(strtoupper($e['level'])); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>

            <!-- FOOTER -->
            <div style="border-top:2px solid <?php echo esc_attr($pdf_s['accent_color']); ?>;padding-top:12px;display:flex;justify-content:space-between;font-size:10px;color:#9ca3af">
                <span><?php echo esc_html($pdf_s['report_footer'] ?: $pdf_s['company_name'].' — Powered by GT BOGO Engine PRO'); ?></span>
                <span>Generated <?php echo date('F j, Y \a\t g:i A'); ?></span>
            </div>

        </div>
        <div style="margin-top:16px;display:flex;gap:10px;justify-content:flex-end">
            <button onclick="window.print()" class="gt-btn gt-btn-primary" style="padding:12px 32px">🖨 Print / Save as PDF</button>
        </div>
    </div>
</div>

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

<!-- PRINT STYLES -->
<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 { border:none !important; box-shadow:none !important; }
    #gt-report-body { border:none !important; padding:0 !important; color:#111 !important; background:#fff !important; }
    body { background:#fff !important; }
    * { color-adjust:exact !important; -webkit-print-color-adjust:exact !important; print-color-adjust:exact !important; }
}
</style>

<!-- GUIDANCE -->
<div class="gt-card gt-animate-in" style="background:linear-gradient(135deg,rgba(59,130,246,0.06),rgba(7,12,28,0));border-color:rgba(59,130,246,0.15)">
    <div class="gt-card-header"><h2 class="gt-card-title">🧠 PDF Export Guide</h2></div>
    <div class="gt-feature-grid gt-feature-grid--2col">
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">How to Save as PDF</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Click "Print / Save as PDF" and select "Save as PDF" as your printer destination in the browser dialog. Chrome and Edge produce the cleanest output. Set margins to "None" or "Minimal" for a professional borderless layout.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Monthly Client Reports</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Generate this report on the 1st of each month set to "Last 30 Days". Save the PDF with the naming convention CLIENT_BOGO_Report_YYYY_MM.pdf. Send alongside your broader WooCommerce performance summary for a complete picture.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Stakeholder Presentations</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Include the Audit Log section when presenting to stakeholders who want change accountability. The timestamped log shows every rule activation, deactivation, and settings change — demonstrating controlled, deliberate campaign management.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Compliance and Archiving</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">For stores in regulated markets, archive PDFs quarterly. The report documents which promotional rules were active during each period, the discount amounts given, and the audit trail — creating a paper record that satisfies most promotional compliance requirements.</div></div>
    </div>
</div>

<?php endif; ?>
<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
