<?php
declare(strict_types=1);

/** @var array{ok:?string,err:?string} $flash */
/** @var null|array{id:int,site_url:string,last_sync_at:?string} $activeProp */
/** @var null|array $data */
/** @var string $rangeStart */
/** @var string $rangeEnd */
/** @var ?array $globalFilters */

$pageTitle = __('cannibalization.page_title');
$pageHeading = __('cannibalization.heading');
$activeNav = 'cannibalization';
$hideHero = true;

$total = is_array($data) ? (int) ($data['total'] ?? 0) : 0;
$rows = is_array($data) ? ($data['rows'] ?? []) : [];
$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = max(10, min(100, (int) ($_GET['per_page'] ?? 10)));
$pages = $total > 0 ? (int) ceil($total / $perPage) : 1;
$sort = (string) ($_GET['sort'] ?? 'impressions');
$dir = (string) ($_GET['dir'] ?? 'DESC');
$minImpr = max(0, (int) ($_GET['min_impr'] ?? 500));
$minPages = max(2, (int) ($_GET['min_pages'] ?? 2));

$fmtInt = static fn (int $n): string => number_format($n, 0, '.', ',');
$fmtCtr = static fn (float $n): string => number_format($n * 100, 2) . '%';
$fmtPos = static fn (float $n): string => number_format($n, 2);
$fmtPct = static fn (float $n): string => number_format($n * 100, 0) . '%';

$baseSiteUrl = '';
if (is_array($activeProp) && !empty($activeProp['site_url'])) {
    $baseSiteUrl = rtrim((string) $activeProp['site_url'], '/');
}
$stripBaseUrl = static function (string $url) use ($baseSiteUrl): string {
    $u = trim($url);
    if ($u === '') {
        return '';
    }
    if ($baseSiteUrl !== '' && str_starts_with($u, $baseSiteUrl)) {
        $u = substr($u, strlen($baseSiteUrl));
        if ($u === '') {
            $u = '/';
        }
    }
    if ($u !== '' && $u[0] !== '/' && preg_match('#^https?://#i', $u) !== 1) {
        $u = '/' . $u;
    }
    return $u;
};

$buildUrl = static function (array $overrides): string {
    $base = [
        'prop' => (string) ($_GET['prop'] ?? ''),
        'range' => (string) ($_GET['range'] ?? 'last_28_days'),
        'per_page' => (string) ($_GET['per_page'] ?? '10'),
        'sort' => (string) ($_GET['sort'] ?? 'impressions'),
        'dir' => (string) ($_GET['dir'] ?? 'DESC'),
        'min_impr' => (string) ($_GET['min_impr'] ?? '500'),
        'min_pages' => (string) ($_GET['min_pages'] ?? '2'),
        'page' => (string) ($_GET['page'] ?? '1'),
    ];
    foreach ($overrides as $k => $v) {
        $base[$k] = (string) $v;
    }
    if (($base['prop'] ?? '') === '') unset($base['prop']);
    return seoscope_url('/cannibalization?' . http_build_query($base));
};

