<?php
/**
 * Reports — overview + generator + archive.
 *
 * @package Brainwerk SEO Suite
 */
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! current_user_can( 'manage_options' ) && ! current_user_can( 'manage_network_options' ) ) return;

$archive = Seoforge_Reports::list_archive();
$today   = wp_date( 'Y-m-d' );
$last_7  = wp_date( 'Y-m-d', strtotime( '-7 days' ) );
$last_30 = wp_date( 'Y-m-d', strtotime( '-30 days' ) );
$last_90 = wp_date( 'Y-m-d', strtotime( '-90 days' ) );

$auto_weekly  = (bool) Seoforge_Settings::get( Seoforge_Reports::OPT_AUTO_WEEKLY, true );
$auto_monthly = (bool) Seoforge_Settings::get( Seoforge_Reports::OPT_AUTO_MONTHLY, true );
$auto_to      = (string) Seoforge_Settings::get( Seoforge_Reports::OPT_AUTO_RECIPIENT, '' );

if ( isset( $_GET['seoforge_report_ok'] ) ) {
    echo '<div class="notice notice-success is-dismissible"><p>✓ ' . sprintf(
        /* translators: %s: generated report file name */
        esc_html__( 'Report created: %s', 'brainwerk-seo-suite' ),
        '<code>' . esc_html( sanitize_file_name( wp_unslash( $_GET['seoforge_report_ok'] ) ) ) . '</code>'
    ) . '</p></div>';
}
if ( isset( $_GET['seoforge_resent'] ) )  echo '<div class="notice notice-success is-dismissible"><p>✓ ' . esc_html__( 'Report sent by e-mail.', 'brainwerk-seo-suite' ) . '</p></div>';
if ( isset( $_GET['seoforge_deleted'] ) ) echo '<div class="notice notice-info is-dismissible"><p>' . esc_html__( 'Report deleted.', 'brainwerk-seo-suite' ) . '</p></div>';

// === Executive report (CEO / CTO) — Pro =============================
// The renderer lives in a __premium_only class that is stripped from the Free
// build, so we require BOTH an active license AND the class to be present.
$report_pro = class_exists( 'Seoforge_License' ) && Seoforge_License::is_pro() && class_exists( 'Seoforge_Pro_Report' );

// True when the bundled PDF engine is present and usable (Pro build): reports
// are then real, server-generated PDFs. In the Free build the class is stripped
// and the report falls back to the printable HTML variant.
$pdf_export = class_exists( 'Seoforge_Pro_Pdf' ) && Seoforge_Pro_Pdf::available();
?>

<div class="seoforge-card" style="background:#fff;border:1px solid #c3c4c7;border-radius:6px;padding:18px 22px;margin-bottom:18px;">
    <h2 style="margin-top:0;">✨ <?php esc_html_e( 'Executive report (CEO / CTO)', 'brainwerk-seo-suite' ); ?></h2>
    <?php if ( ! $report_pro ) : ?>
        <?php
        // Free tier (or Premium build without an active license): show the upsell.
        echo Seoforge_Pro::upsell( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            __( 'Executive report (CEO / CTO)', 'brainwerk-seo-suite' ),
            __( 'A polished, print-ready one-click report — pick an Executive (CEO) or Technical (CTO) preset, choose a period, and present or save it as PDF. Reuses your live analytics; no data leaves your site.', 'brainwerk-seo-suite' )
        );
        ?>
    <?php else : ?>
        <p style="color:#50575e;font-size:13px;">
            <?php esc_html_e( 'Generate a branded, print-ready report for leadership. Opens in a new tab — use your browser’s “Save as PDF” or print it.', 'brainwerk-seo-suite' ); ?>
        </p>
        <form method="get" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" target="_blank" style="display:flex;align-items:flex-end;gap:14px;flex-wrap:wrap;margin-top:14px;">
            <?php wp_nonce_field( Seoforge_Pro_Report::ACTION ); ?>
            <input type="hidden" name="action" value="<?php echo esc_attr( Seoforge_Pro_Report::ACTION ); ?>">
            <div>
                <label style="display:block;font-weight:600;font-size:13px;margin-bottom:4px;"><?php esc_html_e( 'Preset', 'brainwerk-seo-suite' ); ?></label>
                <select name="preset" style="font-size:14px;">
                    <?php foreach ( Seoforge_Pro_Report::presets() as $key => $p ) : ?>
                        <option value="<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $p['label'] ); ?> — <?php echo esc_html( $p['blurb'] ); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label style="display:block;font-weight:600;font-size:13px;margin-bottom:4px;"><?php esc_html_e( 'From', 'brainwerk-seo-suite' ); ?></label>
                <input type="date" name="range_start" required value="<?php echo esc_attr( $last_30 ); ?>" max="<?php echo esc_attr( $today ); ?>" style="font-size:14px;">
            </div>
            <div>
                <label style="display:block;font-weight:600;font-size:13px;margin-bottom:4px;"><?php esc_html_e( 'To', 'brainwerk-seo-suite' ); ?></label>
                <input type="date" name="range_end" required value="<?php echo esc_attr( $today ); ?>" max="<?php echo esc_attr( $today ); ?>" style="font-size:14px;">
            </div>
            <button type="submit" class="button button-primary button-large">📊 <?php esc_html_e( 'Open report', 'brainwerk-seo-suite' ); ?></button>
        </form>
    <?php endif; ?>
