<?php
/**
 * FLOWB0T NEXUS - Dashboard Page
 * Main dashboard with statistics and active jobs overview
 */

// Load required classes
require_once NEXUS_ROOT . '/core/Database.php';
require_once NEXUS_ROOT . '/engine/Processors/ImportProcessor.php';

use Flowb0t\Core\Database;
use Flowb0t\Engine\Processors\ImportProcessor;

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

// Get statistics
$activeJobs = 0;
$totalJobs = 0;
$totalCrawled = 0;
$importedToday = 0;

try {
    // Active jobs from nexus_jobs
    $stmt = $pdo->query("SELECT COUNT(*) FROM nexus_jobs WHERE status IN ('running', 'queued')");
    $activeJobs = (int) $stmt->fetchColumn();

    // Total jobs
    $stmt = $pdo->query("SELECT COUNT(*) FROM nexus_jobs");
    $totalJobs = (int) $stmt->fetchColumn();

    // Total crawled (from nexus_results)
    $stmt = $pdo->query("SELECT COUNT(*) FROM nexus_results");
    $totalCrawled = (int) $stmt->fetchColumn();

    // Imported today to pinfeeds
    $stmt = $pdo->query("SELECT COUNT(*) FROM pinfeeds WHERE DATE(pubDate) = CURDATE()");
    $importedToday = (int) $stmt->fetchColumn();
} catch (Exception $e) {
    // Tables might not exist yet
}

// Get pinfeeds stats
$pinfeedsTotal = $importProcessor->getPinfeedsCount();
$usersTotal = $importProcessor->getUsersCount();
$domainsTotal = $importProcessor->getDomainsCount();

// Get recent imports
$recentImports = $importProcessor->getRecentImports(5);

// Get top domains
$topDomains = $importProcessor->getTopDomains(5);

