<?php

if ( ! current_user_can( 'seoaic_edit_plugin' ) ) {
    return;
}

use SEOAIC\SEOAIC;

global $SEOAIC, $SEOAIC_OPTIONS;

$get = wp_unslash( $_GET );

$adminUrl = SEOAIC::getAdminUrl( 'admin.php' );

$tab     = ! empty( $get['tab'] ) ? $get['tab'] : 'overview';
$orderby = ! empty( $get['orderby'] ) ? $get['orderby'] : 'date';
$order   = ! empty( $get['order'] ) ? $get['order'] : 'desc';
$search  = ! empty( $get['s'] ) ? $get['s'] : '';

$competitors_tab_search = ! empty( $get['cs'] ) ? $get['cs'] : '';

$create_from = ! empty( $get['created_date_from'] ) ? $get['created_date_from'] : '';
$create_to   = ! empty( $get['created_date_to'] ) ? $get['created_date_to'] : '';

$active_competitor = ! empty( $get['competitor'] ) ? $get['competitor'] : '';

$prompts = $SEOAIC->brand_visibility->getPrompts( [
    'orderby'           => $orderby,
    'order'             => $order,
    'search'            => $search,
    'created_date_from' => $create_from,
    'created_date_to'   => $create_to,
]);

$prompts_details = $SEOAIC->brand_visibility->getPromptsDetails();
$history = $SEOAIC->brand_visibility->getHistory();

if ( isset( $history['google_ai_overview'] ) ) {
    $history['Google AIO'] = $history['google_ai_overview'];
    unset( $history['google_ai_overview'] );
}

$config = $SEOAIC->brand_visibility->getConfig();

$mentions = [];
$sources  = [];
$total = 0;

foreach ($prompts_details as $entries) {
    foreach ($entries as $entry) {
        $mentions[$entry['source']] = 0;
        $total += 1;
    }
}


foreach ($prompts_details as $entries) {
    foreach ($entries as $entry) {
        $sources[] = $entry['source'];

        if ($entry['mentioned']) {
            $mentions[$entry['source']]++;
        }
    }
}

if( $prompts_details ){
    $ovaral_value = round( (array_sum($mentions) / (count($prompts_details) * count($mentions))) * 100 );
}else{
    $ovaral_value = 0;
}

$sources = array_values(array_unique($sources));

$competitors        = $config['data']['brand_tracking_competitors'] ?? [];
$main_brand         = $config['data']['brand_tracking_main_branding_words'] ?? [];
$competitors_data   = $SEOAIC->brand_visibility->getCompetitors() ?? [];

if( $competitors && !empty($competitors_data['data']) && is_array($competitors_data['data']) ){
    $competitors_data_by_id = array_column($competitors_data['data'], null, 'id');
}else{
    $competitors_data = [];
    $competitors_data_by_id = [];
}

$providers = $SEOAIC->brand_visibility->getProvidersList();
$providersByKey = array_column($providers, null, 'provider');
$activeProvidersCount    = count(array_filter($providers, fn($p) => $p['status'] === 'active'));
?>