ob_start();
?>
<div class="dashboard-card section-card">
    <div class="section-title mb-1"><?= seoscope_h(__('cannibalization.title')) ?></div>
    <div class="section-subtitle mb-3">
        <?= seoscope_h(__('cannibalization.subtitle', ['start' => $rangeStart, 'end' => $rangeEnd])) ?>
    </div>

    <?php if (is_array($activeProp)): ?>
        <form method="get" class="row g-2 align-items-end mb-3">
            <input type="hidden" name="prop" value="<?= seoscope_h((string) ($_GET['prop'] ?? '')) ?>">
            <input type="hidden" name="range" value="<?= seoscope_h((string) ($_GET['range'] ?? 'last_28_days')) ?>">
            <input type="hidden" name="sort" value="<?= seoscope_h($sort) ?>">
            <input type="hidden" name="dir" value="<?= seoscope_h($dir) ?>">
            <input type="hidden" name="per_page" value="<?= seoscope_h((string) $perPage) ?>">

            <div class="col-12 col-md-3">
                <label class="form-label small mb-1"><?= seoscope_h(__('cannibalization.min_impressions')) ?></label>
                <input class="form-control form-control-sm" type="number" name="min_impr" min="0" value="<?= seoscope_h((string) $minImpr) ?>">
            </div>
            <div class="col-12 col-md-3">
                <label class="form-label small mb-1"><?= seoscope_h(__('cannibalization.min_urls')) ?></label>
                <input class="form-control form-control-sm" type="number" name="min_pages" min="2" value="<?= seoscope_h((string) $minPages) ?>">
            </div>

            <div class="col-auto">
                <button class="btn btn-sm btn-upgrade" type="submit"><?= seoscope_h(__('common.apply')) ?></button>
            </div>
            <div class="col-auto">
                <a class="btn btn-sm btn-outline-secondary" href="<?= seoscope_h($buildUrl(['min_impr' => '500', 'min_pages' => '2', 'page' => '1'])) ?>">
                    <?= seoscope_h(__('common.reset')) ?>
                </a>
            </div>
        </form>
    <?php endif; ?>

    <?php
    if (!isset($seoAiCanCard)) {
        $seoAiCanCard = null;
    }
    if (!isset($seoAiInsightsEnabled)) {
        $seoAiInsightsEnabled = false;
    }
    if (is_array($seoAiCanCard) && !empty($seoAiInsightsEnabled)):
        $ssAiQw = $seoAiCanCard;
        require __DIR__ . '/partials/seo_ai_quickwin_card.php';
    endif;
    ?>

    <?php if (!is_array($activeProp)): ?>
        <div class="text-muted"><?= seoscope_h(__('cannibalization.no_property')) ?></div>
    <?php elseif (empty($rows)): ?>
        <div class="text-muted"><?= seoscope_h(__('cannibalization.empty')) ?></div>
    <?php else: ?>
        <div class="table-wrap">
            <div class="table-responsive">
                <table class="crm-table">
                    <thead>
                        <tr>
                            <th style="width: 46px;"></th>
                            <?php
                                $cols = [
                                    'query' => __('cannibalization.col_query'),
                                    'pages_count' => __('cannibalization.col_pages'),
                                    'impressions' => __('cannibalization.col_impressions'),
                                    'clicks' => __('cannibalization.col_clicks'),
                                ];
                                foreach ($cols as $key => $label):
                                    $isActive = $sort === $key;
                                    $nextDir = ($isActive && strtoupper($dir) === 'DESC') ? 'ASC' : 'DESC';
                                    $arrow = $isActive ? (strtoupper($dir) === 'DESC' ? ' ↓' : ' ↑') : '';
                            ?>
                                <th>
                                    <a href="<?= seoscope_h($buildUrl(['sort' => $key, 'dir' => $nextDir, 'page' => '1'])) ?>" style="text-decoration:none;">
                                        <?= seoscope_h($label . $arrow) ?>
                                    </a>
                                </th>
                            <?php endforeach; ?>
                            <?php
                                $isActive = $sort === 'position';
                                $nextDir = ($isActive && strtoupper($dir) === 'DESC') ? 'ASC' : 'DESC';
                                $arrow = $isActive ? (strtoupper($dir) === 'DESC' ? ' ↓' : ' ↑') : '';
                            ?>
                            <th>
                                <a href="<?= seoscope_h($buildUrl(['sort' => 'position', 'dir' => $nextDir, 'page' => '1'])) ?>" style="text-decoration:none;">
                                    <?= seoscope_h(__('cannibalization.col_position') . $arrow) ?>
                                </a>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($rows as $r): ?>
                            <?php if (!is_array($r)) { continue; } ?>
                            <?php $top = (isset($r['top_pages']) && is_array($r['top_pages'])) ? $r['top_pages'] : []; ?>
                            <?php
                                $rowKey = substr(sha1((string) ($r['query'] ?? '') . '|' . (string) ($r['pages_count'] ?? '')), 0, 12);
                                $collapseId = 'ss-can-urls-' . $rowKey;
                                $hasUrls = !empty($top);
                            ?>
                            <tr>
                                <td>
                                    <span class="d-inline-block">
                                        <button
                                            type="button"
                                            class="btn btn-sm btn-light-secondary ss-kw-toggle"
                                            data-bs-toggle="collapse"
                                            data-bs-target="#<?= seoscope_h($collapseId) ?>"
                                            aria-expanded="false"
                                            aria-controls="<?= seoscope_h($collapseId) ?>"
                                            <?= $hasUrls ? '' : 'disabled' ?>
                                        >
                                            <i class="fa-solid fa-chevron-right"></i>
                                        </button>
                                    </span>
                                </td>
                                <td><?= seoscope_h((string) ($r['query'] ?? '')) ?></td>
                                <td><?= seoscope_h($fmtInt((int) ($r['pages_count'] ?? 0))) ?></td>
                                <td><?= seoscope_h($fmtInt((int) ($r['total_impressions'] ?? 0))) ?></td>
                                <td><?= seoscope_h($fmtInt((int) ($r['total_clicks'] ?? 0))) ?></td>
                                <td><?= seoscope_h($fmtPos((float) ($r['total_position'] ?? 0))) ?></td>
                            </tr>
                            <tr class="collapse" id="<?= seoscope_h($collapseId) ?>">
                                <td colspan="6" class="p-0">
                                    <div class="p-3" style="background: rgba(255,255,255,0.55);">
                                        <?php foreach ($top as $tp): ?>
                                            <?php if (!is_array($tp)) { continue; } ?>
                                            <?php
                                                $fullUrl = (string) ($tp['page'] ?? '');
                                                $dispUrl = $stripBaseUrl($fullUrl);
                                            ?>
                                            <div class="d-flex align-items-center justify-content-between gap-3 py-1">
                                                <a href="<?= seoscope_h($fullUrl) ?>" target="_blank" rel="noopener noreferrer">
                                                    <?= seoscope_h($dispUrl !== '' ? $dispUrl : $fullUrl) ?>
                                                </a>
                                                <span class="text-muted small"><?= seoscope_h($fmtPct((float) ($tp['share_impressions'] ?? 0))) ?></span>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php if ($pages > 1): ?>
            <div class="mt-3 d-flex align-items-center justify-content-between gap-3 flex-wrap">
                <?php
                    $prev = max(1, $page - 1);
                    $next = min($pages, $page + 1);
                ?>
                <nav aria-label="Pagination">
                    <ul class="pagination mb-0">
                        <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                            <a class="page-link" href="<?= seoscope_h($buildUrl(['page' => (string) $prev])) ?>">
                                <?= seoscope_h(__('pages.prev')) ?>
                            </a>
                        </li>
                        <li class="page-item disabled">
                            <span class="page-link"><?= seoscope_h(__('pages.page_x_of_y', ['x' => (string) $page, 'y' => (string) $pages])) ?></span>
                        </li>
                        <li class="page-item <?= $page >= $pages ? 'disabled' : '' ?>">
                            <a class="page-link" href="<?= seoscope_h($buildUrl(['page' => (string) $next])) ?>">
                                <?= seoscope_h(__('pages.next')) ?>
                            </a>
                        </li>
                    </ul>
                </nav>
                <form method="get" class="m-0 d-flex align-items-center gap-2">
                    <span class="text-muted small"><?= seoscope_h(__('pages.rows_per_page')) ?></span>
                    <select class="form-select form-select-sm" name="per_page" style="width:auto;" onchange="this.form.submit()">
                        <option value="10" <?= $perPage === 10 ? 'selected' : '' ?>>10</option>
                        <option value="25" <?= $perPage === 25 ? 'selected' : '' ?>>25</option>
                        <option value="50" <?= $perPage === 50 ? 'selected' : '' ?>>50</option>
                        <option value="100" <?= $perPage === 100 ? 'selected' : '' ?>>100</option>
                    </select>
                    <?php
                        // Preserve all current filters/sort but reset page to 1.
                        $keep = $_GET;
                        if (!is_array($keep)) $keep = [];
                        $keep['page'] = '1';
                        unset($keep['per_page']);
                        foreach ($keep as $k => $v) {
                            if (is_array($v)) continue;
                            if ($v === null) continue;
                            $sv = (string) $v;
                            if ($sv === '') continue;
                            echo '<input type="hidden" name="' . seoscope_h((string) $k) . '" value="' . seoscope_h($sv) . '">';
                        }
                    ?>
                </form>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>
<?php
$content = (string) ob_get_clean();
require __DIR__ . '/layout_admin.php';