// Get running jobs
$runningJobs = [];
try {
    $stmt = $pdo->query("
        SELECT job_uuid, name, status, progress_percent, total_queued, total_processed,
               total_imported, started_at, current_phase
        FROM nexus_jobs
        WHERE status IN ('running', 'queued', 'paused')
        ORDER BY started_at DESC
        LIMIT 5
    ");
    $runningJobs = $stmt->fetchAll();
} catch (Exception $e) {
    // Table might not exist
}
?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-0">Dashboard</h2>
        <small class="text-muted">Welcome to FLOWB0T NEXUS Control Center</small>
    </div>
    <div>
        <a href="?page=new-job" class="btn btn-primary">
            <i class="bi bi-plus-circle me-2"></i>New Crawl Job
        </a>
    </div>
</div>

<!-- Stats Cards -->
<div class="row g-4 mb-4" id="stats">
    <div class="col-md-3">
        <div class="stat-card">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="value"><?= number_format($activeJobs) ?></div>
                    <div class="label">Active Jobs</div>
                </div>
                <div class="icon bg-primary bg-opacity-25 text-primary">
                    <i class="bi bi-activity"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="value"><?= number_format($pinfeedsTotal) ?></div>
                    <div class="label">Total in Pinfeeds</div>
                </div>
                <div class="icon bg-success bg-opacity-25 text-success">
                    <i class="bi bi-database"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="value"><?= number_format($importedToday) ?></div>
                    <div class="label">Imported Today</div>
                </div>
                <div class="icon bg-info bg-opacity-25 text-info">
                    <i class="bi bi-arrow-down-circle"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="value"><?= number_format($domainsTotal) ?></div>
                    <div class="label">Unique Domains</div>
                </div>
                <div class="icon bg-warning bg-opacity-25 text-warning">
                    <i class="bi bi-globe"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Additional Stats Row -->
<div class="row g-4 mb-4">
    <div class="col-md-4">
        <div class="stat-card">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="value"><?= number_format($usersTotal) ?></div>
                    <div class="label">Authors Created</div>
                </div>
                <div class="icon bg-danger bg-opacity-25 text-danger">
                    <i class="bi bi-people"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="stat-card">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="value"><?= number_format($totalJobs) ?></div>
                    <div class="label">Total Jobs</div>
                </div>
                <div class="icon bg-secondary bg-opacity-25 text-secondary">
                    <i class="bi bi-list-task"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="stat-card">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="value"><?= number_format($totalCrawled) ?></div>
                    <div class="label">URLs Crawled</div>
                </div>
                <div class="icon" style="background: rgba(99, 102, 241, 0.25); color: var(--nexus-primary);">
                    <i class="bi bi-link-45deg"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Active Jobs -->
<div class="card mb-4" id="active-jobs">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-lightning me-2"></i>Active Jobs</h5>
        <a href="?page=jobs" class="btn btn-sm btn-outline-light">View All</a>
    </div>
    <div class="card-body p-0">
        <?php if (empty($runningJobs)): ?>
            <div class="text-center py-5 text-muted">
                <i class="bi bi-inbox display-4"></i>
                <p class="mt-3">No active jobs. <a href="?page=new-job">Start a new 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>Status</th>
                            <th>Progress</th>
                            <th>URLs</th>
                            <th>Imported</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($runningJobs as $job): ?>
                            <tr>
                                <td>
                                    <a href="?page=job-detail&id=<?= htmlspecialchars($job['job_uuid']) ?>">
                                        <?= htmlspecialchars($job['name']) ?>
                                    </a>
                                </td>
                                <td>
                                    <?php
                                    $statusClass = [
                                        'running' => 'badge-running',
                                        'queued' => 'badge-paused',
                                        'paused' => 'badge-paused',
                                        'completed' => 'badge-completed',
                                        'failed' => 'badge-failed'
                                    ][$job['status']] ?? 'badge-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: 200px;">
                                    <div class="progress" style="height: 8px;">
                                        <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']) ?> / <?= number_format($job['total_queued']) ?></td>
                                <td><?= number_format($job['total_imported']) ?></td>
                                <td>
                                    <?php if ($job['status'] === 'running'): ?>
                                        <button class="btn btn-sm btn-outline-warning" onclick="NEXUS.api('pause_job', {id: '<?= $job['job_uuid'] ?>'})">
                                            <i class="bi bi-pause"></i>
                                        </button>
                                    <?php elseif ($job['status'] === 'paused'): ?>
                                        <button class="btn btn-sm btn-outline-success" onclick="NEXUS.api('resume_job', {id: '<?= $job['job_uuid'] ?>'})">
                                            <i class="bi bi-play"></i>
                                        </button>
                                    <?php endif; ?>
                                    <a href="?page=job-detail&id=<?= htmlspecialchars($job['job_uuid']) ?>" class="btn btn-sm btn-outline-light">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Two Column Layout -->
<div class="row g-4">
    <!-- Top Domains -->
    <div class="col-md-6">
        <div class="card">
            <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 py-4 text-muted">
                        <p class="mb-0">No domain data yet</p>
                    </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>
                                    <i class="bi bi-globe2 me-2 text-muted"></i>
                                    <?= htmlspecialchars($domain['source_domain'] ?: 'Unknown') ?>
                                </span>
                                <span class="badge bg-primary rounded-pill">
                                    <?= number_format($domain['count']) ?>
                                </span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Recent Imports -->
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-clock-history me-2"></i>Recent Imports</h5>
            </div>
            <div class="card-body p-0">
                <?php if (empty($recentImports)): ?>
                    <div class="text-center py-4 text-muted">
                        <p class="mb-0">No imports yet</p>
                    </div>
                <?php else: ?>
                    <ul class="list-group list-group-flush">
                        <?php foreach ($recentImports as $item): ?>
                            <li class="list-group-item bg-transparent">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="me-2" style="overflow: hidden;">
                                        <a href="<?= htmlspecialchars($item['link']) ?>" target="_blank"
                                           class="text-light text-decoration-none"
                                           style="display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; overflow: hidden;">
                                            <?= htmlspecialchars(mb_substr($item['title'], 0, 50)) ?>...
                                        </a>
                                        <small class="text-muted d-block">
                                            <?= htmlspecialchars($item['source_domain']) ?> &bull; <?= htmlspecialchars($item['author']) ?>
                                        </small>
                                    </div>
                                    <small class="text-muted text-nowrap">
                                        <?= date('H:i', strtotime($item['pubDate'])) ?>
                                    </small>
                                </div>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Quick Actions -->
<div class="card mt-4">
    <div class="card-header">
        <h5 class="mb-0"><i class="bi bi-lightning-charge me-2"></i>Quick Actions</h5>
    </div>
    <div class="card-body">
        <div class="row g-3">
            <div class="col-md-3">
                <a href="?page=new-job" class="btn btn-outline-primary w-100 py-3">
                    <i class="bi bi-plus-circle d-block mb-2" style="font-size: 1.5rem;"></i>
                    New Crawl Job
                </a>
            </div>
            <div class="col-md-3">
                <a href="?page=results" class="btn btn-outline-success w-100 py-3">
                    <i class="bi bi-database d-block mb-2" style="font-size: 1.5rem;"></i>
                    Browse Results
                </a>
            </div>
            <div class="col-md-3">
                <a href="?page=exports" class="btn btn-outline-info w-100 py-3">
                    <i class="bi bi-download d-block mb-2" style="font-size: 1.5rem;"></i>
                    Export Data
                </a>
            </div>
            <div class="col-md-3">
                <a href="?page=logs" class="btn btn-outline-warning w-100 py-3">
                    <i class="bi bi-terminal d-block mb-2" style="font-size: 1.5rem;"></i>
                    View Logs
                </a>
            </div>
        </div>
    </div>
</div>
