<?php
/**
 * FLOWB0T NEXUS - Jobs List Page
 * View and manage all crawl jobs
 */

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

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

// Pagination
$page = max(1, intval($_GET['p'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Filters
$statusFilter = $_GET['status'] ?? '';
$searchFilter = $_GET['search'] ?? '';

// Build query
$where = "1=1";
$params = [];

if ($statusFilter && in_array($statusFilter, ['pending','queued','running','paused','completed','failed','cancelled'])) {
    $where .= " AND status = ?";
    $params[] = $statusFilter;
}

if ($searchFilter) {
    $where .= " AND (name LIKE ? OR description LIKE ?)";
    $params[] = "%{$searchFilter}%";
    $params[] = "%{$searchFilter}%";
}

// Get total count
$totalJobs = 0;
$jobs = [];

try {
    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM nexus_jobs WHERE {$where}");
    $countStmt->execute($params);
    $totalJobs = (int) $countStmt->fetchColumn();

    // Get jobs
    $sql = "SELECT job_uuid, name, description, job_type, status, progress_percent,
                   total_queued, total_processed, total_imported, total_failed,
                   created_at, started_at, completed_at
            FROM nexus_jobs
            WHERE {$where}
            ORDER BY created_at DESC
            LIMIT {$perPage} OFFSET {$offset}";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $jobs = $stmt->fetchAll();
} catch (Exception $e) {
    // Table might not exist yet
}

$totalPages = ceil($totalJobs / $perPage);
?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-0">All Jobs</h2>
        <small class="text-muted"><?= number_format($totalJobs) ?> total jobs</small>
    </div>
    <a href="?page=new-job" class="btn btn-primary">
        <i class="bi bi-plus-circle me-2"></i>New Job
    </a>
</div>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3 align-items-end">
            <input type="hidden" name="page" value="jobs">
            <div class="col-md-4">
                <label class="form-label">Status</label>
                <select name="status" class="form-select">
                    <option value="">All Status</option>
                    <option value="running" <?= $statusFilter === 'running' ? 'selected' : '' ?>>Running</option>
                    <option value="queued" <?= $statusFilter === 'queued' ? 'selected' : '' ?>>Queued</option>
                    <option value="paused" <?= $statusFilter === 'paused' ? 'selected' : '' ?>>Paused</option>
                    <option value="completed" <?= $statusFilter === 'completed' ? 'selected' : '' ?>>Completed</option>
                    <option value="failed" <?= $statusFilter === 'failed' ? 'selected' : '' ?>>Failed</option>
                    <option value="cancelled" <?= $statusFilter === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                </select>
            </div>
            <div class="col-md-6">
                <label class="form-label">Search</label>
                <input type="text" name="search" class="form-control" placeholder="Search by name or description"
                       value="<?= htmlspecialchars($searchFilter) ?>">
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="bi bi-search me-2"></i>Filter
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Jobs Table -->
<div class="card">
    <div class="card-body p-0">
        <?php if (empty($jobs)): ?>
            <div class="text-center py-5 text-muted">
                <i class="bi bi-inbox display-4"></i>
                <p class="mt-3">No jobs found. <a href="?page=new-job">Create your first crawl job</a></p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Job Name</th>
                            <th>Type</th>
                            <th>Status</th>
                            <th>Progress</th>
                            <th>Processed</th>
                            <th>Imported</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($jobs as $job): ?>
                            <tr>
                                <td>
                                    <a href="?page=job-detail&id=<?= htmlspecialchars($job['job_uuid']) ?>" class="text-light text-decoration-none">
                                        <strong><?= htmlspecialchars($job['name']) ?></strong>
                                    </a>
                                    <?php if ($job['description']): ?>
                                        <br><small class="text-muted"><?= htmlspecialchars(mb_substr($job['description'], 0, 50)) ?>...</small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge bg-secondary"><?= ucfirst($job['job_type']) ?></span>
                                </td>
                                <td>
                                    <?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 ?>">
                                        <?php if ($job['status'] === 'running'): ?>
                                            <i class="bi bi-circle-fill pulse me-1" style="font-size: 0.5rem;"></i>
                                        <?php endif; ?>
                                        <?= ucfirst($job['status']) ?>
                                    </span>
                                </td>
                                <td style="width: 150px;">
                                    <div class="progress" style="height: 6px;">
                                        <div class="progress-bar" style="width: <?= $job['progress_percent'] ?>%"></div>
                                    </div>
                                    <small class="text-muted"><?= number_format($job['progress_percent'], 1) ?>%</small>
                                </td>
                                <td>
                                    <?= number_format($job['total_processed']) ?>
                                    <small class="text-muted">/ <?= number_format($job['total_queued']) ?></small>
                                </td>
                                <td>
                                    <span class="text-success"><?= number_format($job['total_imported']) ?></span>
                                    <?php if ($job['total_failed'] > 0): ?>
                                        <small class="text-danger">(<?= number_format($job['total_failed']) ?> failed)</small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <small><?= date('M j, Y', strtotime($job['created_at'])) ?></small>
                                    <br><small class="text-muted"><?= date('H:i', strtotime($job['created_at'])) ?></small>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <?php if ($job['status'] === 'running'): ?>
                                            <button class="btn btn-outline-warning" onclick="pauseJob('<?= $job['job_uuid'] ?>')" title="Pause">
                                                <i class="bi bi-pause"></i>
                                            </button>
                                        <?php elseif (in_array($job['status'], ['paused', 'queued'])): ?>
                                            <button class="btn btn-outline-success" onclick="resumeJob('<?= $job['job_uuid'] ?>')" title="Resume">
                                                <i class="bi bi-play"></i>
                                            </button>
                                        <?php endif; ?>
                                        <a href="?page=job-detail&id=<?= htmlspecialchars($job['job_uuid']) ?>" class="btn btn-outline-light" title="View Details">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                        <?php if (in_array($job['status'], ['completed', 'failed', 'cancelled'])): ?>
                                            <button class="btn btn-outline-danger" onclick="deleteJob('<?= $job['job_uuid'] ?>')" title="Delete">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
                <div class="card-footer d-flex justify-content-between align-items-center">
                    <div class="text-muted">
                        Showing <?= ($offset + 1) ?>-<?= min($offset + $perPage, $totalJobs) ?> of <?= $totalJobs ?>
                    </div>
                    <nav>
                        <ul class="pagination pagination-sm mb-0">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=jobs&p=<?= $page - 1 ?>&status=<?= $statusFilter ?>&search=<?= urlencode($searchFilter) ?>">
                                        <i class="bi bi-chevron-left"></i>
                                    </a>
                                </li>
                            <?php endif; ?>

                            <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                                <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                                    <a class="page-link" href="?page=jobs&p=<?= $i ?>&status=<?= $statusFilter ?>&search=<?= urlencode($searchFilter) ?>">
                                        <?= $i ?>
                                    </a>
                                </li>
                            <?php endfor; ?>

                            <?php if ($page < $totalPages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=jobs&p=<?= $page + 1 ?>&status=<?= $statusFilter ?>&search=<?= urlencode($searchFilter) ?>">
                                        <i class="bi bi-chevron-right"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </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 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) {
                location.reload();
            } else {
                NEXUS.toast('Failed to delete job', 'error');
            }
        });
    }
}
</script>