</div>

<div class="seoforge-card" style="background:#fff;border:1px solid #c3c4c7;border-radius:6px;padding:18px 22px;margin-bottom:18px;">
    <h2 style="margin-top:0;"><span aria-hidden="true">📊</span> <?php esc_html_e( 'Generate a new report', 'brainwerk-seo-suite' ); ?></h2>
    <?php if ( $pdf_export ) : ?>
        <p style="color:#50575e;font-size:13px;"><?php esc_html_e( 'A real PDF report with 34 KPIs (pageviews, sessions, conversions, Core Web Vitals, top pages, sources, devices, countries, outbound, downloads, site search) plus prior-period comparison, trend chart and audit footer — generated on your server and ready to download, e-mail or archive.', 'brainwerk-seo-suite' ); ?></p>
    <?php else : ?>
        <p style="color:#50575e;font-size:13px;"><?php esc_html_e( 'A printable HTML report with 34 KPIs (pageviews, sessions, conversions, Core Web Vitals, top pages, sources, devices, countries, outbound, downloads, site search) plus prior-period comparison, trend chart and audit footer. Open it and use your browser’s “Save as PDF” — no PDF software required.', 'brainwerk-seo-suite' ); ?></p>
    <?php endif; ?>

    <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="display:flex;align-items:flex-end;gap:14px;flex-wrap:wrap;margin-top:14px;">
        <?php wp_nonce_field( 'seoforge_generate_report' ); ?>
        <input type="hidden" name="action" value="seoforge_generate_report">
        <div>
            <label style="display:block;font-weight:600;font-size:13px;margin-bottom:4px;"><?php esc_html_e( 'From', 'brainwerk-seo-suite' ); ?></label>
            <input type="date" name="range_start" required value="<?php echo esc_attr( $last_7 ); ?>" max="<?php echo esc_attr( $today ); ?>" style="font-size:14px;">
        </div>
        <div>
            <label style="display:block;font-weight:600;font-size:13px;margin-bottom:4px;"><?php esc_html_e( 'To', 'brainwerk-seo-suite' ); ?></label>
            <input type="date" name="range_end" required value="<?php echo esc_attr( $today ); ?>" max="<?php echo esc_attr( $today ); ?>" style="font-size:14px;">
        </div>
        <div>
            <label style="display:block;font-weight:600;font-size:13px;margin-bottom:4px;"><?php esc_html_e( 'Label', 'brainwerk-seo-suite' ); ?></label>
            <select name="tag" style="font-size:14px;">
                <option value="custom"><?php esc_html_e( 'Custom', 'brainwerk-seo-suite' ); ?></option>
                <option value="daily"><?php esc_html_e( 'Day', 'brainwerk-seo-suite' ); ?></option>
                <option value="weekly"><?php esc_html_e( 'Week', 'brainwerk-seo-suite' ); ?></option>
                <option value="monthly"><?php esc_html_e( 'Month', 'brainwerk-seo-suite' ); ?></option>
                <option value="quarterly"><?php esc_html_e( 'Quarter', 'brainwerk-seo-suite' ); ?></option>
                <option value="yearly"><?php esc_html_e( 'Year', 'brainwerk-seo-suite' ); ?></option>
            </select>
        </div>
        <button type="submit" class="button button-primary button-large"><span aria-hidden="true">📄</span> <?php esc_html_e( 'Create report', 'brainwerk-seo-suite' ); ?></button>
    </form>

    <p style="margin-top:14px;font-size:12px;color:#646970;">
        <?php esc_html_e( 'Quick ranges:', 'brainwerk-seo-suite' ); ?>
        <a href="#" class="seoforge-quick-range" data-start="<?php echo esc_attr( $today ); ?>" data-end="<?php echo esc_attr( $today ); ?>" data-tag="daily"><?php esc_html_e( 'Today', 'brainwerk-seo-suite' ); ?></a> ·
        <a href="#" class="seoforge-quick-range" data-start="<?php echo esc_attr( $last_7 ); ?>" data-end="<?php echo esc_attr( $today ); ?>" data-tag="weekly"><?php esc_html_e( '7 days', 'brainwerk-seo-suite' ); ?></a> ·
        <a href="#" class="seoforge-quick-range" data-start="<?php echo esc_attr( $last_30 ); ?>" data-end="<?php echo esc_attr( $today ); ?>" data-tag="monthly"><?php esc_html_e( '30 days', 'brainwerk-seo-suite' ); ?></a> ·
        <a href="#" class="seoforge-quick-range" data-start="<?php echo esc_attr( $last_90 ); ?>" data-end="<?php echo esc_attr( $today ); ?>" data-tag="quarterly"><?php esc_html_e( '90 days', 'brainwerk-seo-suite' ); ?></a> ·
        <a href="#" class="seoforge-quick-range" data-start="<?php echo esc_attr( wp_date( 'Y-m-d', strtotime( '-1 year' ) ) ); ?>" data-end="<?php echo esc_attr( $today ); ?>" data-tag="yearly"><?php esc_html_e( '365 days', 'brainwerk-seo-suite' ); ?></a>
    </p>
