<?php
/**
 * ============================================
 * FLOWBOT DCI v3.0 - DOMAIN STATISTICS
 * ============================================
 * Domain statistics and analysis page
 */
declare(strict_types=1);

$baseUrl = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
$pageTitle = 'Domain Statistics';
$currentPage = 'domains';

// Calculate totals
$totalDomains = count($domainStats ?? []);
$totalUrls = $data['total_links'] ?? 0;
$totalSuccess = 0;
$totalErrors = 0;
$totalIgnored = 0;
$bestDomain = null;
$worstDomain = null;
$bestRate = 0;
$worstRate = 100;

foreach ($domainStats as $domain => $stats) {
    $totalSuccess += $stats['success'] ?? 0;
    $totalErrors += $stats['error'] ?? 0;
    $totalIgnored += $stats['ignored'] ?? 0;

    $domainTotal = $stats['total'] ?? 1;
    $successRate = round((($stats['success'] ?? 0) / $domainTotal) * 100, 1);

    if ($successRate > $bestRate && $domainTotal >= 3) {
        $bestRate = $successRate;
        $bestDomain = $domain;
    }
    if ($successRate < $worstRate && $domainTotal >= 3) {
        $worstRate = $successRate;
        $worstDomain = $domain;
    }
}

// Top 10 domains by total
$topDomains = array_slice($domainStats, 0, 10, true);
$maxDomainTotal = max(array_column($domainStats, 'total') ?: [1]);

// Slowest domains
$slowestDomains = $domainStats;
uasort($slowestDomains, fn($a, $b) => ($b['avg_response_time'] ?? 0) <=> ($a['avg_response_time'] ?? 0));
$slowestDomains = array_slice($slowestDomains, 0, 5, true);

// HTTP codes helper
$getCodeClass = function($code) {
    return match(true) {
        (int)$code >= 200 && (int)$code < 300 => 'success',
        (int)$code >= 300 && (int)$code < 400 => 'info',
        (int)$code >= 400 && (int)$code < 500 => 'warning',
        (int)$code >= 500 => 'error',
        default => 'info',
    };
};

// Error distribution
$errorDistribution = [];
foreach ($domainStats as $stats) {
    foreach ($stats['error_types'] ?? [] as $type => $count) {
        $errorDistribution[$type] = ($errorDistribution[$type] ?? 0) + $count;
    }
}
arsort($errorDistribution);
$totalErrorCount = array_sum($errorDistribution) ?: 1;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($pageTitle) ?> - Flowb0t DCI v3.0</title>
    <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><rect width='32' height='32' rx='8' fill='%233B82F6'/><path d='M8 10h16M8 16h12M8 22h8' stroke='white' stroke-width='2.5' stroke-linecap='round'/></svg>">
    <link rel="stylesheet" href="<?= $baseUrl ?>/assets/css/v3-styles.css?v=<?= time() ?>">
