<?php
if (!defined('ABSPATH')) {
    exit;
}

$ui_labels = isset($ui_labels) && is_array($ui_labels) ? $ui_labels : [];
$profile_key = sanitize_key((string) ($ui_labels['profile_key'] ?? ''));
$analytics_title = isset($analytics_title) ? (string) $analytics_title : sanitize_text_field((string) ($ui_labels['owner_analytics_title'] ?? __('Analytics', 'nexdirectory')));
$analytics_description = isset($analytics_description) ? (string) $analytics_description : sanitize_text_field((string) ($ui_labels['owner_analytics_description'] ?? __('Review listing views, clicks, enquiries, and discovery performance.', 'nexdirectory')));
$report = isset($report) && is_array($report) ? $report : [];
$totals = isset($report['totals']) && is_array($report['totals']) ? $report['totals'] : [];
$rows = isset($report['rows']) && is_array($report['rows']) ? $report['rows'] : [];
$comparison = isset($report['comparison']) && is_array($report['comparison']) ? $report['comparison'] : [];
$deltas = isset($comparison['deltas']) && is_array($comparison['deltas']) ? $comparison['deltas'] : [];
$boost_impact = isset($report['boost_impact']) && is_array($report['boost_impact']) ? $report['boost_impact'] : [];
$boosted_metrics = isset($boost_impact['boosted']) && is_array($boost_impact['boosted']) ? $boost_impact['boosted'] : [];
$non_boosted_metrics = isset($boost_impact['non_boosted']) && is_array($boost_impact['non_boosted']) ? $boost_impact['non_boosted'] : [];
$boost_shares = isset($boost_impact['shares']) && is_array($boost_impact['shares']) ? $boost_impact['shares'] : [];
$boost_uplift = isset($boost_impact['uplift']) && is_array($boost_impact['uplift']) ? $boost_impact['uplift'] : [];
$trend_rows = isset($report['trend']) && is_array($report['trend']) ? $report['trend'] : [];
$trend_meta = isset($report['trend_meta']) && is_array($report['trend_meta']) ? $report['trend_meta'] : [];
$days = isset($days) ? absint((int) $days) : 30;
$events_url = isset($events_url) ? (string) $events_url : $this->get_profile_route_default_url('events', $profile_key);
$page_kicker = sanitize_text_field((string) $this->get_event_hero_kicker_text());

$trend_display = $trend_rows;
if (count($trend_display) > 30) {
    $trend_display = array_slice($trend_display, -30);
}
$trend_max = max(1, (int) ($trend_meta['max_value'] ?? 0));

$delta_badge_class = static function ($delta_row) {
    if (!is_array($delta_row)) {
        return 'is-flat';
    }
    $trend = sanitize_key((string) ($delta_row['trend'] ?? 'flat'));
    if ($trend === 'up') {
        return 'is-up';
    }
    if ($trend === 'down') {
        return 'is-down';
    }
    return 'is-flat';
};
$delta_badge_text = static function ($delta_row) {
    if (!is_array($delta_row)) {
        return '0.00';
    }
    $value = (float) ($delta_row['change_pct'] ?? 0);
    $prefix = $value > 0 ? '+' : '';
    return $prefix . number_format($value, 2);
};
$uplift_badge_class = static function ($value) {
    $value = (float) $value;
    if ($value > 0) {
        return 'is-up';
    }
    if ($value < 0) {
        return 'is-down';
    }
    return 'is-flat';
};

echo $this->render_notice();
echo $this->render_platform_breadcrumbs($analytics_title); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
?>
<section class="eep-page-banner">
    <p class="eep-page-kicker"><?php echo esc_html($page_kicker); ?></p>
    <h1><?php echo esc_html($analytics_title); ?></h1>
    <p><?php echo esc_html($analytics_description); ?></p>
