<?php
/**
 * FLOWB0T NEXUS - Job Detail Page
 * View detailed information and control a specific crawl job
 */

require_once NEXUS_ROOT . '/core/Database.php';
use Flowb0t\Core\Database;

$db = Database::getInstance();
$pdo = $db->getConnection();

$jobId = $_GET['id'] ?? '';
$job = null;
$recentResults = [];
$recentLogs = [];
$topDomains = [];

if ($jobId) {
    try {
        // Get job details
        $stmt = $pdo->prepare("SELECT * FROM nexus_jobs WHERE job_uuid = ?");
        $stmt->execute([$jobId]);
        $job = $stmt->fetch();

        if ($job) {
            // Get recent results for this job
            $stmt = $pdo->prepare("
                SELECT url, title, http_status, relevance_score, import_status, crawled_at
                FROM nexus_results
                WHERE job_id = ?
                ORDER BY crawled_at DESC
                LIMIT 10
            ");
            $stmt->execute([$job['id']]);
            $recentResults = $stmt->fetchAll();

            // Get recent logs
            $stmt = $pdo->prepare("
                SELECT log_level, category, message, created_at
                FROM nexus_logs
                WHERE job_id = ?
                ORDER BY created_at DESC
                LIMIT 20
            ");
            $stmt->execute([$job['id']]);
            $recentLogs = $stmt->fetchAll();

            // Get top domains for this job
            $stmt = $pdo->prepare("
                SELECT domain, COUNT(*) as count
                FROM nexus_queue
                WHERE job_id = ?
                GROUP BY domain
                ORDER BY count DESC
                LIMIT 5
            ");
            $stmt->execute([$job['id']]);
            $topDomains = $stmt->fetchAll();
        }
    } catch (Exception $e) {
        // Handle error
    }
}

if (!$job) {
    echo '<div class="alert alert-danger">Job not found</div>';
    echo '<a href="?page=jobs" class="btn btn-primary">Back to Jobs</a>';
    return;
}

// Calculate duration
$duration = '';
if ($job['started_at']) {
    $start = new DateTime($job['started_at']);
    $end = $job['completed_at'] ? new DateTime($job['completed_at']) : new DateTime();
    $diff = $start->diff($end);
    if ($diff->h > 0) {
        $duration = $diff->h . 'h ' . $diff->i . 'm';
    } else {
        $duration = $diff->i . 'm ' . $diff->s . 's';
    }
}

// Phase names
$phases = [
    0 => 'Seed Collection',
    1 => 'Search Expansion',
    2 => 'Fast Crawl',
    3 => 'Medium Crawl',
    4 => 'Slow Crawl',
    5 => 'Import to Database'
];
$currentPhase = $phases[$job['current_phase']] ?? 'Unknown';
?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-0"><?= htmlspecialchars($job['name']) ?></h2>
        <small class="text-muted"><?= htmlspecialchars($job['description'] ?: 'No description') ?></small>
    </div>
    <div class="d-flex gap-2">
        <?php if ($job['status'] === 'running'): ?>
            <button class="btn btn-warning" onclick="pauseJob('<?= $jobId ?>')">
                <i class="bi bi-pause me-2"></i>Pause
            </button>
            <button class="btn btn-danger" onclick="cancelJob('<?= $jobId ?>')">
                <i class="bi bi-x-circle me-2"></i>Cancel
            </button>
        <?php elseif ($job['status'] === 'paused'): ?>
            <button class="btn btn-success" onclick="resumeJob('<?= $jobId ?>')">
                <i class="bi bi-play me-2"></i>Resume
            </button>
            <button class="btn btn-danger" onclick="cancelJob('<?= $jobId ?>')">
                <i class="bi bi-x-circle me-2"></i>Cancel
            </button>
        <?php elseif (in_array($job['status'], ['completed', 'failed', 'cancelled'])): ?>
            <button class="btn btn-primary" onclick="restartJob('<?= $jobId ?>')">
                <i class="bi bi-arrow-repeat me-2"></i>Restart
            </button>
        <?php endif; ?>
        <a href="?page=jobs" class="btn btn-outline-light">
            <i class="bi bi-arrow-left me-2"></i>Back
        </a>
    </div>
</div>

<!-- Status & Progress -->
<div class="card mb-4">
    <div class="card-body">
        <div class="row align-items-center">
            <div class="col-md-2 text-center">
                <?php
                $statusClass = [
                    'running' => 'badge-running',
                    'queued' => 'badge-paused',
                    'paused' => 'badge-paused',
                    'pending' => 'bg-secondary',
                    'completed' => 'badge-completed',
                    'failed' => 'badge-failed',
                    'cancelled' => 'bg-dark'
                ][$job['status']] ?? 'bg-secondary';
                ?>
                <span class="badge <?= $statusClass ?> px-3 py-2" style="font-size: 1rem;">
                    <?php if ($job['status'] === 'running'): ?>
                        <i class="bi bi-circle-fill pulse me-1" style="font-size: 0.6rem;"></i>
                    <?php endif; ?>
                    <?= strtoupper($job['status']) ?>
                </span>
                <div class="mt-2 text-muted small">Phase: <?= $currentPhase ?></div>
            </div>
            <div class="col-md-7">
                <div class="d-flex justify-content-between mb-1">
                    <span>Progress</span>
                    <span><?= number_format($job['progress_percent'], 1) ?>%</span>
                </div>
                <div class="progress" style="height: 20px;">
                    <div class="progress-bar" style="width: <?= $job['progress_percent'] ?>%">
                        <?= number_format($job['progress_percent'], 1) ?>%
                    </div>
                </div>
            </div>
            <div class="col-md-3 text-end">
                <?php if ($duration): ?>
                    <div class="text-muted">Duration</div>
                    <div class="h4 mb-0"><?= $duration ?></div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Stats Cards -->
<div class="row g-4 mb-4">
    <div class="col-md-2">
        <div class="stat-card text-center">
            <div class="value"><?= number_format($job['total_queued']) ?></div>
            <div class="label">Queued</div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="stat-card text-center">
            <div class="value"><?= number_format($job['total_processed']) ?></div>
            <div class="label">Processed</div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="stat-card text-center">
            <div class="value text-success"><?= number_format($job['total_successful']) ?></div>
            <div class="label">Successful</div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="stat-card text-center">
            <div class="value text-primary"><?= number_format($job['total_imported']) ?></div>
            <div class="label">Imported</div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="stat-card text-center">
            <div class="value text-warning"><?= number_format($job['total_skipped']) ?></div>
            <div class="label">Skipped</div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="stat-card text-center">
            <div class="value text-danger"><?= number_format($job['total_failed']) ?></div>
            <div class="label">Failed</div>
        </div>
    </div>
</div>

<div class="row g-4">
    <!-- Live Log -->
    <div class="col-md-8">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-terminal me-2"></i>Live Activity Log</h5>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="autoScroll" checked>
                    <label class="form-check-label" for="autoScroll">Auto-scroll</label>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="log-viewer" id="logViewer">
                    <?php if (empty($recentLogs)): ?>
                        <div class="text-center text-muted py-3">No logs yet</div>
                    <?php else: ?>
                        <?php foreach ($recentLogs as $log): ?>
                            <div class="log-entry">
                                <span class="log-time"><?= date('H:i:s', strtotime($log['created_at'])) ?></span>
                                <span class="log-level-<?= $log['log_level'] ?>">[<?= $log['log_level'] ?>]</span>
                                <span class="text-muted">[<?= $log['category'] ?>]</span>
                                <?= htmlspecialchars($log['message']) ?>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Recent Results -->
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-list-check me-2"></i>Recent Results</h5>
            </div>
            <div class="card-body p-0">
                <?php if (empty($recentResults)): ?>
                    <div class="text-center text-muted py-4">No results yet</div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-sm mb-0">
                            <thead>
                                <tr>
                                    <th>URL</th>
                                    <th>Title</th>
                                    <th>Status</th>
                                    <th>Score</th>
                                    <th>Import</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recentResults as $result): ?>
                                    <tr>
                                        <td style="max-width: 200px; overflow: hidden; text-overflow: ellipsis;">
                                            <a href="<?= htmlspecialchars($result['url']) ?>" target="_blank" class="text-light">
                                                <?= htmlspecialchars(mb_substr($result['url'], 0, 40)) ?>...
                                            </a>
                                        </td>
                                        <td style="max-width: 200px; overflow: hidden; text-overflow: ellipsis;">
                                            <?= htmlspecialchars($result['title'] ?: 'No title') ?>
                                        </td>
                                        <td>
                                            <?php if ($result['http_status'] == 200): ?>
                                                <span class="badge bg-success"><?= $result['http_status'] ?></span>
                                            <?php else: ?>
                                                <span class="badge bg-danger"><?= $result['http_status'] ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?= number_format($result['relevance_score'], 1) ?></td>
                                        <td>
                                            <?php if ($result['import_status'] === 'imported'): ?>
                                                <i class="bi bi-check-circle text-success"></i>
                                            <?php elseif ($result['import_status'] === 'pending'): ?>
                                                <i class="bi bi-clock text-warning"></i>
                                            <?php else: ?>
                                                <i class="bi bi-x-circle text-danger"></i>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Sidebar -->
    <div class="col-md-4">
        <!-- Job Configuration -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-gear me-2"></i>Configuration</h5>
            </div>
            <div class="card-body">
                <table class="table table-sm mb-0">
                    <tr>
                        <td class="text-muted">Type</td>
                        <td><?= ucfirst($job['job_type']) ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Max Depth</td>
                        <td><?= $job['max_depth'] ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Max Pages</td>
                        <td><?= number_format($job['max_pages']) ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Concurrent</td>
                        <td><?= $job['max_concurrent'] ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Timeout</td>
                        <td><?= $job['request_timeout'] ?>s</td>
                    </tr>
                    <tr>
                        <td class="text-muted">Search Provider</td>
                        <td><?= ucfirst($job['search_provider']) ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Auto Import</td>
                        <td><?= $job['auto_import'] ? 'Yes' : 'No' ?></td>
                    </tr>
                </table>
            </div>
        </div>

        <!-- Top Domains -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-globe me-2"></i>Top Domains</h5>
            </div>
            <div class="card-body p-0">
                <?php if (empty($topDomains)): ?>
                    <div class="text-center text-muted py-3">No data yet</div>
                <?php else: ?>
                    <ul class="list-group list-group-flush">
                        <?php foreach ($topDomains as $domain): ?>
                            <li class="list-group-item d-flex justify-content-between align-items-center bg-transparent">
                                <span><?= htmlspecialchars($domain['domain'] ?: 'Unknown') ?></span>
                                <span class="badge bg-primary rounded-pill"><?= number_format($domain['count']) ?></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>

        <!-- Actions -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-lightning me-2"></i>Actions</h5>
            </div>
            <div class="card-body d-grid gap-2">
                <a href="?page=results&job_id=<?= $jobId ?>" class="btn btn-outline-primary">
                    <i class="bi bi-database me-2"></i>View All Results
                </a>
                <button class="btn btn-outline-success" onclick="exportResults('<?= $jobId ?>', 'csv')">
                    <i class="bi bi-file-earmark-spreadsheet me-2"></i>Export CSV
                </button>
                <button class="btn btn-outline-info" onclick="exportResults('<?= $jobId ?>', 'json')">
                    <i class="bi bi-file-earmark-code me-2"></i>Export JSON
                </button>
                <?php if (in_array($job['status'], ['completed', 'failed', 'cancelled'])): ?>
                    <button class="btn btn-outline-danger" onclick="deleteJob('<?= $jobId ?>')">
                        <i class="bi bi-trash me-2"></i>Delete Job
                    </button>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
function pauseJob(id) {
    NEXUS.api('pause_job', {id: id}).then(r => {
        if (r.success) location.reload();
        else NEXUS.toast('Failed to pause job', 'error');
    });
}

function resumeJob(id) {
    NEXUS.api('resume_job', {id: id}).then(r => {
        if (r.success) location.reload();
        else NEXUS.toast('Failed to resume job', 'error');
    });
}

function cancelJob(id) {
    if (confirm('Are you sure you want to cancel this job?')) {
        NEXUS.api('cancel_job', {id: id}).then(r => {
            if (r.success) location.reload();
            else NEXUS.toast('Failed to cancel job', 'error');
        });
    }
}

function restartJob(id) {
    if (confirm('Are you sure you want to restart this job? All previous progress will be lost.')) {
        NEXUS.api('restart_job', {id: id}).then(r => {
            if (r.success) location.reload();
            else NEXUS.toast('Failed to restart job', 'error');
        });
    }
}

function deleteJob(id) {
    if (confirm('Are you sure you want to delete this job? This cannot be undone.')) {
        NEXUS.api('delete_job', {id: id}).then(r => {
            if (r.success) window.location = '?page=jobs';
            else NEXUS.toast('Failed to delete job', 'error');
        });
    }
}

function exportResults(id, format) {
    NEXUS.api('export_job', {id: id, format: format}).then(r => {
        if (r.success) {
            NEXUS.toast('Export started. Check exports page.', 'success');
        } else {
            NEXUS.toast('Failed to start export', 'error');
        }
    });
}

// Auto-refresh for running jobs
<?php if ($job['status'] === 'running'): ?>
setInterval(() => {
    location.reload();
}, 10000);
<?php endif; ?>
</script>