</head>
<body>
    <!-- Navigation -->
    <nav class="main-nav">
        <div class="nav-container">
            <div class="nav-brand">
                <a href="<?= $baseUrl ?>/" class="brand-link">
                    <span class="brand-logo">
                        <svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <rect width="32" height="32" rx="8" fill="url(#brand-gradient)"/>
                            <path d="M8 10h16M8 16h12M8 22h8" stroke="white" stroke-width="2.5" stroke-linecap="round"/>
                            <circle cx="24" cy="22" r="4" fill="#10B981"/>
                            <defs>
                                <linearGradient id="brand-gradient" x1="0" y1="0" x2="32" y2="32">
                                    <stop stop-color="#3B82F6"/>
                                    <stop offset="1" stop-color="#8B5CF6"/>
                                </linearGradient>
                            </defs>
                        </svg>
                    </span>
                    <span class="brand-text">Flowb0t DCI</span>
                    <span class="brand-version">v3.0</span>
                </a>
            </div>

            <div class="nav-main">
                <a href="<?= $baseUrl ?>/" class="nav-link">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <rect x="3" y="3" width="7" height="7" rx="1"/>
                        <rect x="14" y="3" width="7" height="7" rx="1"/>
                        <rect x="3" y="14" width="7" height="7" rx="1"/>
                        <rect x="14" y="14" width="7" height="7" rx="1"/>
                    </svg>
                    <span>Dashboard</span>
                </a>
                <a href="<?= $baseUrl ?>/new" class="nav-link">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="9"/>
                        <line x1="12" y1="8" x2="12" y2="16"/>
                        <line x1="8" y1="12" x2="16" y2="12"/>
                    </svg>
                    <span>New Process</span>
                </a>
                <a href="<?= $baseUrl ?>/history" class="nav-link">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="9"/>
                        <polyline points="12,7 12,12 16,14"/>
                    </svg>
                    <span>History</span>
                </a>
            </div>

            <div class="nav-right">
                <a href="<?= $baseUrl ?>/process/<?= htmlspecialchars($processId) ?>" class="btn btn-ghost btn-sm">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                        <polyline points="15 18 9 12 15 6"/>
                    </svg>
                    Back to Process
                </a>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <main class="main-content">
        <!-- Page Header -->
        <div class="page-header">
            <h1 class="page-title">Domain Statistics</h1>
            <p class="page-subtitle">Detailed breakdown for process #<?= htmlspecialchars(substr($processId, 0, 8)) ?></p>
        </div>

        <!-- Stats Grid -->
        <div class="stats-grid">
            <div class="stat-card stat-card-active">
                <div class="stat-icon">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="10"/>
                        <circle cx="12" cy="12" r="3"/>
                    </svg>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?= number_format($totalDomains) ?></span>
                    <span class="stat-label">Total Domains</span>
                </div>
            </div>

            <div class="stat-card stat-card-success">
                <div class="stat-icon">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
                        <polyline points="22 4 12 14.01 9 11.01"/>
                    </svg>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?= number_format($totalSuccess) ?></span>
                    <span class="stat-label">Success</span>
                </div>
            </div>

            <div class="stat-card stat-card-warning">
                <div class="stat-icon">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
                        <line x1="12" y1="9" x2="12" y2="13"/>
                        <line x1="12" y1="17" x2="12.01" y2="17"/>
                    </svg>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?= number_format($totalIgnored) ?></span>
                    <span class="stat-label">Ignored</span>
                </div>
            </div>

            <div class="stat-card stat-card-error">
                <div class="stat-icon">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="10"/>
                        <line x1="15" y1="9" x2="9" y2="15"/>
                        <line x1="9" y1="9" x2="15" y2="15"/>
                    </svg>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?= number_format($totalErrors) ?></span>
                    <span class="stat-label">Errors</span>
                </div>
            </div>
        </div>

        <!-- Dashboard Grid -->
        <div class="dashboard-grid">
            <!-- Main Column -->
            <div class="dashboard-main">
                <!-- Best/Worst Performers -->
                <?php if ($bestDomain || $worstDomain): ?>
                <div class="grid-2col mb-lg">
                    <?php if ($bestDomain): ?>
                    <div class="card card-success">
                        <div class="card-body">
                            <div class="flex items-center gap-sm mb-sm">
                                <span class="text-2xl">🏆</span>
                                <h3 class="card-title">Best Performer</h3>
                            </div>
                            <p class="text-lg font-medium"><?= htmlspecialchars($bestDomain) ?></p>
                            <p class="text-success text-sm"><?= $bestRate ?>% success rate</p>
                        </div>
                    </div>
                    <?php endif; ?>
                    <?php if ($worstDomain): ?>
                    <div class="card card-error">
                        <div class="card-body">
                            <div class="flex items-center gap-sm mb-sm">
                                <span class="text-2xl">🚨</span>
                                <h3 class="card-title">Most Problematic</h3>
                            </div>
                            <p class="text-lg font-medium"><?= htmlspecialchars($worstDomain) ?></p>
                            <p class="text-error text-sm"><?= $worstRate ?>% success rate</p>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>

                <!-- Top 10 Domains Chart -->
                <div class="section">
                    <div class="section-header">
                        <h2 class="section-title">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <line x1="18" y1="20" x2="18" y2="10"/>
                                <line x1="12" y1="20" x2="12" y2="4"/>
                                <line x1="6" y1="20" x2="6" y2="14"/>
                            </svg>
                            Top 10 Domains by Volume
                        </h2>
                    </div>
                    <div class="section-body">
                        <div class="bar-chart">
                            <?php foreach ($topDomains as $domain => $stats):
                                $total = $stats['total'] ?? 0;
                                $success = $stats['success'] ?? 0;
                                $error = $stats['error'] ?? 0;
                                $ignored = $stats['ignored'] ?? 0;
                                $width = ($total / $maxDomainTotal) * 100;
                                $successWidth = ($success / max($total, 1)) * 100;
                                $errorWidth = ($error / max($total, 1)) * 100;
                                $ignoredWidth = ($ignored / max($total, 1)) * 100;
                            ?>
                            <div class="bar-row">
                                <div class="bar-label" title="<?= htmlspecialchars($domain) ?>">
                                    <?= htmlspecialchars(substr($domain, 0, 25)) ?><?= strlen($domain) > 25 ? '...' : '' ?>
                                </div>
                                <div class="bar-container">
                                    <div class="bar-fill-stacked" style="width: <?= $width ?>%">
                                        <div class="bar-segment bar-success" style="width: <?= $successWidth ?>%" title="Success: <?= $success ?>"></div>
                                        <div class="bar-segment bar-warning" style="width: <?= $ignoredWidth ?>%" title="Ignored: <?= $ignored ?>"></div>
                                        <div class="bar-segment bar-error" style="width: <?= $errorWidth ?>%" title="Error: <?= $error ?>"></div>
                                    </div>
                                </div>
                                <div class="bar-value"><?= number_format($total) ?></div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <!-- Domain Table -->
                <div class="section">
                    <div class="section-header">
                        <h2 class="section-title">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <circle cx="12" cy="12" r="10"/>
                                <circle cx="12" cy="12" r="3"/>
                            </svg>
                            All Domains
                            <span class="badge badge-info ml-sm"><?= number_format($totalDomains) ?></span>
                        </h2>
                        <div class="section-actions">
                            <input type="text" id="domainSearch" class="input input-sm" placeholder="Search domains..." style="width: 200px;">
                            <div class="btn-group ml-sm">
                                <a href="?process_id=<?= urlencode($processId) ?>&page=api&action=export&type=domains&format=csv" class="btn btn-ghost btn-sm">CSV</a>
                                <a href="?process_id=<?= urlencode($processId) ?>&page=api&action=export&type=domains&format=json" class="btn btn-ghost btn-sm">JSON</a>
                            </div>
                        </div>
                    </div>
                    <div class="table-container">
                        <table id="domainTable">
                            <thead>
                                <tr>
                                    <th class="sortable" data-sort="domain">Domain</th>
                                    <th class="sortable text-center" data-sort="total">Total</th>
                                    <th class="sortable text-center" data-sort="success">Success</th>
                                    <th class="sortable text-center" data-sort="error">Errors</th>
                                    <th class="sortable text-center" data-sort="ignored">Ignored</th>
                                    <th class="sortable text-center" data-sort="rate">Rate</th>
                                    <th class="sortable text-center" data-sort="avg_time">Avg Time</th>
                                    <th class="text-center">HTTP Codes</th>
                                    <th class="text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($domainStats as $domain => $stats):
                                    $total = $stats['total'] ?? 0;
                                    $success = $stats['success'] ?? 0;
                                    $error = $stats['error'] ?? 0;
                                    $ignored = $stats['ignored'] ?? 0;
                                    $avgTime = $stats['avg_response_time'] ?? 0;
                                    $minTime = ($stats['min_response_time'] ?? PHP_FLOAT_MAX) < PHP_FLOAT_MAX ? $stats['min_response_time'] : 0;
                                    $maxTime = $stats['max_response_time'] ?? 0;
                                    $httpCodes = $stats['http_codes'] ?? [];
                                    arsort($httpCodes);
                                    $rate = round(($success / max($total, 1)) * 100, 1);

                                    $rateClass = 'success';
                                    if ($rate < 80) $rateClass = 'info';
                                    if ($rate < 50) $rateClass = 'warning';
                                    if ($rate < 25) $rateClass = 'error';
                                ?>
                                <tr class="domain-row"
                                    data-domain="<?= htmlspecialchars($domain) ?>"
                                    data-total="<?= $total ?>"
                                    data-success="<?= $success ?>"
                                    data-error="<?= $error ?>"
                                    data-ignored="<?= $ignored ?>"
                                    data-rate="<?= $rate ?>"
                                    data-avg_time="<?= $avgTime ?>">
                                    <td class="domain-name">
                                        <span class="domain-text"><?= htmlspecialchars($domain) ?></span>
                                    </td>
                                    <td class="text-center"><?= number_format($total) ?></td>
                                    <td class="text-center text-success"><?= number_format($success) ?></td>
                                    <td class="text-center text-error"><?= number_format($error) ?></td>
                                    <td class="text-center text-warning"><?= number_format($ignored) ?></td>
                                    <td class="text-center">
                                        <span class="badge badge-<?= $rateClass ?>"><?= $rate ?>%</span>
                                    </td>
                                    <td class="text-center" title="Min: <?= number_format($minTime, 2) ?>s | Max: <?= number_format($maxTime, 2) ?>s">
                                        <?= number_format($avgTime, 2) ?>s
                                    </td>
                                    <td class="text-center">
                                        <?php foreach (array_slice($httpCodes, 0, 3, true) as $code => $count):
                                            $codeClass = $getCodeClass($code);
                                        ?>
                                        <span class="badge badge-<?= $codeClass ?> badge-sm" title="HTTP <?= $code ?>: <?= $count ?> requests"><?= $code ?></span>
                                        <?php endforeach; ?>
                                        <?php if (empty($httpCodes)): ?>
                                        <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <a href="?process_id=<?= urlencode($processId) ?>&page=logs&domain=<?= urlencode($domain) ?>"
                                           class="btn btn-ghost btn-sm" title="View logs">
                                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                                                <circle cx="11" cy="11" r="8"/>
                                                <path d="m21 21-4.35-4.35"/>
                                            </svg>
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="dashboard-sidebar">
                <!-- Slowest Domains -->
                <?php if (!empty($slowestDomains)): ?>
                <div class="section">
                    <div class="section-header">
                        <h2 class="section-title">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <circle cx="12" cy="12" r="10"/>
                                <polyline points="12,6 12,12 16,14"/>
                            </svg>
                            Slowest Domains
                        </h2>
                    </div>
                    <div class="section-body">
                        <ul class="activity-list">
                            <?php foreach ($slowestDomains as $domain => $stats):
                                $avgTime = $stats['avg_response_time'] ?? 0;
                                if ($avgTime <= 0) continue;
                                $timeClass = $avgTime > 5 ? 'error' : ($avgTime > 3 ? 'warning' : 'info');
                            ?>
                            <li class="activity-item">
                                <div class="activity-icon <?= $timeClass ?>">
                                    <?= $avgTime > 5 ? '⚠' : '⏱' ?>
                                </div>
                                <div class="activity-content">
                                    <p class="activity-text" title="<?= htmlspecialchars($domain) ?>">
                                        <?= htmlspecialchars(strlen($domain) > 20 ? substr($domain, 0, 20) . '...' : $domain) ?>
                                    </p>
                                    <span class="activity-time text-<?= $timeClass ?>"><?= number_format($avgTime, 2) ?>s</span>
                                </div>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Error Distribution -->
                <?php if (!empty($errorDistribution)): ?>
                <div class="section">
                    <div class="section-header">
                        <h2 class="section-title">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
                                <line x1="12" y1="9" x2="12" y2="13"/>
                                <line x1="12" y1="17" x2="12.01" y2="17"/>
                            </svg>
                            Error Distribution
                        </h2>
                    </div>
                    <div class="section-body">
                        <div class="perf-stats">
                            <?php foreach (array_slice($errorDistribution, 0, 6, true) as $type => $count):
                                $percent = round(($count / $totalErrorCount) * 100, 1);
                                $label = match($type) {
                                    'timeout' => 'Timeout',
                                    'http_429' => 'Rate Limit (429)',
                                    'http_404' => 'Not Found (404)',
                                    'http_403' => 'Forbidden (403)',
                                    'http_5xx' => 'Server Error (5xx)',
                                    'connection' => 'Connection Error',
                                    'metadata' => 'Metadata Error',
                                    default => ucfirst($type),
                                };
                            ?>
                            <div class="perf-stat">
                                <span class="perf-label"><?= $label ?></span>
                                <span class="perf-value"><?= number_format($count) ?></span>
                            </div>
                            <div class="perf-bar">
                                <div class="perf-bar-fill perf-bar-error" style="width: <?= $percent ?>%"></div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </main>

    <!-- Toast Container -->
    <div id="toastContainer" class="toast-container"></div>

    <script src="<?= $baseUrl ?>/assets/js/app.js?v=<?= time() ?>"></script>
    <script>
        window.processId = '<?= htmlspecialchars($processId) ?>';

        document.addEventListener('DOMContentLoaded', function() {
            // Initialize domain table search
            const searchInput = document.getElementById('domainSearch');
            const table = document.getElementById('domainTable');

            if (searchInput && table) {
                searchInput.addEventListener('input', function() {
                    const filter = this.value.toLowerCase();
                    const rows = table.querySelectorAll('tbody tr');

                    rows.forEach(row => {
                        const domain = row.getAttribute('data-domain')?.toLowerCase() || '';
                        row.style.display = domain.includes(filter) ? '' : 'none';
                    });
                });
            }

            // Initialize sorting
            const headers = document.querySelectorAll('.sortable');
            headers.forEach(header => {
                header.addEventListener('click', function() {
                    const sortBy = this.getAttribute('data-sort');
                    const tbody = table.querySelector('tbody');
                    const rows = Array.from(tbody.querySelectorAll('tr'));
                    const isAsc = this.classList.contains('sort-asc');

                    // Remove sort classes from all headers
                    headers.forEach(h => h.classList.remove('sort-asc', 'sort-desc'));

                    // Add sort class to current header
                    this.classList.add(isAsc ? 'sort-desc' : 'sort-asc');

                    rows.sort((a, b) => {
                        let aVal = a.getAttribute('data-' + sortBy) || '';
                        let bVal = b.getAttribute('data-' + sortBy) || '';

                        // Convert to numbers if possible
                        if (!isNaN(parseFloat(aVal))) aVal = parseFloat(aVal);
                        if (!isNaN(parseFloat(bVal))) bVal = parseFloat(bVal);

                        if (aVal < bVal) return isAsc ? 1 : -1;
                        if (aVal > bVal) return isAsc ? -1 : 1;
                        return 0;
                    });

                    rows.forEach(row => tbody.appendChild(row));
                });
            });
        });
    </script>
</body>
</html>