</section>
<?php echo $this->render_account_tabs('owner-analytics', $profile_key); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
<div class="eep-account-shell">
    <div class="eep-account-panel eep-owner-analytics-panel">
        <div class="eep-owner-analytics-toolbar">
            <?php $current_url = esc_url_raw((string) $this->current_url()); ?>
            <div class="eep-owner-analytics-filter">
                <label for="eep-owner-days"><?php esc_html_e('Reporting Window', 'nexdirectory'); ?></label>
                <select id="eep-owner-days" onchange="window.location.href=this.value;">
                    <?php
                    $ranges = [7 => __('Last 7 days', 'nexdirectory'), 30 => __('Last 30 days', 'nexdirectory'), 90 => __('Last 90 days', 'nexdirectory'), 365 => __('Last 12 months', 'nexdirectory')];
                    foreach ($ranges as $range_value => $range_label) :
                        $range_url = eep_add_query_arg('eep_owner_days', (int) $range_value, eep_remove_query_arg('eep_owner_days', $current_url));
                        ?>
                        <option value="<?php echo esc_url($range_url); ?>" <?php selected($days, (int) $range_value); ?>><?php echo esc_html((string) $range_label); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="eep-owner-analytics-export">
                <input type="hidden" name="action" value="eep_export_owner_analytics">
                <input type="hidden" name="eep_owner_days" value="<?php echo esc_attr((string) $days); ?>">
                <?php wp_nonce_field('eep_export_owner_analytics_nonce', 'eep_export_owner_analytics_nonce'); ?>
                <label for="eep-owner-export-format" class="screen-reader-text"><?php esc_html_e('Export format', 'nexdirectory'); ?></label>
                <select id="eep-owner-export-format" name="eep_export_format">
                    <option value="csv"><?php esc_html_e('CSV', 'nexdirectory'); ?></option>
                    <option value="json"><?php esc_html_e('JSON', 'nexdirectory'); ?></option>
                </select>
                <button type="submit" class="eep-btn eep-btn-secondary"><?php esc_html_e('Export Report', 'nexdirectory'); ?></button>
            </form>
        </div>

        <div class="eep-owner-analytics-cards">
            <article class="eep-owner-analytics-card">
                <span><?php esc_html_e('Listing Views', 'nexdirectory'); ?></span>
                <strong><?php echo esc_html((string) ((int) ($totals['listing_views'] ?? 0))); ?></strong>
                <?php $views_delta = isset($deltas['listing_views']) && is_array($deltas['listing_views']) ? $deltas['listing_views'] : []; ?>
                <small class="eep-owner-delta <?php echo esc_attr($delta_badge_class($views_delta)); ?>">
                    <?php echo esc_html($delta_badge_text($views_delta)); ?>%
                </small>
            </article>
            <article class="eep-owner-analytics-card">
                <span><?php esc_html_e('Enquiries Received', 'nexdirectory'); ?></span>
                <strong><?php echo esc_html((string) ((int) ($totals['enquiries_received'] ?? 0))); ?></strong>
                <?php $enquiries_delta = isset($deltas['enquiries_received']) && is_array($deltas['enquiries_received']) ? $deltas['enquiries_received'] : []; ?>
                <small class="eep-owner-delta <?php echo esc_attr($delta_badge_class($enquiries_delta)); ?>">
                    <?php echo esc_html($delta_badge_text($enquiries_delta)); ?>%
                </small>
            </article>
            <article class="eep-owner-analytics-card">
                <span><?php esc_html_e('Website Clicks', 'nexdirectory'); ?></span>
                <strong><?php echo esc_html((string) ((int) ($totals['click_website'] ?? 0))); ?></strong>
                <?php $website_delta = isset($deltas['click_website']) && is_array($deltas['click_website']) ? $deltas['click_website'] : []; ?>
                <small class="eep-owner-delta <?php echo esc_attr($delta_badge_class($website_delta)); ?>">
                    <?php echo esc_html($delta_badge_text($website_delta)); ?>%
                </small>
            </article>
            <article class="eep-owner-analytics-card">
                <span><?php esc_html_e('View to Enquiry', 'nexdirectory'); ?></span>
                <strong><?php echo esc_html(number_format((float) ($totals['conversion_rate'] ?? 0), 2)); ?>%</strong>
                <?php $conversion_delta = isset($deltas['conversion_rate']) && is_array($deltas['conversion_rate']) ? $deltas['conversion_rate'] : []; ?>
                <small class="eep-owner-delta <?php echo esc_attr($delta_badge_class($conversion_delta)); ?>">
                    <?php echo esc_html($delta_badge_text($conversion_delta)); ?>%
                </small>
            </article>
        </div>

        <section class="eep-owner-analytics-chart">
            <div class="eep-owner-analytics-chart-head">
                <h3><?php esc_html_e('Views and Enquiries Trend', 'nexdirectory'); ?></h3>
                <p><?php esc_html_e('Visual trend for your selected reporting window.', 'nexdirectory'); ?></p>
            </div>
            <?php if (!empty($trend_display)) : ?>
                <div class="eep-owner-trend-grid">
                    <?php foreach ($trend_display as $trend_row) : ?>
                        <?php
                        $trend_label = sanitize_text_field((string) ($trend_row['label'] ?? ''));
                        $trend_views = (int) ($trend_row['listing_views'] ?? 0);
                        $trend_enquiries = (int) ($trend_row['enquiries_received'] ?? 0);
                        $trend_views_width = min(100, max(0, ($trend_views / $trend_max) * 100));
                        $trend_enquiries_width = min(100, max(0, ($trend_enquiries / $trend_max) * 100));
                        ?>
                        <div class="eep-owner-trend-row">
                            <span class="eep-owner-trend-label"><?php echo esc_html($trend_label); ?></span>
                            <div class="eep-owner-trend-bars">
                                <span class="eep-owner-trend-bar is-views" style="width: <?php echo esc_attr(number_format((float) $trend_views_width, 2, '.', '')); ?>%"></span>
                                <span class="eep-owner-trend-bar is-enquiries" style="width: <?php echo esc_attr(number_format((float) $trend_enquiries_width, 2, '.', '')); ?>%"></span>
                            </div>
                            <span class="eep-owner-trend-values"><?php echo esc_html(sprintf(__('V %1$d / E %2$d', 'nexdirectory'), $trend_views, $trend_enquiries)); ?></span>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else : ?>
                <p class="eep-meta"><?php esc_html_e('No trend data available for this period.', 'nexdirectory'); ?></p>
            <?php endif; ?>
        </section>

        <section class="eep-owner-boost-impact">
            <div class="eep-owner-analytics-chart-head">
                <h3><?php esc_html_e('Boost Impact Snapshot', 'nexdirectory'); ?></h3>
                <p><?php esc_html_e('Compare performance between boosted and non-boosted listings.', 'nexdirectory'); ?></p>
            </div>
            <div class="eep-owner-boost-impact-grid">
                <article class="eep-owner-impact-card">
                    <h4><?php esc_html_e('Boosted Listings', 'nexdirectory'); ?></h4>
                    <p><?php echo esc_html(sprintf(__('Listings: %d', 'nexdirectory'), (int) ($boosted_metrics['listings'] ?? 0))); ?></p>
                    <p><?php echo esc_html(sprintf(__('Views: %d', 'nexdirectory'), (int) ($boosted_metrics['listing_views'] ?? 0))); ?></p>
                    <p><?php echo esc_html(sprintf(__('Enquiries: %d', 'nexdirectory'), (int) ($boosted_metrics['enquiries_received'] ?? 0))); ?></p>
                    <p><?php echo esc_html(sprintf(__('Conversion: %s%%', 'nexdirectory'), number_format((float) ($boosted_metrics['conversion_rate'] ?? 0), 2))); ?></p>
                </article>
                <article class="eep-owner-impact-card">
                    <h4><?php esc_html_e('Non-Boosted Listings', 'nexdirectory'); ?></h4>
                    <p><?php echo esc_html(sprintf(__('Listings: %d', 'nexdirectory'), (int) ($non_boosted_metrics['listings'] ?? 0))); ?></p>
                    <p><?php echo esc_html(sprintf(__('Views: %d', 'nexdirectory'), (int) ($non_boosted_metrics['listing_views'] ?? 0))); ?></p>
                    <p><?php echo esc_html(sprintf(__('Enquiries: %d', 'nexdirectory'), (int) ($non_boosted_metrics['enquiries_received'] ?? 0))); ?></p>
                    <p><?php echo esc_html(sprintf(__('Conversion: %s%%', 'nexdirectory'), number_format((float) ($non_boosted_metrics['conversion_rate'] ?? 0), 2))); ?></p>
                </article>
            </div>
            <div class="eep-owner-uplift-row">
                <?php
                $views_uplift = (float) ($boost_uplift['views_per_listing_pct'] ?? 0);
                $enquiries_uplift = (float) ($boost_uplift['enquiries_per_listing_pct'] ?? 0);
                $conversion_uplift = (float) ($boost_uplift['conversion_rate_pct'] ?? 0);
                ?>
                <span class="eep-owner-uplift-pill <?php echo esc_attr($uplift_badge_class($views_uplift)); ?>"><?php echo esc_html(sprintf(__('Views/listing: %s%%', 'nexdirectory'), number_format($views_uplift, 2))); ?></span>
                <span class="eep-owner-uplift-pill <?php echo esc_attr($uplift_badge_class($enquiries_uplift)); ?>"><?php echo esc_html(sprintf(__('Enquiries/listing: %s%%', 'nexdirectory'), number_format($enquiries_uplift, 2))); ?></span>
                <span class="eep-owner-uplift-pill <?php echo esc_attr($uplift_badge_class($conversion_uplift)); ?>"><?php echo esc_html(sprintf(__('Conversion uplift: %s%%', 'nexdirectory'), number_format($conversion_uplift, 2))); ?></span>
            </div>
            <p class="eep-meta">
                <?php
                echo esc_html(sprintf(
                    __('Share of total views from boosted listings: %1$s%% | Share of total enquiries from boosted listings: %2$s%%', 'nexdirectory'),
                    number_format((float) ($boost_shares['views_boosted_pct'] ?? 0), 2),
                    number_format((float) ($boost_shares['enquiries_boosted_pct'] ?? 0), 2)
                ));
                ?>
            </p>
        </section>

        <h3><?php esc_html_e('Performance by Listing', 'nexdirectory'); ?></h3>
        <?php if (!empty($rows)) : ?>
            <div class="eep-table-wrap">
                <table class="eep-admin-table eep-responsive-table">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Listing', 'nexdirectory'); ?></th>
                            <th><?php esc_html_e('Boosted', 'nexdirectory'); ?></th>
                            <th><?php esc_html_e('Views', 'nexdirectory'); ?></th>
                            <th><?php esc_html_e('Phone', 'nexdirectory'); ?></th>
                            <th><?php esc_html_e('Website', 'nexdirectory'); ?></th>
                            <th><?php esc_html_e('WhatsApp', 'nexdirectory'); ?></th>
                            <th><?php esc_html_e('Enquiries', 'nexdirectory'); ?></th>
                            <th><?php esc_html_e('Map', 'nexdirectory'); ?></th>
                            <th><?php esc_html_e('Search', 'nexdirectory'); ?></th>
                            <th><?php esc_html_e('Conversion', 'nexdirectory'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($rows as $row) : ?>
                            <?php $title = sanitize_text_field((string) ($row['title'] ?? '')); ?>
                            <?php $row_boosted = !empty($row['is_boosted']); ?>
                            <tr>
                                <td data-label="<?php esc_attr_e('Listing', 'nexdirectory'); ?>">
                                    <a href="<?php echo esc_url((string) ($row['url'] ?? '#')); ?>"><?php echo esc_html($title !== '' ? $title : ('#' . (string) ((int) ($row['event_id'] ?? 0)))); ?></a>
                                </td>
                                <td data-label="<?php esc_attr_e('Boosted', 'nexdirectory'); ?>">
                                    <span class="eep-status-pill eep-status-<?php echo esc_attr($row_boosted ? 'publish' : 'draft'); ?>">
                                        <?php echo esc_html($row_boosted ? __('Yes', 'nexdirectory') : __('No', 'nexdirectory')); ?>
                                    </span>
                                </td>
                                <td data-label="<?php esc_attr_e('Views', 'nexdirectory'); ?>"><?php echo esc_html((string) ((int) ($row['listing_views'] ?? 0))); ?></td>
                                <td data-label="<?php esc_attr_e('Phone', 'nexdirectory'); ?>"><?php echo esc_html((string) ((int) ($row['click_phone'] ?? 0))); ?></td>
                                <td data-label="<?php esc_attr_e('Website', 'nexdirectory'); ?>"><?php echo esc_html((string) ((int) ($row['click_website'] ?? 0))); ?></td>
                                <td data-label="<?php esc_attr_e('WhatsApp', 'nexdirectory'); ?>"><?php echo esc_html((string) ((int) ($row['click_whatsapp'] ?? 0))); ?></td>
                                <td data-label="<?php esc_attr_e('Enquiries', 'nexdirectory'); ?>"><?php echo esc_html((string) ((int) ($row['enquiries_received'] ?? 0))); ?></td>
                                <td data-label="<?php esc_attr_e('Map', 'nexdirectory'); ?>"><?php echo esc_html((string) ((int) ($row['map_impressions'] ?? 0))); ?></td>
                                <td data-label="<?php esc_attr_e('Search', 'nexdirectory'); ?>"><?php echo esc_html((string) ((int) ($row['search_appearances'] ?? 0))); ?></td>
                                <td data-label="<?php esc_attr_e('Conversion', 'nexdirectory'); ?>"><?php echo esc_html((string) ((float) ($row['conversion_rate'] ?? 0))); ?>%</td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else : ?>
            <div class="eep-empty-state eep-owner-analytics-empty">
                <h3><?php esc_html_e('No analytics yet', 'nexdirectory'); ?></h3>
                <p><?php esc_html_e('Publish listings and share them to start collecting performance data.', 'nexdirectory'); ?></p>
                <a class="eep-btn eep-force-accent-action" href="<?php echo esc_url($events_url); ?>"><?php esc_html_e('Browse Listings', 'nexdirectory'); ?></a>
            </div>
        <?php endif; ?>
    </div>
</div>