<div id="seoaic-admin-container" class="wrap seoaic-brand-visibility-page">
    <h1 id="seoaic-admin-title">
        <?php
        echo wp_kses( seoai_get_logo( 'logo.svg' ), [
            'img' => [
                'title' => [],
                'src'   => [],
                'alt'   => [],
            ],
        ] );
        ?>
        <span>
            <?php echo esc_html( get_admin_page_title() ); ?>
        </span>
    </h1>

    <div id="seoaic-admin-body" class="seoaic-with-loader seoaic-loading">
        <div class="row full-width">
            <div class="col">
                <div class="inner">
                    <div class="seoaic-brand-visibility-page__body">
                        <div class="seoaic-brand-visibility-page__controls">
                            <div class="seoaic-brand-visibility-page__tabs">
                                <ul>
                                    <li class="seoaic-brand-visibility-page__tab <?php echo $tab === 'overview' ? 'active' : ''; ?>"
                                        data-tab="overview">
                                        <?php esc_html_e( 'Overview', 'seoai' ); ?>
                                    </li>

                                    <li class="seoaic-brand-visibility-page__tab <?php echo $tab === 'analysis' ? 'active' : ''; ?>"
                                        data-tab="analysis">
                                        <?php esc_html_e( 'Detailed Analysis', 'seoai' ); ?>
                                    </li>

                                    <li class="seoaic-brand-visibility-page__tab <?php echo $tab === 'competitors' ? 'active' : ''; ?>"
                                        data-tab="competitors">
                                        <?php esc_html_e( 'Competitors', 'seoai' ); ?>
                                    </li>
                                </ul>
                            </div>
                            <div class="seoaic-brand-visibility-page__actions">
                                <?php if ( isset($config['data']['brand_tracking_max_prompts_limit']) && $config['data']['brand_tracking_max_prompts_limit'] > 0 ): ?>
                                    <button class="seoaic-brand-visibility-page__actions-button modal-button"
                                            data-modal="#seoaic-brand-visibility-modal">
                                        <?php esc_html_e( 'Generate Prompts', 'seoaic' ); ?>
                                    </button>
                                    <button class="seoaic-brand-visibility-page__actions-button modal-button"
                                            data-modal="#seoaic-brand-visibility-manual-prompts-generate-modal">
                                        <?php esc_html_e( 'Add Prompts', 'seoaic' ); ?>
                                    </button>
                                    <button class="seoaic-brand-visibility-page__actions-button modal-button"
                                            data-modal="#seoaic-brand-visibility-competitor-modal">
                                        <?php esc_html_e( 'Setup Brands', 'seoaic' ); ?>
                                    </button>
                                <?php else: ?>
                                    <button class="seoaic-brand-visibility-page__actions-button modal-button"
                                            data-modal="#seoaic-alert-modal"
                                            data-content="<?php esc_html_e('You don’t have permission to generate prompts'); ?>">
                                        <?php esc_html_e( 'Generate Prompts', 'seoaic' ); ?>
                                    </button>
                                <?php endif;?>
                                <a href="<?php echo admin_url('admin.php?page=seoaic-brand-sentiment-analysis'); ?>" class="seoaic-brand-visibility-page__actions-button outline">
                                    <?php esc_html_e( 'Sentiment Analysis →', 'seoaic' ); ?>
                                </a>
                            </div>
                        </div>

                        <div class="seoaic-brand-visibility-page__tab-content seoaic-brand-visibility-page__overview <?php echo $tab === 'overview' ? 'active' : ''; ?>"
                             data-tab-id="overview">
                            <div class="seoaic-brand-visibility-page__overview-items">
                                <div class="seoaic-brand-visibility-page__overview-item">
                                    <div class="seoaic-brand-visibility-page__overview-item-graph">
                                        <div id="seoaic-brand-visibility-page__overview-item-graph-chart">
                                            <div class="graph">
                                                <div class="pie no-round" style="--p: <?php echo $ovaral_value ? $ovaral_value : 0; ?>;"></div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="seoaic-brand-visibility-page__overview-item-content">
                                        <h3 class="seoaic-brand-visibility-page__overview-item__title"> <?php esc_html_e( 'Overall AI Visibility', 'seoaic' ); ?></h3>
                                        <p class="seoaic-brand-visibility-page__overview-item__value"><?php echo $ovaral_value ? $ovaral_value : 0; ?>%</p>
                                        <p class="seoaic-brand-visibility-page__overview-item__description"><?php esc_html_e( 'Based on current tracking', 'seoaic' ); ?></p>
                                    </div>
                                </div>
                                <div class="seoaic-brand-visibility-page__overview-item">
                                    <div class="seoaic-brand-visibility-page__overview-item-graph">
                                        <div id="seoaic-brand-visibility-page__overview-item-graph-chart">
                                            <div class="graph">
                                                <div class="pie no-round" style="--p: calc( (<?php echo $prompts_details ? count( $prompts_details ) : 0; ?> / 200) * 100);"></div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="seoaic-brand-visibility-page__overview-item-content">
                                        <h3 class="seoaic-brand-visibility-page__overview-item__title"><?php esc_html_e( 'Total Prompts Tracked', 'seoaic' ); ?></h3>
                                        <p class="seoaic-brand-visibility-page__overview-item__value">
                                            <?php echo $prompts_details ? count( $prompts_details ) : 0; ?>
                                            /
                                            <?php echo isset( $config['data']['brand_tracking_max_prompts_limit'] ) ? $config['data']['brand_tracking_max_prompts_limit'] : 0; ?>
                                        </p>
                                        <div class="seoaic-brand-visibility-page__overview-item__description">
                                            <?php esc_html_e( 'Across all analyses', 'seoaic' ); ?>
                                            <?php if( $prompts_details && count( $prompts_details ) > $config['data']['brand_tracking_max_prompts_limit'] ): ?>
                                                <a href=""><?php esc_html_e( 'Ask for more', 'seoaic' ); ?></a>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <?php if ( !empty($providers) && is_array($providers) ): ?>
                                <?php
                                    $providers_order = ['active', 'requested', 'available', 'no_available', 'disabled'];

                                    usort($providers, function($a, $b) use ($providers_order) {
                                        $posA = array_search($a['status'], $providers_order);
                                        $posB = array_search($b['status'], $providers_order);
                                        return $posA <=> $posB;
                                    });
                                ?>
                                <div class="seoaic-brand-visibility-page__overview-items">
                                    <?php foreach ( $providers as $provider ): ?>


                                        <?php
                                        $provKey = isset($provider['provider']) ? (string)$provider['provider'] : '';
                                        if ($provKey === '') continue;
                                        $source  = strtolower($provKey) === 'google_ai_overview' ? 'Google AIO' : $provKey;
                                        $status  = isset($provider['status']) ? strtolower($provider['status']) : 'inactive';
                                        $mention = (!empty($mentions) && isset($mentions[$provKey])) ? (int)$mentions[$provKey] : 0;

                                        if( $status === 'disabled' ) continue;
                                        ?>

                                        <?php if ( $status === 'active' ): ?>
                                            <div class="seoaic-brand-visibility-page__overview-item">
                                                <div class="seoaic-brand-visibility-page__overview-item-content">
                                                    <h3 class="seoaic-brand-visibility-page__overview-item__title <?php echo esc_attr(str_replace(' ', '-', strtolower($source)) . '-icon'); ?>">
                                                        <?php echo esc_html(ucfirst($source)); ?>
                                                    </h3>
                                                    <p class="seoaic-brand-visibility-page__overview-item__value">
                                                        <?php echo esc_html($mention); ?> <?php esc_html_e('Mentions', 'seoaic'); ?>
                                                    </p>
                                                    <div class="seoaic-brand-visibility-page__overview-item__description">
                                                        <?php esc_html_e('Tracked mentions', 'seoaic'); ?>
                                                    </div>
                                                </div>
                                            </div>

                                        <?php elseif ( $status === 'requested' || $status === 'no_available' ): ?>
                                            <div class="seoaic-brand-visibility-page__overview-item">
                                                <div class="seoaic-brand-visibility-page__overview-item-content">
                                                    <h3 class="seoaic-brand-visibility-page__overview-item__title <?php echo esc_attr(str_replace(' ', '-', strtolower($source)) . '-icon'); ?>">
                                                        <?php echo esc_html(ucfirst($source)); ?>
                                                    </h3>
                                                    <p><b><?php esc_html_e('Access request sent', 'seoaic'); ?></b><br>
                                                        <?php esc_html_e('Your request is being reviewed.', 'seoaic'); ?></p>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <div class="seoaic-brand-visibility-page__overview-item">
                                                <div class="seoaic-brand-visibility-page__overview-item-content">
                                                    <h3 class="seoaic-brand-visibility-page__overview-item__title <?php echo esc_attr(str_replace(' ', '-', strtolower($source)) . '-icon'); ?>">
                                                        <?php echo esc_html(ucfirst($source)); ?>
                                                    </h3>
                                                    <p><b><?php esc_html_e('Want access to this model?', 'seoaic'); ?></b><br>
                                                        <?php esc_html_e('Contact our customer support team to request activation', 'seoaic'); ?></p>
                                                    <div class="seoaic-brand-visibility-page__overview-item__description">
                                                        <button class="modal-button" data-modal="#seoaic-brand-visibility-models-request-modal">
                                                            <?php esc_html_e( 'Request model access', 'seoaic' ); ?>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>

                            <div class="seoaic-brand-visibility-page__overview-items">
                                <div class="seoaic-brand-visibility-page__overview-wide-item">
                                    <div class="seoaic-brand-visibility-page__overview-wide-item-graph"
                                         id="seoaic-brand-visibility-chart" data-chart='<?php echo esc_attr(json_encode($history)); ?>'></div>
                                </div>
                            </div>
                        </div>
                        <div class="seoaic-brand-visibility-page__tab-content seoaic-brand-visibility-page__analysis <?php echo $tab === 'analysis' ? 'active' : ''; ?>"
                             data-tab-id="analysis">
                            <div class="seoaic-brand-visibility-page__analysis-filters">
                                <div class="seoaic-brand-visibility-page__analysis-filters-row">
                                    <div class="seoaic-brand-visibility-page__analysis-filter brand-visibility-col-1">
                                        <span class="seoaic-brand-visibility-page__analysis-filter__selected-count">
                                             <?php if ( ! empty( $prompts ) ): ?>
                                                 <?php esc_html_e( 'Selected:', 'seoai' ); ?> 0
                                             <?php endif; ?>
                                        </span>
                                    </div>
                                    <div class="seoaic-brand-visibility-page__analysis-filter brand-visibility-col-4">
                                        <div class="seoaic-brand-visibility-page__analysis-filter__mass_actions">
                                            <button class="seoaic-brand-visibility-page__analysis-filter__mass_actions-button run-action analyze-prompts-button">
                                                <?php esc_html_e( 'Analyze Prompts', 'seoaic' ); ?>
                                            </button>

                                            <button class="seoaic-brand-visibility-page__analysis-filter__mass_actions-button update-action modal-button confirm-modal-button"
                                                    data-modal="#seoaic-brand-visibility-groups-modal">
                                                <?php esc_html_e( 'Change Group', 'seoai' ); ?>
                                            </button>

                                            <button
                                                    class="seoaic-brand-visibility-page__analysis-filter__mass_actions-button remove-action modal-button confirm-modal-button"
                                                    data-modal="#seoaic-confirm-modal"
                                                    data-action="seoaic_remove_prompts"
                                                    data-form-callback="window_reload"
                                                    data-content="Do you want to remove selected prompts?">
                                                <?php esc_html_e( 'Remove Selected', 'seoai' ); ?>
                                            </button>
                                        </div>
                                    </div>

                                    <div class="seoaic-brand-visibility-page__analysis-filter brand-visibility-col-7 align-right">
                                        <div class="search">
                                            <input id="ideas_search_input" type="text" placeholder="Enter a prompt"
                                                   value="<?php echo $search; ?>">
                                            <a href="" id="ideas_search_do_search" class="seoaic-filter-btn"></a>
                                        </div>

                                        <div class="date-filter">
                                            <div class="f-date">
                                                <div class="position-relative">
                                                    <input type="text" name="created_date_from" value="<?php echo $create_from; ?>"
                                                           class="mt-0 seoaic-form-item form-input" placeholder="Created from">
                                                    <div class="picker-call"></div>
                                                </div>
                                            </div>
                                            <div class="f-date">
                                                <div class="position-relative">
                                                    <input type="text" name="created_date_to" value="<?php echo $create_to; ?>"
                                                           class="mt-0 seoaic-form-item form-input" placeholder="Created to">
                                                    <div class="picker-call"></div>
                                                </div>
                                            </div>
                                            <div class="f-btn">
                                                <a href="<?php echo esc_url( $adminUrl ); ?>?page=seoaic-brand-visibility&tab=analysis"
                                                   class="filter-clear-btn filter-btn" title="Clear all filters"></a>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <?php if ( empty( $prompts ) ): ?>
                                    <div class="seoaic-brand-visibility-page__analysis-filters-row mt-20">
                                        <h3 class="seoaic-brand-visibility-page__analysis-filter__selected-count">
                                            <?php esc_html_e( 'No prompts found', 'seoai' ); ?>
                                        </h3>
                                    </div>
                                <?php endif; ?>

                            </div>
                            <?php if ( ! empty( $prompts ) ): ?>
                                <div class="seoaic-brand-visibility-page__analysis-table">
                                    <div class="seoaic-brand-visibility-page__analysis-table-head-row">
                                        <div class="seoaic-brand-visibility-page__analysis-table-head-row-content">
                                            <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-4">
                                                <div class="check check-all">
                                                    <input type="checkbox">
                                                </div>

                                                <div class="sortable seoaic-brand-visibility-page__analysis-table-col" data-orderby="prompt" <?php echo $orderby === 'prompt' ? 'data-order="' . $order . '"' : ''; ?>>
                                                    <span><?php esc_html_e( 'Prompt', 'seoai' ); ?></span>
                                                </div>
                                            </div>
                                            <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-1 sortable"
                                                 data-orderby="date"
                                                <?php echo $orderby === 'date' ? 'data-order="' . $order . '"' : ''; ?>>
                                                <span><?php esc_html_e( 'Date', 'seoai' ); ?></span>
                                            </div>
                                            <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-2 sortable"
                                                 data-orderby="group"
                                                <?php echo $orderby === 'group' ? 'data-order="' . $order . '"' : ''; ?>>
                                                <span><?php esc_html_e( 'Group', 'seoai' ); ?></span>
                                            </div>
                                            <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-1 sortable"
                                                 data-orderby="overall"
                                                <?php echo $orderby === 'overall' ? 'data-order="' . $order . '"' : ''; ?>>
                                                <span><?php esc_html_e( 'Overall', 'seoai' ); ?></span>
                                            </div>

                                            <?php if ( !empty($providers) && is_array($providers) ): ?>
                                                <?php
                                                    $providers_order = ['active', 'requested', 'available', 'no_available'];

                                                    usort($providers, function($a, $b) use ($providers_order) {
                                                        $posA = array_search($a['status'], $providers_order);
                                                        $posB = array_search($b['status'], $providers_order);
                                                        return $posA <=> $posB;
                                                    });
                                                ?>
                                                <?php foreach ( $providers as $provider ): ?>
                                                    <?php if( $provider['status'] === 'active' ): ?>
                                                        <?php $source = strtolower( $provider['provider'] ) === 'google_ai_overview' ? 'Google AIO' : $provider['provider']; ?>
                                                        <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-1 sortable"
                                                             data-orderby="provider-<?= $provider['provider'];  ?>"
                                                            <?php echo $orderby === 'provider-' . $provider['provider'] ? 'data-order="' . $order . '"' : ''; ?>>
                                                            <span><?php echo esc_html( ucfirst( $source ) ); ?></span>
                                                        </div>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            <?php else: ?>
                                                <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-<?php echo $activeProvidersCount; ?>"></div>
                                            <?php endif; ?>

                                            <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-1 align-right">
                                                <span><?php esc_html_e( 'Actions', 'seoai' ); ?></span>
                                            </div>
                                        </div>
                                    </div>

                                    <?php foreach ( $prompts as $prompt ): ?>
                                        <div class="seoaic-brand-visibility-page__analysis-table-row" id="seoaic-brand-visibility-prompt-<?php echo isset( $prompt['id'] ) ? (int) $prompt['id'] : '' ?>">
                                            <div class="seoaic-brand-visibility-page__analysis-table-row-content">
                                                <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-4">
                                                    <div class="check"><input type="checkbox" value="<?php echo isset( $prompt['id'] ) ? (int) $prompt['id'] : '' ?>"></div>
                                                    <span><?php echo esc_html( $prompt['prompt'] ) ?></span>
                                                </div>
                                                <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-1">
                                                    <span><?php echo esc_html( date( 'd.m.Y', strtotime( $prompt['created_at'] ) ) ) ?></span>
                                                </div>
                                                <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-2">
                                                    <button title="Change Group"
                                                            class="seoaic-brand-visibility-page__analysis-btn__group modal-button"
                                                            data-modal="#seoaic-brand-visibility-groups-modal"
                                                            data-prompt-id="<?php echo isset( $prompt['id'] ) ? (int) $prompt['id'] : '' ?>"
                                                            data-prompts-group="<?php echo isset( $prompt['group'] ) ? esc_attr( $prompt['group'] ) : '' ?>"
                                                    >
                                                        <?php echo esc_html( $prompt['group'] ?? '' ) ?>
                                                        <div class="dn edit-form-items">
                                                            <input type="hidden"
                                                                   name="keyword_id"
                                                                   value="<?php echo isset( $prompt['id'] ) ? (int) $prompt['id'] : '' ?>">
                                                        </div>
                                                    </button>
                                                </div>

                                                <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-1">
                                                    <span class="seoaic-brand-visibility-page__analysis__label <?php echo esc_html( $prompt['status'] ) ?>">
                                                        <?php if( isset( $prompt['status'] ) && $prompt['status'] === 'scanning') : ?>
                                                            <?php echo esc_html( 'Scanning' ); ?>
                                                        <?php elseif( isset( $prompt['status'] ) && $prompt['status'] === 'scanned' ) : ?>
                                                            <?php echo esc_html( 'Scanned' ); ?>
                                                        <?php else : ?>
                                                            <?php echo esc_html( 'No data' ); ?>
                                                        <?php endif; ?>
                                                    </span>
                                                </div>

                                                <?php if( isset( $prompts_details[ $prompt['id'] ] ) ) : ?>
                                                    <?php
                                                    $details = $prompts_details[$prompt['id']] ?? [];
                                                    $bySource = array_column($details, null, 'source');

                                                    foreach ($providersByKey as $provider => $info) {
                                                        if (!isset($bySource[$provider])) {
                                                            $bySource[$provider] = [
                                                                'id' => null,
                                                                'source' => $provider,
                                                                'mentioned' => false,
                                                                'simulated_response' => '',
                                                                'entity_featured' => null,
                                                            ];
                                                        }
                                                    }

                                                    $prompts_details[$prompt['id']] = array_values($bySource);
                                                        usort($prompts_details[ $prompt['id'] ], function($a, $b) {
                                                            return strcmp(strtolower($a['source']), strtolower($b['source']));
                                                        });
                                                    ?>
                                                    <?php foreach ( $prompts_details[ $prompt['id'] ] as $prompt_detail ) : ?>
                                                        <?php if (!empty($providersByKey[$prompt_detail['source']]['status']) && $providersByKey[$prompt_detail['source']]['status'] === 'active'): ?>
                                                            <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-1 ">
                                                                <span
                                                                        data-source="<?php esc_html_e( $prompt_detail['source'] ) ?>"
                                                                        data-mentioned="<?php echo $prompt_detail['mentioned'] ? '1' : '0' ?>"
                                                                        class="seoaic-brand-visibility-page__analysis__label <?php esc_html( $prompt_detail['mentioned'] ) ?> <?php echo $prompt_detail['mentioned'] ? 'highly-likely' : 'not-mentioned' ?>">
                                                                    <?php echo $prompt_detail['mentioned'] ? esc_html( 'Mentioned' ) : esc_html( 'Not Mentioned' ) ?>
                                                                </span>
                                                            </div>
                                                        <?php endif; ?>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-<?php echo $activeProvidersCount ?>"></div>
                                                <?php endif; ?>

                                                <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-1 align-right">
                                                    <button title="Prompt details" type="button" class="seoaic-details"></button>
                                                    <button title="Remove prompt" type="button" class="seoaic-remove modal-button confirm-modal-button"
                                                            data-modal="#seoaic-confirm-modal"
                                                            data-action="seoaic_remove_prompts"
                                                            data-content="Do you want to remove prompt?"
                                                            data-form-callback="window_reload"
                                                            data-prompt-id="<?php echo isset( $prompt['id'] ) ? (int) $prompt['id'] : '' ?>">
                                                    </button>
                                                </div>
                                            </div>

                                            <div class="seoaic-brand-visibility-page__analysis-table-row-hidden-content">
                                                <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-6 fd-column align-left">
                                                    <h4><?php echo esc_html( 'Simulated AI Platform Responses' ) ?></h4>

                                                    <div class="seoaic-brand-visibility-page__analysis-table__tabs">
                                                        <ul>
                                                            <?php if( isset( $prompts_details[ $prompt['id'] ] ) ) : ?>
                                                                <?php
                                                                usort($prompts_details[ $prompt['id'] ], function($a, $b) {
                                                                    return strcmp(strtolower($a['source']), strtolower($b['source']));
                                                                });
                                                                ?>
                                                                <?php foreach ( $prompts_details[ $prompt['id'] ] as $key => $prompt_detail ) : ?>
                                                                    <?php if (!empty($providersByKey[$prompt_detail['source']]['status']) && $providersByKey[$prompt_detail['source']]['status'] === 'active'): ?>
                                                                        <li class="seoaic-brand-visibility-page__analysis-table__tab<?php echo $key === 0 ? ' active' : ''; ?><?php echo $prompt_detail['mentioned'] ? ' highly-likely' : ' not-mentioned' ?>"
                                                                            data-tab="<?php echo $prompt_detail['source'] ?>">

                                                                            <?php $prompt_detail['source'] = strtolower( $prompt_detail['source'] ) === 'google_ai_overview' ? 'Google AIO' : $prompt_detail['source']; ?>
                                                                            <?php echo esc_html(  ucfirst( $prompt_detail['source'] ) );  ?>
                                                                        </li>
                                                                    <?php endif; ?>
                                                                <?php endforeach; ?>
                                                            <?php endif; ?>
                                                        </ul>
                                                    </div>

                                                    <?php if( isset( $prompts_details[ $prompt['id'] ] ) ) : ?>
                                                        <?php foreach ( $prompts_details[ $prompt['id'] ] as $key => $prompt_detail ) : ?>
                                                            <?php if (!empty($providersByKey[$prompt_detail['source']]['status']) && $providersByKey[$prompt_detail['source']]['status'] === 'active'): ?>
                                                                <div class="seoaic-brand-visibility-page__analysis-table__tab-content<?php echo $key === 0 ? ' active' : '' ?>"
                                                                     data-tab="<?php echo $prompt_detail['source'] ?>">
                                                                    <?php echo $SEOAIC->brand_visibility::mdToHTML(  $prompt_detail['simulated_response']  ); ?>
                                                                </div>
                                                            <?php endif; ?>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>
                                                </div>

                                                <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-6 fd-column align-left">
                                                    <h4><?php echo esc_html( 'Entities Featured on AI Platforms' ) ?></h4>

                                                    <div class="seoaic-brand-visibility-page__analysis-table__tabs">
                                                        <ul>
                                                            <?php if( isset( $prompts_details[ $prompt['id'] ] ) ) : ?>
                                                                <?php foreach ( $prompts_details[ $prompt['id'] ] as $key => $prompt_detail ) : ?>
                                                                    <?php if (!empty($providersByKey[$prompt_detail['source']]['status']) && $providersByKey[$prompt_detail['source']]['status'] === 'active'): ?>
                                                                        <li class="seoaic-brand-visibility-page__analysis-table__tab<?php echo $key === 0 ? ' active' : '' ?><?php echo $prompt_detail['mentioned'] ? ' highly-likely' : ' not-mentioned' ?>"
                                                                            data-tab="<?php echo $prompt_detail['source'] ?>">
                                                                            <?php $prompt_detail['source'] = strtolower( $prompt_detail['source'] ) === 'google_ai_overview' ? 'Google AIO' : $prompt_detail['source']; ?>
                                                                            <?php echo esc_html(  ucfirst( $prompt_detail['source'] ) );  ?>
                                                                        </li>
                                                                    <?php endif; ?>
                                                                <?php endforeach; ?>
                                                            <?php endif; ?>
                                                        </ul>
                                                    </div>

                                                    <?php if( isset( $prompts_details[ $prompt['id'] ] ) ) : ?>
                                                        <?php foreach ( $prompts_details[ $prompt['id'] ] as $key => $prompt_detail ) : ?>
                                                            <?php if (!empty($providersByKey[$prompt_detail['source']]['status']) && $providersByKey[$prompt_detail['source']]['status'] === 'active'): ?>
                                                                <div class="seoaic-brand-visibility-page__analysis-table__tab-content<?php echo $key === 0 ? ' active' : '' ?>"
                                                                     data-tab="<?php echo $prompt_detail['source'] ?>">
                                                                    <?php echo $SEOAIC->brand_visibility::mdToHTML(  $prompt_detail['entity_featured']  ); ?>
                                                                </div>
                                                            <?php endif; ?>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>
                                                </div>

                                                <?php if( isset($competitors_data_by_id[ $prompt['id'] ] ) ): ?>
                                                    <div class="seoaic-brand-visibility-page__analysis-table-col brand-visibility-col-12 fd-column align-left">
                                                    <h4><?php echo esc_html( 'All Links in This Response' ) ?></h4>

                                                        <?php if ( ! empty(  $competitors_data_by_id[ $prompt['id'] ]['results'] ) ): ?>
                                                            <div class="seoaic-brand-visibility-page__analysis-table__links-table">
                                                                <div class="seoaic-brand-visibility-page__analysis-table__links-table-head-row">
                                                                    <div class="brand-visibility-col-6 seoaic-brand-visibility-page__analysis-table__links-table-col">
                                                                        <span><?php echo esc_html( 'Domain' ) ?></span>
                                                                    </div>
                                                                    <div class="brand-visibility-col-2 seoaic-brand-visibility-page__analysis-table__links-table-col">
                                                                        <span><?php echo esc_html( 'First Seen' ) ?></span>
                                                                    </div>
                                                                    <div class="brand-visibility-col-2 seoaic-brand-visibility-page__analysis-table__links-table-col">
                                                                        <span><?php echo esc_html( 'Sources' ) ?></span>
                                                                    </div>
                                                                    <div class="brand-visibility-col-2 seoaic-brand-visibility-page__analysis-table__links-table-col">
                                                                        <span><?php echo esc_html( 'Frequency in Response' ) ?></span>
                                                                    </div>
                                                                </div>

                                                                <?php foreach ( $competitors_data_by_id[ $prompt['id'] ]['results'] as $competitor ): ?>
                                                                    <?php if ( ! empty( $competitor['mentioned_urls'] ) ): ?>
                                                                        <?php foreach ( $competitor['mentioned_urls'] as $urlData ):
                                                                            $url      = $urlData['competitor'];
                                                                            $domain   = parse_url( $url, PHP_URL_HOST );
                                                                            $firstSeen = ! empty( $urlData['created_at'] ) ? date( 'd.m.Y', strtotime( $urlData['created_at'] ) ) : '-';
                                                                            $frequency = $urlData['frequency'] ?? 0;
                                                                            $tag       = $urlData['tag'] ?? 'Neutral';
                                                                            ?>
                                                                            <div class="seoaic-brand-visibility-page__analysis-table__links-table-row">
                                                                                <div class="brand-visibility-col-6">
                                                                                    <div class="seoaic-brand-visibility-page__analysis-table__links-table-domain">
                                                                                        <a class="seoaic-brand-visibility-page__analysis-table__links-table-link"
                                                                                           href="<?php echo esc_url( $url ); ?>"
                                                                                           data-url="<?php echo esc_url( $url ); ?>"
                                                                                           data-first-seen="<?php echo esc_attr( $firstSeen ); ?>">
                                                                                            <?php echo esc_html( $domain ); ?>
                                                                                        </a>
                                                                                        <span class="seoaic-brand-visibility-page__analysis-table__links-table-tag">
                                                                                            <?php echo esc_html( strtoupper( $tag ) ); ?>
                                                                                        </span>
                                                                                    </div>
                                                                                </div>
                                                                                <div class="brand-visibility-col-2">
                                                                                    <span class="seoaic-brand-visibility-page__analysis-table__links-table-date">
                                                                                        <?php echo esc_html( $firstSeen ); ?>
                                                                                    </span>
                                                                                </div>
                                                                                <div class="brand-visibility-col-2">
                                                                                    <span><?php echo esc_html( ucfirst( $competitor['source'] ) ); ?></span>
                                                                                </div>
                                                                                <div class="brand-visibility-col-2">
                                                                                    <span>x<?php echo intval( $frequency ); ?></span>
                                                                                </div>
                                                                            </div>
                                                                        <?php endforeach; ?>
                                                                    <?php endif; ?>
                                                                <?php endforeach; ?>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="seoaic-brand-visibility-page__tab-content seoaic-brand-visibility-page__competitors <?php echo $tab === 'competitors' ? 'active' : ''; ?>"
                             data-tab-id="competitors">
                            <div class="seoaic-brand-visibility-page__competitors-filters">
                                <div class="seoaic-brand-visibility-page__competitors-filters-row">
                                    <div class="seoaic-brand-visibility-page__competitors-filter brand-visibility-col-1"></div>
                                    <div class="seoaic-brand-visibility-page__competitors-filter brand-visibility-col-4">

                                    </div>

                                    <div class="seoaic-brand-visibility-page__competitors-filter brand-visibility-col-7 align-right">
                                        <div class="search">
                                            <input id="ideas_search_input" type="text" placeholder="Enter a prompt"
                                                   value="<?php echo $competitors_tab_search; ?>">
                                            <a href="" id="ideas_search_do_search" class="seoaic-filter-btn"></a>
                                        </div>

                                        <div class="date-filter">
                                            <div class="f-btn">
                                                <a href="<?php echo esc_url( $adminUrl ); ?>?page=seoaic-brand-visibility&tab=competitors"
                                                   class="filter-clear-btn filter-btn" title="Clear all filters"></a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="seoaic-brand-visibility-page__competitors-overview">
                                <div class="seoaic-brand-visibility-page__competitors-table brand-visibility-col-5">
                                    <div class="seoaic-brand-visibility-page__competitors-table-head-row">
                                        <div class="seoaic-brand-visibility-page__competitors-table-col brand-visibility-col-5 sortable" data-orderby="competitor"
                                            <?php echo $orderby === 'competitor' ? 'data-order="' . $order . '"' : ''; ?>>
                                            <span>Competitor</span>
                                        </div>
                                        <div class="seoaic-brand-visibility-page__competitors-table-col brand-visibility-col-2 sortable" data-orderby="mentions"
                                            <?php echo $orderby === 'mentions' ? 'data-order="' . $order . '"' : ''; ?>>
                                            <span>Mentions</span>
                                        </div>
                                        <div class="seoaic-brand-visibility-page__competitors-table-col brand-visibility-col-2 sortable" data-orderby="presence"
                                            <?php echo $orderby === 'presence' ? 'data-order="' . $order . '"' : ''; ?>>
                                            <span>Presence</span>
                                        </div>
                                        <div class="seoaic-brand-visibility-page__competitors-table-col brand-visibility-col-2 sortable" data-orderby="visibility"
                                            <?php echo $orderby === 'visibility' ? 'data-order="' . $order . '"' : ''; ?>>
                                            <span>Visibility</span>
                                        </div>
                                        <div class="seoaic-brand-visibility-page__competitors-table-col brand-visibility-col-1">
                                            <span>Actions</span>
                                        </div>
                                    </div>
                                    <?php
                                    $stats = [];

                                    if ( ! empty( $competitors_data['stats'] ) ) {
                                        foreach ( $competitors_data['stats'] as $key => $val ) {
                                            $percentage = $total > 0 ? ( $val / $total ) * 100 : 0;
                                            $score = $percentage > 66 ? 'High' : ( $percentage > 33 ? 'Medium' : 'Low' );

                                            $stats[] = [
                                                'competitor' => $key,
                                                'mentions' => $val,
                                                'presence' => $percentage,
                                                'visibility' => $score,
                                            ];
                                        }

                                        usort($stats, function ($a, $b) use ($orderby, $order) {
                                            $a_val = $a[$orderby] ?? null;
                                            $b_val = $b[$orderby] ?? null;

                                            if ( $orderby === 'visibility' ) {
                                                $weights = [ 'Low' => 1, 'Medium' => 2, 'High' => 3 ];
                                                $a_val = $weights[$a_val] ?? 0;
                                                $b_val = $weights[$b_val] ?? 0;
                                            }

                                            if ( is_string($a_val) ) {
                                                $result = strcmp(mb_strtolower($a_val), mb_strtolower($b_val));
                                            } else {
                                                $result = $a_val <=> $b_val;
                                            }

                                            return $order === 'desc' ? -$result : $result;
                                        });
                                    }
                                    ?>

                                    <?php if ( ! empty( $stats ) ): ?>
                                        <?php foreach ( $stats as $item ): ?>
                                            <div class="seoaic-brand-visibility-page__competitors-table-row <?php echo $item['competitor'] === $active_competitor ? 'active' : '' ?>" data-competitor="<?php echo esc_attr( $item['competitor'] ); ?>">
                                                <div class="seoaic-brand-visibility-page__competitors-table-col brand-visibility-col-5">
                                                    <div class="seoaic-brand-visibility-page__competitors-table-competitor-info">
                                                        <h4><?php echo esc_html( $item['competitor'] ); ?></h4>
                                                    </div>
                                                </div>
                                                <div class="seoaic-brand-visibility-page__competitors-table-col brand-visibility-col-2">
                                                    <span><?php echo esc_html( $item['mentions'] ); ?> / <?php echo esc_html( $total ); ?></span>
                                                </div>
                                                <div class="seoaic-brand-visibility-page__competitors-table-col brand-visibility-col-2">
                                                    <span><?php echo number_format( $item['presence'], 2 ); ?>%</span>
                                                </div>
                                                <div class="seoaic-brand-visibility-page__competitors-table-col brand-visibility-col-2">
                                                    <span><?php echo esc_html( $item['visibility'] ); ?></span>
                                                </div>
                                                <div class="seoaic-brand-visibility-page__competitors-table-col brand-visibility-col-1">
                                                    <div class="flex-right">
                                                        <button data-competitor="<?php echo esc_attr( $item['competitor'] ); ?>" type="button" class="seoaic-remove"></button>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div class="seoaic-brand-visibility-page__competitors-table-row">
                                            <div class="seoaic-brand-visibility-page__competitors-table-col brand-visibility-col-12">
                                                <div class="seoaic-brand-visibility-page__competitors-table-competitor-info">
                                                    <h4><?php esc_html_e( 'No competitors found', 'seoaic' ); ?></h4>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div class="seoaic-brand-visibility-page__competitors-prompts-table brand-visibility-col-7">
                                    <div class="seoaic-brand-visibility-page__competitors-prompts-table-head-row">
                                        <div class="seoaic-brand-visibility-page__competitors-prompts-table-col brand-visibility-col-6 sortable" data-orderby="prompt"
                                            <?php echo $orderby === 'prompt' ? 'data-order="' . $order . '"' : ''; ?>>
                                            <span><?php esc_html_e( 'Prompt', 'seoaic' ); ?></span>
                                        </div>
                                        <div class="seoaic-brand-visibility-page__competitors-prompts-table-col brand-visibility-col-3">
                                            <span><?php esc_html_e( 'AI Source', 'seoaic' ); ?></span>
                                        </div>
                                        <div class="seoaic-brand-visibility-page__competitors-prompts-table-col brand-visibility-col-3">
                                            <span><?php esc_html_e( 'Top 3 Referenced Domains', 'seoaic' ); ?></span>
                                        </div>
                                    </div>
                                    <?php
                                    $filtered_items = [];

                                    if ( ! empty( $competitors_data['data'] ) ) {
                                        foreach ( $competitors_data['data'] as $item ) {
                                            $mentioned_brands = [];
                                            $sources = [];

                                            if ( ! empty( $item['results'] ) ) {
                                                foreach ( $item['results'] as $result ) {
                                                    if ( ! empty( $result['mentioned_brands'] ) && is_array( $result['mentioned_brands'] ) ) {
                                                        $mentioned_brands = array_merge( $mentioned_brands, $result['mentioned_brands'] );
                                                        $sources[] = ucfirst( $result['source'] );
                                                    }
                                                }
                                            }

                                            if ( empty( $mentioned_brands ) ) {
                                                continue;
                                            }

                                            $mentioned_brands   = array_unique( $mentioned_brands );

                                            $mentioned_lower = array_map('mb_strtolower', $mentioned_brands);
                                            $main_lower      = array_map('mb_strtolower', $main_brand);

                                            $main_indexes = array_keys(array_intersect($mentioned_lower, $main_lower));
                                            $competitor_indexes = array_diff(array_keys($mentioned_lower), $main_indexes);

                                            $main_terms        = array_intersect_key($mentioned_brands, array_flip($main_indexes));
                                            $competitor_terms  = array_intersect_key($mentioned_brands, array_flip($competitor_indexes));

                                            $sources = array_unique($sources);

                                            $sources = array_map(function($src) {
                                                return strcasecmp($src, 'Google_ai_overview') === 0 ? 'Google AIO' : $src;
                                            }, $sources);

                                            $sources_string = implode(', ', $sources );

                                            if ( ! empty( $active_competitor ) && ! in_array( $active_competitor, $mentioned_brands ) ) {
                                                continue;
                                            }

                                            if (
                                                ! empty( $competitors_tab_search ) &&
                                                stripos( strip_tags( $item['prompt'] ?? '' ), $competitors_tab_search ) === false
                                            ) {
                                                continue;
                                            }
                                            $filtered_items[] = [
                                                'id' => $item['id'],
                                                'prompt' => $item['prompt'],
                                                'sources_string' => $sources_string,
                                                'competitors' => $competitor_terms,
                                                'brands' => $main_terms,
                                            ];
                                        }


                                        if ( $orderby === 'prompt' ) {
                                            usort($filtered_items, function ($a, $b) use ( $order ) {
                                                $result = strcmp(mb_strtolower($a['prompt']), mb_strtolower($b['prompt']));
                                                return $order === 'desc' ? -$result : $result;
                                            });
                                        }
                                    }
                                    ?>

                                    <?php if ( ! empty( $filtered_items ) ): ?>
                                        <?php foreach ( $filtered_items as $filtered ): ?>
                                            <div class="seoaic-brand-visibility-page__competitors-prompts-table-row <?php echo ! empty( $active_competitor ) ? 'active' : '' ?>" data-prompt-id="<?php echo $filtered['id'] ?>">
                                                <div class="seoaic-brand-visibility-page__competitors-prompts-table-col brand-visibility-col-6">
                                                    <span style="font-weight: 600;"><?php echo esc_html( $filtered['prompt'] ); ?></span>
                                                </div>
                                                <div class="seoaic-brand-visibility-page__competitors-prompts-table-col brand-visibility-col-3">
                                                    <span><?php echo esc_html( $filtered['sources_string'] ); ?></span>
                                                </div>
                                                <div class="seoaic-brand-visibility-page__competitors-prompts-table-col brand-competitors-wrapper brand-visibility-col-3">
                                                    <?php if ( $filtered['brands'] ): ?>
                                                        <?php foreach ( $filtered['brands'] as $brand ): ?>
                                                            <span class="seoaic-brand-visibility-page__competitors-prompts-table-brand"><?php echo esc_html( $brand ); ?></span>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>

                                                    <?php if ( $filtered['competitors'] ): ?>
                                                        <?php foreach ( $filtered['competitors'] as $competitor ): ?>
                                                            <span class="seoaic-brand-visibility-page__competitors-prompts-table-competitor"><?php echo esc_html( $competitor ); ?></span>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div class="seoaic-brand-visibility-page__competitors-prompts-table-row">
                                            <div class="seoaic-brand-visibility-page__competitors-prompts-table-col brand-visibility-col-12">
                                                <div class="seoaic-brand-visibility-page__competitors-prompts-table-competitor-info">
                                                    <h4><?php esc_html_e( 'No results found', 'seoaic' ); ?></h4>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="lds-dual-ring"></div>
    </div>

</div>