</div>

<div class="seoforge-card" style="background:#fff;border:1px solid #c3c4c7;border-radius:6px;padding:18px 22px;margin-bottom:18px;">
    <h2 style="margin-top:0;">⏰ <?php esc_html_e( 'Auto-Reports', 'brainwerk-seo-suite' ); ?></h2>
    <p style="color:#50575e;font-size:13px;"><?php esc_html_e( 'Brainwerk SEO Suite automatically generates two reports and stores them in the archive (see below). Optionally sends them to a configured e-mail address.', 'brainwerk-seo-suite' ); ?></p>
    <form method="post" action="<?php echo esc_url( admin_url( 'admin.php?page=' . Seoforge_Admin::MENU_SLUG . '&tab=reports' ) ); ?>">
        <?php wp_nonce_field( Seoforge_Admin::NONCE ); ?>
        <input type="hidden" name="seoforge_action" value="save_settings">
        <input type="hidden" name="seoforge_tab_keys[]" value="<?php echo esc_attr( Seoforge_Reports::OPT_AUTO_WEEKLY ); ?>">
        <input type="hidden" name="seoforge_tab_keys[]" value="<?php echo esc_attr( Seoforge_Reports::OPT_AUTO_MONTHLY ); ?>">
        <table class="form-table">
            <tr><th><?php esc_html_e( 'Weekly report', 'brainwerk-seo-suite' ); ?></th><td>
                <label><input type="checkbox" name="seoforge[<?php echo esc_attr( Seoforge_Reports::OPT_AUTO_WEEKLY ); ?>]" value="1" <?php checked( $auto_weekly, true ); ?>> <?php esc_html_e( 'Active (Sunday 06:00 UTC, covers the past week)', 'brainwerk-seo-suite' ); ?></label>
            </td></tr>
            <tr><th><?php esc_html_e( 'Monthly report', 'brainwerk-seo-suite' ); ?></th><td>
                <label><input type="checkbox" name="seoforge[<?php echo esc_attr( Seoforge_Reports::OPT_AUTO_MONTHLY ); ?>]" value="1" <?php checked( $auto_monthly, true ); ?>> <?php esc_html_e( 'Active (1st of the month 06:00 UTC, covers the past month)', 'brainwerk-seo-suite' ); ?></label>
            </td></tr>
            <tr><th><?php esc_html_e( 'Recipient e-mail (optional)', 'brainwerk-seo-suite' ); ?></th><td>
                <input type="email" name="seoforge[<?php echo esc_attr( Seoforge_Reports::OPT_AUTO_RECIPIENT ); ?>]" value="<?php echo esc_attr( $auto_to ); ?>" class="regular-text" placeholder="<?php esc_attr_e( 'e.g. office@example.com', 'brainwerk-seo-suite' ); ?>">
                <p class="description"><?php esc_html_e( 'If set, the report is additionally e-mailed automatically.', 'brainwerk-seo-suite' ); ?></p>
            </td></tr>
        </table>
        <?php submit_button( __( 'Save auto-report settings', 'brainwerk-seo-suite' ) ); ?>
    </form>
