<?php
/**
 * ============================================
 * FLOWBOT DCI v3.0 - PROCESSING LOGS
 * ============================================
 * Complete log history with search and filtering
 */
declare(strict_types=1);

$baseUrl = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
$pageTitle = 'Processing Logs';
$currentPage = 'logs';

// Get filter parameters
$filterStatus = $_GET['status'] ?? '';
$filterDomain = $_GET['domain'] ?? '';
$filterErrorType = $_GET['error_type'] ?? '';
$filterSearch = $_GET['search'] ?? '';
$filterDateFrom = $_GET['date_from'] ?? '';
$filterDateTo = $_GET['date_to'] ?? '';
$currentPageNum = (int)($_GET['p'] ?? 1);

// Get logs data
$logs = $logsData['logs'] ?? [];
$totalLogs = $logsData['total'] ?? 0;
$totalPages = $logsData['total_pages'] ?? 1;
$perPage = $logsData['per_page'] ?? 50;

// Status counts for quick filters
$statusCounts = ['success' => 0, 'warning' => 0, 'error' => 0, 'info' => 0];
foreach ($logs as $log) {
    $class = $log['class'] ?? 'info';
    if (isset($statusCounts[$class])) {
        $statusCounts[$class]++;
    }
}

// Error types for filter dropdown
$errorTypes = [
    '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',
    'other' => 'Other',
];

