<?php
declare(strict_types=1);

/** @var array{ok:?string,err:?string} $flash */
/** @var list<array{id:int,name:string,site_url:string,notes:?string,gsc_property:?string}> $projects */
/** @var list<array{id:int,site_url:string,site_type:string,permission_level:string,fetched_at:string,is_enabled:int,enabled_at:?string,last_sync_date:?string,last_sync_at:?string,last_sync_error:?string}> $propertiesRows */
/** @var array<int,array<string,mixed>> $propertiesWithJobs */
/** @var array<int,bool> $propertiesHasActiveJob */
/** @var array<int,array{min:?string,max:?string}> $importedRanges */
/** @var array<int,array{completed_at:string,initial_start_date:?string,initial_end_date:?string}> $propertiesBackfillDone */
/** @var ?string $cronLastRunAt */
/** @var list<array<string,mixed>> $recentJobs */

$pageTitle = __('projects.page_title');
$pageHeading = __('projects.heading');
$activeNav = 'projects';
$hideHero = true;
$csrf = \SeoScope\Auth\AdminCsrf::token();
$postRedirect = (string) ($_SERVER['REQUEST_URI'] ?? '/projects');
ob_start();
?>
<div class="dashboard-card section-card">
    <div class="d-flex align-items-center justify-content-between flex-wrap gap-3 mb-1">
        <div class="section-title mb-0"><?= seoscope_h(__('projects.gsc_properties_title')) ?></div>
        <form method="post" action="<?= seoscope_h(seoscope_url('/settings/google/properties/fetch')) ?>" class="m-0">
            <input type="hidden" name="_csrf" value="<?= seoscope_h($csrf) ?>">
            <input type="hidden" name="redirect" value="<?= seoscope_h($postRedirect) ?>">
            <button type="submit" class="btn btn-upgrade">
                <?= seoscope_h(__('settings.google.props.fetch')) ?>
            </button>
        </form>
    </div>
    <div class="section-subtitle mb-3"><?= seoscope_h(__('projects.gsc_properties_subtitle')) ?></div>
    <?php
        $cronStale = false;
        if (is_string($cronLastRunAt) && $cronLastRunAt !== '' && preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $cronLastRunAt)) {
            $cronStale = (time() - strtotime($cronLastRunAt)) > (60 * 30);
        } else {
            $cronStale = true;
        }
    ?>
    <div class="small text-muted mb-2">
        <?= seoscope_h(__('projects.cron_last_run')) ?> <code><?= seoscope_h((string) ($cronLastRunAt ?? '—')) ?></code>
        <?php if ($cronStale): ?>
            <span class="badge bg-warning ms-2"><?= seoscope_h(__('projects.cron_stale')) ?></span>
        <?php else: ?>
            <span class="badge bg-success ms-2"><?= seoscope_h(__('projects.cron_ok')) ?></span>
        <?php endif; ?>
    </div>

    <?php if (empty($propertiesRows)): ?>
        <div class="text-muted">
            <?= seoscope_h(__('projects.gsc_properties_empty_prefix')) ?>
            <form method="post" action="<?= seoscope_h(seoscope_url('/settings/google/properties/fetch')) ?>" class="d-inline">
                <input type="hidden" name="_csrf" value="<?= seoscope_h($csrf) ?>">
                <input type="hidden" name="redirect" value="<?= seoscope_h($postRedirect) ?>">
                <button type="submit" class="btn btn-link p-0 align-baseline">
                    <?= seoscope_h(__('settings.google.props.fetch')) ?>
                </button>
            </form>
            <?= seoscope_h(__('projects.gsc_properties_empty_suffix')) ?>
        </div>
    <?php else: ?>
        <?php
            $verifyFilter = strtolower((string) ($_GET['verify'] ?? 'all'));
            if (!in_array($verifyFilter, ['all', 'verified', 'unverified'], true)) {
                $verifyFilter = 'all';
            }
            $buildVerifyUrl = static function (string $val) use ($postRedirect): string {
                $parts = parse_url($postRedirect);
                $path = is_array($parts) && !empty($parts['path']) ? (string) $parts['path'] : '/projects';
                $q = [];
                if (is_array($parts) && !empty($parts['query'])) {
                    parse_str((string) $parts['query'], $q);
                }
                if ($val === 'all') {
                    unset($q['verify']);
                } else {
                    $q['verify'] = $val;
                }
                return seoscope_url($path . ($q !== [] ? ('?' . http_build_query($q)) : ''));
            };
        ?>
        <div class="d-flex align-items-center gap-2 flex-wrap mb-2 small">
            <span class="text-muted"><?= seoscope_h(__('projects.gsc_filter_label')) ?></span>
            <a class="<?= $verifyFilter === 'all' ? 'fw-semibold text-decoration-none' : 'text-decoration-none' ?>" href="<?= seoscope_h($buildVerifyUrl('all')) ?>">
                <?= seoscope_h(__('projects.gsc_filter_all')) ?>
            </a>
            <span class="text-muted" aria-hidden="true">|</span>
            <a class="<?= $verifyFilter === 'verified' ? 'fw-semibold text-decoration-none' : 'text-decoration-none' ?>" href="<?= seoscope_h($buildVerifyUrl('verified')) ?>">
                <?= seoscope_h(__('projects.gsc_filter_verified')) ?>
            </a>
            <span class="text-muted" aria-hidden="true">|</span>
            <a class="<?= $verifyFilter === 'unverified' ? 'fw-semibold text-decoration-none' : 'text-decoration-none' ?>" href="<?= seoscope_h($buildVerifyUrl('unverified')) ?>">
                <?= seoscope_h(__('projects.gsc_filter_unverified')) ?>
            </a>
        </div>
        <div class="table-wrap">
            <div class="table-responsive">
                <table class="crm-table">
                    <thead>
                        <tr>
                            <th><?= seoscope_h(__('projects.gsc_prop_col_site')) ?></th>
                            <th><?= seoscope_h(__('projects.gsc_prop_col_enabled')) ?></th>
                            <th><?= seoscope_h(__('projects.gsc_prop_col_fullsync')) ?></th>
                            <th><?= seoscope_h(__('projects.gsc_prop_col_imported_range')) ?></th>
                            <th><?= seoscope_h(__('projects.gsc_prop_col_last_synced')) ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($propertiesRows as $row): ?>
                            <?php
                                $pid = (int) ($row['id'] ?? 0);
                                $site = (string) ($row['site_url'] ?? '');
                                $enabled = !empty($row['is_enabled']);
                                $perm = strtolower((string) ($row['permission_level'] ?? ''));
                                $isUnverified = ($perm === 'siteunverifieduser');
                                if ($verifyFilter === 'verified' && $isUnverified) {
                                    continue;
                                }
                                if ($verifyFilter === 'unverified' && !$isUnverified) {
                                    continue;
                                }
                                $enableBlocked = (!$enabled && $perm === 'siteunverifieduser');
                                $lastSyncedAt = is_string($row['last_sync_at'] ?? null) ? (string) $row['last_sync_at'] : null;
                                $lastSyncDate = is_string($row['last_sync_date'] ?? null) ? (string) $row['last_sync_date'] : null;
                                $lastSyncError = is_string($row['last_sync_error'] ?? null) ? (string) $row['last_sync_error'] : null;
                                $job = $pid > 0 ? ($propertiesWithJobs[$pid] ?? null) : null;
                                $hasActiveAnyJob = $pid > 0 && !empty($propertiesHasActiveJob[$pid]);
                            ?>
                            <tr>
                                <td><code><?= seoscope_h($site) ?></code></td>
                                <td style="white-space: nowrap;">
                                    <form method="post" action="<?= seoscope_h(seoscope_url('/settings/google/properties/toggle')) ?>" class="d-inline">
                                        <input type="hidden" name="_csrf" value="<?= seoscope_h($csrf) ?>">
                                        <input type="hidden" name="redirect" value="<?= seoscope_h($postRedirect) ?>">
                                        <input type="hidden" name="site_url" value="<?= seoscope_h($site) ?>">
                                        <input type="hidden" name="enabled" value="<?= $enabled ? '0' : '1' ?>">
                                        <?php if ($enableBlocked): ?>
                                            <span
                                                class="d-inline-block"
                                                tabindex="0"
                                                data-bs-toggle="tooltip"
                                                data-bs-placement="top"
                                                title="<?= seoscope_h(__('projects.gsc_enable_blocked_hint')) ?>"
                                            >
                                                <button type="submit" class="btn btn-sm btn-secondary" disabled>
                                                    <?= seoscope_h(__('projects.gsc_enable')) ?>
                                                </button>
                                            </span>
                                        <?php else: ?>
                                            <?php if (!$enabled): ?>
                                                <span
                                                    class="d-inline-block"
                                                    tabindex="0"
                                                    data-bs-toggle="tooltip"
                                                    data-bs-placement="top"
                                                    title="<?= seoscope_h(__('projects.gsc_enable_hint')) ?>"
                                                >
                                                    <button type="submit" class="btn btn-sm btn-success">
                                                        <?= seoscope_h(__('projects.gsc_enable')) ?>
                                                    </button>
                                                </span>
                                            <?php else: ?>
                                                <button type="submit" class="btn btn-sm btn-outline-danger">
                                                    <?= seoscope_h(__('projects.gsc_disable')) ?>
                                                </button>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </form>
                                </td>
                                <td style="white-space: nowrap;">
                                    <?php if ($perm === 'siteunverifieduser'): ?>
                                        <span class="text-muted small"><?= seoscope_h(__('projects.full_sync_blocked')) ?></span>
                                    <?php else: ?>
                                        <?php
                                            $isFullBackfillJob = is_array($job) && strtolower((string) ($job['job_type'] ?? '')) === 'full_backfill';
                                            $isBootstrapJob = is_array($job) && strtolower((string) ($job['job_type'] ?? '')) === 'bootstrap_28';
                                            // "COMPLETED" should reflect the current enabled state and should not overlap with any active job badges.
                                            $hasCompletedBackfill = $enabled && $pid > 0 && isset($propertiesBackfillDone[$pid]) && !$hasActiveAnyJob;
                                        ?>
                                        <?php if ($hasCompletedBackfill): ?>
                                            <div class="d-flex align-items-center justify-content-between gap-2">
                                                <span
                                                    class="badge bg-success"
                                                    data-bs-toggle="tooltip"
                                                    data-bs-placement="top"
                                                    title="<?= seoscope_h(__('projects.full_sync_completed_hint')) ?>"
                                                >
                                                    <?= seoscope_h(__('projects.full_sync_completed_badge')) ?>
                                                </span>
                                                <div class="dropdown">
                                                    <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                        ⋯
                                                    </button>
                                                    <ul class="dropdown-menu dropdown-menu-end">
                                                        <li>
                                                            <form method="post" action="<?= seoscope_h(seoscope_url('/projects/full-sync')) ?>" class="m-0">
                                                                <input type="hidden" name="_csrf" value="<?= seoscope_h($csrf) ?>">
                                                                <input type="hidden" name="property_id" value="<?= (int) $pid ?>">
                                                                <input type="hidden" name="refresh" value="1">
                                                                <button type="submit" class="dropdown-item">
                                                                    <?= seoscope_h(__('projects.full_sync_rerun_refresh')) ?>
                                                                </button>
                                                            </form>
                                                        </li>
                                                        <li>
                                                            <form method="post" action="<?= seoscope_h(seoscope_url('/projects/full-sync')) ?>" class="m-0">
                                                                <input type="hidden" name="_csrf" value="<?= seoscope_h($csrf) ?>">
                                                                <input type="hidden" name="property_id" value="<?= (int) $pid ?>">
                                                                <input type="hidden" name="missing_only" value="1">
                                                                <button type="submit" class="dropdown-item">
                                                                    <?= seoscope_h(__('projects.full_sync_missing_only')) ?>
                                                                </button>
                                                            </form>
                                                        </li>
                                                    </ul>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                        <?php if (is_array($job)): ?>
                                            <?php
                                                $st = strtolower((string) ($job['status'] ?? ''));
                                                $isActiveJob = in_array($st, ['running', 'pending', 'retry', 'paused'], true);
                                                $jobType = (string) ($job['job_type'] ?? '');
                                                $initialStart = is_string($job['initial_start_date'] ?? null) ? (string) $job['initial_start_date'] : null;
                                                $initialEnd = is_string($job['initial_end_date'] ?? null) ? (string) $job['initial_end_date'] : null;
                                                $curStart = (string) ($job['start_date'] ?? '');
                                                $curEnd = (string) ($job['end_date'] ?? '');
                                                $pct = null;
                                                // Progress = share of the [initialStart..initialEnd] range already past the cursor
                                                // (using "days remaining" avoids misleading 100% on the last chunk while still running).
                                                $reverseBackfill = strtolower((string) ($job['job_type'] ?? '')) === 'full_backfill';
                                                $cursorForPct = $reverseBackfill ? $curEnd : $curStart;
                                                if ($initialStart && $initialEnd && preg_match('/^\d{4}-\d{2}-\d{2}$/', $initialStart) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $initialEnd) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $cursorForPct)) {
                                                    $iS = strtotime($initialStart . ' 12:00:00');
                                                    $iE = strtotime($initialEnd . ' 12:00:00');
                                                    $cS = strtotime($cursorForPct . ' 12:00:00');
                                                    if ($iS !== false && $iE !== false && $cS !== false && $iE >= $iS) {
                                                        $totalDays = (int) max(1, (($iE - $iS) / 86400) + 1);
                                                        if ($reverseBackfill) {
                                                            // Cursor is the current end date; remaining window is [initialStart..cursorEnd].
                                                            $remaining = (int) (($cS - $iS) / 86400) + 1;
                                                            $remaining = max(0, min($totalDays, $remaining));
                                                            $completed = $totalDays - $remaining;
                                                            $pct = (int) max(0, min(100, round(($completed / $totalDays) * 100)));
                                                        } elseif ($cS > $iE) {
                                                            $pct = 100;
                                                        } else {
                                                            $remaining = (int) (($iE - $cS) / 86400) + 1;
                                                            $remaining = max(0, min($totalDays, $remaining));
                                                            $completed = $totalDays - $remaining;
                                                            $pct = (int) max(0, min(100, round(($completed / $totalDays) * 100)));
                                                        }
                                                        if (in_array($st, ['running', 'pending', 'retry', 'paused'], true) && $pct >= 100) {
                                                            $pct = 99;
                                                        }
                                                    }
                                                }
                                                $badge = match ($st) {
                                                    'running' => 'bg-primary',
                                                    'retry' => 'bg-warning',
                                                    'failed' => 'bg-danger',
                                                    'done' => 'bg-success',
                                                    default => 'bg-secondary',
                                                };
                                                $jobTag = match (strtolower($jobType)) {
                                                    'bootstrap_28' => 'FAST 28d',
                                                    'full_backfill' => 'BACKFILL (up to 16m)',
                                                    default => strtoupper($jobType),
                                                };
                                                $title = '';
                                                if (!empty($job['last_error'])) {
                                                    $title = (string) $job['last_error'];
                                                } elseif (!empty($job['next_run_at'])) {
                                                    $title = __('projects.queue_next') . ' ' . (string) $job['next_run_at'];
                                                } elseif ($pct !== null) {
                                                    $title = __('projects.progress_label') . ' ' . (string) $pct . '%';
                                                }
                                            ?>
                                            <?php
                                                $statusText = strtoupper($st) !== '' ? strtoupper($st) : strtoupper((string) __('projects.status_pending'));
                                                $badgeText = $jobTag . ($pct !== null ? (' · ' . (string) $pct . '%') : '');
                                            ?>
                                            <?php if ($isFullBackfillJob): ?>
                                                <div class="d-flex align-items-start justify-content-between gap-2">
                                                    <div>
                                                        <span
                                                            class="badge <?= seoscope_h($badge) ?>"
                                                            <?= $title !== '' ? 'data-bs-toggle="tooltip" data-bs-placement="top" title="' . seoscope_h($statusText . ' — ' . $title) . '"' : 'data-bs-toggle="tooltip" data-bs-placement="top" title="' . seoscope_h($statusText) . '"' ?>
                                                        >
                                                            <?= seoscope_h($badgeText) ?>
                                                        </span>
                                                        <?php if ($pct !== null): ?>
                                                            <div class="progress mt-1" style="height: 6px; width: 140px;">
                                                                <div class="progress-bar" role="progressbar" style="width: <?= (int) $pct ?>%;" aria-valuenow="<?= (int) $pct ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>

                                                    <?php if ($isActiveJob): ?>
                                                        <div class="dropdown">
                                                            <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                                ⋯
                                                            </button>
                                                            <ul class="dropdown-menu dropdown-menu-end">
                                                                <li>
                                                                    <form method="post" action="<?= seoscope_h(seoscope_url('/projects/queue-action')) ?>" class="m-0">
                                                                        <input type="hidden" name="_csrf" value="<?= seoscope_h($csrf) ?>">
                                                                        <input type="hidden" name="property_id" value="<?= (int) $pid ?>">
                                                                        <input type="hidden" name="action" value="<?= $st === 'paused' ? 'resume' : 'pause' ?>">
                                                                        <button type="submit" class="dropdown-item">
                                                                            <?= seoscope_h($st === 'paused' ? __('projects.queue_resume') : __('projects.queue_pause')) ?>
                                                                        </button>
                                                                    </form>
                                                                </li>
                                                                <li><hr class="dropdown-divider"></li>
                                                                <li>
                                                                    <form method="post" action="<?= seoscope_h(seoscope_url('/projects/queue-action')) ?>" class="m-0" onsubmit="return confirm('<?= seoscope_h(__('projects.queue_cancel_confirm')) ?>');">
                                                                        <input type="hidden" name="_csrf" value="<?= seoscope_h($csrf) ?>">
                                                                        <input type="hidden" name="property_id" value="<?= (int) $pid ?>">
                                                                        <input type="hidden" name="action" value="cancel">
                                                                        <button type="submit" class="dropdown-item text-danger">
                                                                            <?= seoscope_h(__('projects.queue_cancel')) ?>
                                                                        </button>
                                                                    </form>
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            <?php else: ?>
                                                <div class="mt-1">
                                                    <span
                                                        class="badge <?= seoscope_h($badge) ?>"
                                                        <?= $title !== '' ? 'data-bs-toggle="tooltip" data-bs-placement="top" title="' . seoscope_h($statusText . ' — ' . $title) . '"' : 'data-bs-toggle="tooltip" data-bs-placement="top" title="' . seoscope_h($statusText) . '"' ?>
                                                    >
                                                        <?= seoscope_h($badgeText) ?>
                                                    </span>
                                                </div>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                        <?php if (!$isFullBackfillJob && !$hasCompletedBackfill && !$hasActiveAnyJob): ?>
                                            <form method="post" action="<?= seoscope_h(seoscope_url('/projects/full-sync')) ?>" class="d-inline mt-2">
                                                <input type="hidden" name="_csrf" value="<?= seoscope_h($csrf) ?>">
                                                <input type="hidden" name="property_id" value="<?= (int) $pid ?>">
                                                <?php if (!$enabled): ?>
                                                    <span
                                                        class="d-inline-block"
                                                        tabindex="0"
                                                        data-bs-toggle="tooltip"
                                                        data-bs-placement="top"
                                                        title="<?= seoscope_h(__('projects.full_sync_requires_enable_hint')) ?>"
                                                    >
                                                        <button type="submit" class="btn btn-sm btn-export-csv" disabled>
                                                            <?= seoscope_h(__('projects.full_sync')) ?>
                                                        </button>
                                                    </span>
                                                <?php else: ?>
                                                    <button type="submit" class="btn btn-sm btn-export-csv">
                                                        <?= seoscope_h(__('projects.full_sync')) ?>
                                                    </button>
                                                <?php endif; ?>
                                            </form>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </td>
                                <td class="small">
                                    <?php
                                        $rng = $pid > 0 ? ($importedRanges[$pid] ?? null) : null;
                                        $min = is_array($rng) ? (string) ($rng['min'] ?? '') : '';
                                        $max = is_array($rng) ? (string) ($rng['max'] ?? '') : '';
                                    ?>
                                    <?php if ($min !== '' && $max !== ''): ?>
                                        <code><?= seoscope_h($min) ?></code> → <code><?= seoscope_h($max) ?></code>
                                    <?php else: ?>
                                        <span class="text-muted small">—</span>
                                    <?php endif; ?>
                                </td>
                                <td class="small">
                                    <?php if (!empty($lastSyncError)): ?>
                                        <span class="badge bg-danger" data-bs-toggle="tooltip" data-bs-placement="top" title="<?= seoscope_h($lastSyncError) ?>">
                                            <?= seoscope_h(__('projects.last_synced_error')) ?>
                                        </span>
                                        <?php if (!empty($lastSyncedAt)): ?>
                                            <div class="text-success small mt-1"><?= seoscope_h($lastSyncedAt) ?></div>
                                        <?php endif; ?>
                                        <?php if (!empty($lastSyncDate)): ?>
                                            <div class="text-muted small mt-1"><?= seoscope_h(__('projects.last_sync_date_label', ['date' => $lastSyncDate])) ?></div>
                                        <?php endif; ?>
                                    <?php elseif (!empty($lastSyncedAt)): ?>
                                        <div class="text-success small"><?= seoscope_h($lastSyncedAt) ?></div>
                                        <?php if (!empty($lastSyncDate)): ?>
                                            <div class="text-muted small mt-1"><?= seoscope_h(__('projects.last_sync_date_label', ['date' => $lastSyncDate])) ?></div>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span class="text-muted small"><?= seoscope_h(__('projects.last_synced_never')) ?></span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>

</div>
<?php
$content = ob_get_clean();
require __DIR__ . '/layout_admin.php';