</div>

<div class="seoforge-card" style="background:#fff;border:1px solid #c3c4c7;border-radius:6px;padding:18px 22px;">
    <h2 style="margin-top:0;">🗄️ <?php
        /* translators: %d: number of archived reports */
        printf( esc_html__( 'Archive (%d reports)', 'brainwerk-seo-suite' ), (int) count( $archive ) );
    ?></h2>
    <?php if ( empty( $archive ) ) : ?>
        <p style="color:#50575e;"><?php esc_html_e( 'No reports yet. Generate your first report above.', 'brainwerk-seo-suite' ); ?></p>
    <?php else : ?>
        <table class="widefat striped" style="margin-top:8px;">
            <thead><tr>
                <th style="width:50%;"><?php esc_html_e( 'File', 'brainwerk-seo-suite' ); ?></th>
                <th><?php esc_html_e( 'Size', 'brainwerk-seo-suite' ); ?></th>
                <th><?php esc_html_e( 'Created', 'brainwerk-seo-suite' ); ?></th>
                <th style="width:280px;"><?php esc_html_e( 'Actions', 'brainwerk-seo-suite' ); ?></th>
            </tr></thead>
            <tbody>
                <?php foreach ( $archive as $r ) :
                    $is_pdf_file = ( 'pdf' === strtolower( (string) pathinfo( $r['name'], PATHINFO_EXTENSION ) ) );
                    $dl_url     = wp_nonce_url( admin_url( 'admin-post.php?action=seoforge_download_report&file=' . urlencode( $r['name'] ) ), 'seoforge_dl_report' );
                    $resend_url = wp_nonce_url( admin_url( 'admin-post.php?action=seoforge_resend_report&file=' . urlencode( $r['name'] ) ), 'seoforge_resend_report' );
                    $del_url    = wp_nonce_url( admin_url( 'admin-post.php?action=seoforge_delete_report&file=' . urlencode( $r['name'] ) ), 'seoforge_delete_report' );
                ?>
                <tr>
                    <td><code><?php echo esc_html( $r['name'] ); ?></code></td>
                    <td><?php echo esc_html( size_format( $r['size'] ) ); ?></td>
                    <td><?php echo esc_html( wp_date( 'd.m.Y H:i', $r['mtime'] ) ); ?></td>
                    <td>
                        <a href="<?php echo esc_url( $dl_url ); ?>" class="button button-small"><span aria-hidden="true">⬇</span> <?php echo $is_pdf_file ? esc_html__( 'Download PDF', 'brainwerk-seo-suite' ) : esc_html__( 'Open HTML', 'brainwerk-seo-suite' ); ?></a>
                        <?php if ( $auto_to ) : ?>
                            <a href="<?php echo esc_url( $resend_url ); ?>" class="button button-small"><span aria-hidden="true">📧</span> <?php esc_html_e( 'Re-send', 'brainwerk-seo-suite' ); ?></a>
                        <?php endif; ?>
                        <a href="<?php echo esc_url( $del_url ); ?>" class="button button-small" style="color:#cf222e;" onclick="return confirm('<?php echo esc_js( __( 'Really delete this report?', 'brainwerk-seo-suite' ) ); ?>');"><span aria-hidden="true">✕</span> <?php esc_html_e( 'Delete', 'brainwerk-seo-suite' ); ?></a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>