// Error patterns analysis
$errorPatterns = [];
foreach ($logs as $log) {
    if (($log['class'] ?? '') === 'error' && !empty($log['error_type'])) {
        $errorPatterns[$log['error_type']] = ($errorPatterns[$log['error_type']] ?? 0) + 1;
    }
}
arsort($errorPatterns);
?>
<!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">Processing Logs</h1>
            <p class="page-subtitle">Complete log history for process #<?= htmlspecialchars(substr($processId, 0, 8)) ?></p>
        </div>

        <!-- Filters Section -->
        <div class="section mb-lg">
            <div class="section-body">
                <form method="GET" class="filters-form" id="logsFilterForm">
                    <input type="hidden" name="process_id" value="<?= htmlspecialchars($processId) ?>">
                    <input type="hidden" name="page" value="logs">

                    <div class="grid-4col gap-md">
                        <div class="form-group">
                            <label for="filterStatus" class="form-label">Status</label>
                            <select name="status" id="filterStatus" class="input">
                                <option value="">All Status</option>
                                <option value="success" <?= $filterStatus === 'success' ? 'selected' : '' ?>>Success</option>
                                <option value="warning" <?= $filterStatus === 'warning' ? 'selected' : '' ?>>Warning</option>
                                <option value="error" <?= $filterStatus === 'error' ? 'selected' : '' ?>>Error</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="filterDomain" class="form-label">Domain</label>
                            <select name="domain" id="filterDomain" class="input">
                                <option value="">All Domains</option>
                                <?php foreach ($logDomains as $domain): ?>
                                <option value="<?= htmlspecialchars($domain) ?>" <?= $filterDomain === $domain ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($domain) ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="filterErrorType" class="form-label">Error Type</label>
                            <select name="error_type" id="filterErrorType" class="input">
                                <option value="">All Types</option>
                                <?php foreach ($errorTypes as $key => $label): ?>
                                <option value="<?= $key ?>" <?= $filterErrorType === $key ? 'selected' : '' ?>>
                                    <?= $label ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="filterSearch" class="form-label">Search</label>
                            <input type="text" name="search" id="filterSearch" class="input"
                                   placeholder="Search URL or message..."
                                   value="<?= htmlspecialchars($filterSearch) ?>">
                        </div>
                    </div>

                    <div class="grid-2col gap-md mt-md">
                        <div class="form-group">
                            <label for="filterDateFrom" class="form-label">From Date/Time</label>
                            <input type="datetime-local" name="date_from" id="filterDateFrom" class="input"
                                   value="<?= htmlspecialchars($filterDateFrom) ?>">
                        </div>
                        <div class="form-group">
                            <label for="filterDateTo" class="form-label">To Date/Time</label>
                            <input type="datetime-local" name="date_to" id="filterDateTo" class="input"
                                   value="<?= htmlspecialchars($filterDateTo) ?>">
                        </div>
                    </div>

                    <div class="flex justify-between items-center mt-md">
                        <div class="btn-group">
                            <a href="?process_id=<?= urlencode($processId) ?>&page=logs"
                               class="btn btn-ghost btn-sm <?= empty($filterStatus) ? 'active' : '' ?>">
                                All <span class="badge badge-info ml-xs"><?= number_format($totalLogs) ?></span>
                            </a>
                            <a href="?process_id=<?= urlencode($processId) ?>&page=logs&status=success"
                               class="btn btn-ghost btn-sm <?= $filterStatus === 'success' ? 'active' : '' ?>">
                                <span class="text-success">Success</span>
                            </a>
                            <a href="?process_id=<?= urlencode($processId) ?>&page=logs&status=warning"
                               class="btn btn-ghost btn-sm <?= $filterStatus === 'warning' ? 'active' : '' ?>">
                                <span class="text-warning">Warnings</span>
                            </a>
                            <a href="?process_id=<?= urlencode($processId) ?>&page=logs&status=error"
                               class="btn btn-ghost btn-sm <?= $filterStatus === 'error' ? 'active' : '' ?>">
                                <span class="text-error">Errors</span>
                            </a>
                        </div>

                        <div class="flex gap-sm">
                            <button type="submit" class="btn btn-primary btn-sm">Apply Filters</button>
                            <a href="?process_id=<?= urlencode($processId) ?>&page=logs" class="btn btn-ghost btn-sm">Clear</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Dashboard Grid -->
        <div class="dashboard-grid">
            <!-- Main Column -->
            <div class="dashboard-main">
                <!-- Logs 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">
                                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                                <polyline points="14 2 14 8 20 8"/>
                                <line x1="16" y1="13" x2="8" y2="13"/>
                                <line x1="16" y1="17" x2="8" y2="17"/>
                                <polyline points="10 9 9 9 8 9"/>
                            </svg>
                            Log Entries
                            <span class="text-muted text-sm ml-sm">
                                Showing <?= (($currentPageNum - 1) * $perPage) + 1 ?>-<?= min($currentPageNum * $perPage, $totalLogs) ?>
                                of <?= number_format($totalLogs) ?>
                            </span>
                        </h2>
                        <div class="btn-group">
                            <a href="?process_id=<?= urlencode($processId) ?>&page=api&action=export&type=logs&format=csv" class="btn btn-ghost btn-sm">Export CSV</a>
                            <a href="?process_id=<?= urlencode($processId) ?>&page=api&action=export&type=logs&format=json" class="btn btn-ghost btn-sm">Export JSON</a>
                        </div>
                    </div>

                    <div class="table-container">
                        <table id="logsTable">
                            <thead>
                                <tr>
                                    <th style="width: 70px;">Time</th>
                                    <th style="width: 140px;">Domain</th>
                                    <th>URL</th>
                                    <th style="width: 80px;" class="text-center">Status</th>
                                    <th style="width: 60px;" class="text-center">Phase</th>
                                    <th style="width: 60px;" class="text-center">HTTP</th>
                                    <th style="width: 70px;" class="text-center">Time</th>
                                    <th style="width: 200px;">Message</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($logs)): ?>
                                <tr>
                                    <td colspan="8" class="text-center text-muted py-lg">
                                        No log entries found matching your filters.
                                    </td>
                                </tr>
                                <?php else: ?>
                                <?php foreach ($logs as $log):
                                    $class = $log['class'] ?? 'info';
                                    $statusLabel = match($class) {
                                        'success' => 'OK',
                                        'warning' => 'Skip',
                                        'error' => 'Error',
                                        default => 'Info',
                                    };
                                    $timestamp = $log['timestamp'] ?? '';
                                    $time = $timestamp ? date('H:i:s', strtotime($timestamp)) : '';
                                    $responseTime = $log['response_time'] ?? 0;
                                ?>
                                <tr class="log-row <?= $class ?>">
                                    <td class="text-muted"><?= $time ?></td>
                                    <td title="<?= htmlspecialchars($log['domain'] ?? '') ?>">
                                        <span class="text-truncate" style="max-width: 130px; display: inline-block;">
                                            <?= htmlspecialchars($log['domain'] ?? '') ?>
                                        </span>
                                    </td>
                                    <td title="<?= htmlspecialchars($log['url'] ?? '') ?>">
                                        <span class="text-truncate" style="max-width: 300px; display: inline-block;">
                                            <?= htmlspecialchars($log['url'] ?? '') ?>
                                        </span>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge badge-<?= $class ?>"><?= $statusLabel ?></span>
                                    </td>
                                    <td class="text-center"><?= $log['phase'] ?? '-' ?></td>
                                    <td class="text-center">
                                        <?php if (!empty($log['http_code']) && $log['http_code'] > 0): ?>
                                        <span class="badge badge-sm badge-<?= $log['http_code'] >= 400 ? 'error' : 'success' ?>"><?= $log['http_code'] ?></span>
                                        <?php else: ?>
                                        <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <?php if ($responseTime > 0): ?>
                                        <span class="<?= $responseTime > 5 ? 'text-error' : ($responseTime > 2 ? 'text-warning' : '') ?>">
                                            <?= number_format($responseTime, 2) ?>s
                                        </span>
                                        <?php else: ?>
                                        <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td title="<?= htmlspecialchars($log['message'] ?? '') ?>">
                                        <span class="text-truncate" style="max-width: 190px; display: inline-block;">
                                            <?= htmlspecialchars($log['message'] ?? '') ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($totalPages > 1): ?>
                    <div class="flex justify-center gap-sm mt-lg pb-md">
                        <?php
                        $baseQueryParams = [
                            'process_id' => $processId,
                            'page' => 'logs',
                        ];
                        if ($filterStatus) $baseQueryParams['status'] = $filterStatus;
                        if ($filterDomain) $baseQueryParams['domain'] = $filterDomain;
                        if ($filterErrorType) $baseQueryParams['error_type'] = $filterErrorType;
                        if ($filterSearch) $baseQueryParams['search'] = $filterSearch;
                        if ($filterDateFrom) $baseQueryParams['date_from'] = $filterDateFrom;
                        if ($filterDateTo) $baseQueryParams['date_to'] = $filterDateTo;
                        ?>

                        <?php if ($currentPageNum > 1): ?>
                        <a href="?<?= http_build_query(array_merge($baseQueryParams, ['p' => $currentPageNum - 1])) ?>" 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>
                            Prev
                        </a>
                        <?php endif; ?>

                        <?php
                        $startPage = max(1, $currentPageNum - 2);
                        $endPage = min($totalPages, $currentPageNum + 2);
                        ?>

                        <?php if ($startPage > 1): ?>
                        <a href="?<?= http_build_query(array_merge($baseQueryParams, ['p' => 1])) ?>" class="btn btn-ghost btn-sm">1</a>
                        <?php if ($startPage > 2): ?>
                        <span class="text-muted px-sm">...</span>
                        <?php endif; ?>
                        <?php endif; ?>

                        <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                        <a href="?<?= http_build_query(array_merge($baseQueryParams, ['p' => $i])) ?>"
                           class="btn btn-sm <?= $i === $currentPageNum ? 'btn-primary' : 'btn-ghost' ?>"><?= $i ?></a>
                        <?php endfor; ?>

                        <?php if ($endPage < $totalPages): ?>
                        <?php if ($endPage < $totalPages - 1): ?>
                        <span class="text-muted px-sm">...</span>
                        <?php endif; ?>
                        <a href="?<?= http_build_query(array_merge($baseQueryParams, ['p' => $totalPages])) ?>" class="btn btn-ghost btn-sm"><?= $totalPages ?></a>
                        <?php endif; ?>

                        <?php if ($currentPageNum < $totalPages): ?>
                        <a href="?<?= http_build_query(array_merge($baseQueryParams, ['p' => $currentPageNum + 1])) ?>" class="btn btn-ghost btn-sm">
                            Next
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                                <polyline points="9 18 15 12 9 6"/>
                            </svg>
                        </a>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="dashboard-sidebar">
                <!-- Error Patterns -->
                <?php if (!empty($errorPatterns)): ?>
                <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 Patterns
                        </h2>
                    </div>
                    <div class="section-body">
                        <ul class="activity-list">
                            <?php foreach (array_slice($errorPatterns, 0, 6, true) as $type => $count):
                                $label = $errorTypes[$type] ?? ucfirst($type);
                            ?>
                            <li class="activity-item">
                                <div class="activity-icon error">!</div>
                                <div class="activity-content">
                                    <p class="activity-text"><?= $label ?></p>
                                    <span class="activity-time"><?= number_format($count) ?> errors</span>
                                </div>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Quick Stats -->
                <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>
                            Page Stats
                        </h2>
                    </div>
                    <div class="section-body">
                        <div class="perf-stats">
                            <div class="perf-stat">
                                <span class="perf-label">Success</span>
                                <span class="perf-value text-success"><?= number_format($statusCounts['success']) ?></span>
                            </div>
                            <div class="perf-stat">
                                <span class="perf-label">Warnings</span>
                                <span class="perf-value text-warning"><?= number_format($statusCounts['warning']) ?></span>
                            </div>
                            <div class="perf-stat">
                                <span class="perf-label">Errors</span>
                                <span class="perf-value text-error"><?= number_format($statusCounts['error']) ?></span>
                            </div>
                            <div class="perf-stat mt-md">
                                <span class="perf-label">Total Logs</span>
                                <span class="perf-value"><?= number_format($totalLogs) ?></span>
                            </div>
                            <div class="perf-stat">
                                <span class="perf-label">Pages</span>
                                <span class="perf-value"><?= number_format($totalPages) ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </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) ?>';
    </script>
</body>
</html>
