<?php
/**
 * FLOWB0T NEXUS - Results Browser
 * Browse and search crawled results from pinfeeds table
 */

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 = 50;
$offset = ($page - 1) * $perPage;

// Filters
$searchFilter = $_GET['search'] ?? '';
$domainFilter = $_GET['domain'] ?? '';
$dateFrom = $_GET['date_from'] ?? '';
$dateTo = $_GET['date_to'] ?? '';

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

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

if ($domainFilter) {
    $where .= " AND source_domain LIKE ?";
    $params[] = "%{$domainFilter}%";
}

if ($dateFrom) {
    $where .= " AND pubDate >= ?";
    $params[] = $dateFrom;
}

if ($dateTo) {
    $where .= " AND pubDate <= ?";
    $params[] = $dateTo . ' 23:59:59';
}

// Get total count and results from pinfeeds
$totalResults = 0;
$results = [];
$domains = [];

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

    // Get results
    $sql = "SELECT id, title, description, thumbnail, link, pubDate, author, source_domain, favicon
            FROM pinfeeds
            WHERE {$where}
            ORDER BY id DESC
            LIMIT {$perPage} OFFSET {$offset}";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $results = $stmt->fetchAll();

    // Get unique domains for filter
    $stmt = $pdo->query("SELECT DISTINCT source_domain FROM pinfeeds WHERE source_domain != '' ORDER BY source_domain LIMIT 100");
    $domains = $stmt->fetchAll(\PDO::FETCH_COLUMN);
} catch (Exception $e) {
    // Table might not exist
}

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

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-0">Results Browser</h2>
        <small class="text-muted"><?= number_format($totalResults) ?> records in pinfeeds</small>
    </div>
    <div class="btn-group">
        <button class="btn btn-outline-success" onclick="exportAll('csv')">
            <i class="bi bi-file-earmark-spreadsheet me-2"></i>Export CSV
        </button>
        <button class="btn btn-outline-info" onclick="exportAll('json')">
            <i class="bi bi-file-earmark-code me-2"></i>Export JSON
        </button>
    </div>
</div>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <input type="hidden" name="page" value="results">
            <div class="col-md-3">
                <label class="form-label">Search</label>
                <input type="text" name="search" class="form-control" placeholder="Title, description, URL..."
                       value="<?= htmlspecialchars($searchFilter) ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Domain</label>
                <select name="domain" class="form-select">
                    <option value="">All Domains</option>
                    <?php foreach ($domains as $domain): ?>
                        <option value="<?= htmlspecialchars($domain) ?>" <?= $domainFilter === $domain ? 'selected' : '' ?>>
                            <?= htmlspecialchars($domain) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Date From</label>
                <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($dateFrom) ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Date To</label>
                <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($dateTo) ?>">
            </div>
            <div class="col-md-3 d-flex align-items-end gap-2">
                <button type="submit" class="btn btn-primary flex-grow-1">
                    <i class="bi bi-search me-2"></i>Search
                </button>
                <a href="?page=results" class="btn btn-outline-secondary">
                    <i class="bi bi-x"></i>
                </a>
            </div>
        </form>
    </div>
</div>

<!-- Results Grid -->
<?php if (empty($results)): ?>
    <div class="card">
        <div class="card-body text-center py-5 text-muted">
            <i class="bi bi-inbox display-4"></i>
            <p class="mt-3">No results found</p>
        </div>
    </div>
<?php else: ?>
    <div class="row g-4">
        <?php foreach ($results as $item): ?>
            <div class="col-md-6 col-lg-4">
                <div class="card h-100">
                    <?php if ($item['thumbnail'] && $item['thumbnail'] !== 'fallback_image.jpg'): ?>
                        <img src="<?= htmlspecialchars($item['thumbnail']) ?>" class="card-img-top"
                             style="height: 150px; object-fit: cover;"
                             onerror="this.src='https://via.placeholder.com/300x150?text=No+Image'">
                    <?php endif; ?>
                    <div class="card-body">
                        <h6 class="card-title">
                            <a href="<?= htmlspecialchars($item['link']) ?>" target="_blank" class="text-light text-decoration-none">
                                <?= htmlspecialchars(mb_substr($item['title'], 0, 80)) ?>
                                <?= mb_strlen($item['title']) > 80 ? '...' : '' ?>
                            </a>
                        </h6>
                        <p class="card-text small text-muted" style="display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;">
                            <?= htmlspecialchars(mb_substr($item['description'], 0, 150)) ?>
                        </p>
                    </div>
                    <div class="card-footer bg-transparent">
                        <div class="d-flex justify-content-between align-items-center">
                            <small class="text-muted">
                                <i class="bi bi-globe me-1"></i>
                                <?= htmlspecialchars($item['source_domain'] ?: 'Unknown') ?>
                            </small>
                            <small class="text-muted">
                                <?= date('M j, Y', strtotime($item['pubDate'])) ?>
                            </small>
                        </div>
                        <div class="mt-2">
                            <small class="text-muted">
                                <i class="bi bi-person me-1"></i>
                                <?= htmlspecialchars($item['author'] ?: 'Anonymous') ?>
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
        <nav class="mt-4">
            <ul class="pagination justify-content-center">
                <?php if ($page > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=results&p=<?= $page - 1 ?>&search=<?= urlencode($searchFilter) ?>&domain=<?= urlencode($domainFilter) ?>&date_from=<?= $dateFrom ?>&date_to=<?= $dateTo ?>">
                            <i class="bi bi-chevron-left"></i> Previous
                        </a>
                    </li>
                <?php endif; ?>

                <li class="page-item disabled">
                    <span class="page-link">
                        Page <?= $page ?> of <?= number_format($totalPages) ?>
                    </span>
                </li>

                <?php if ($page < $totalPages): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=results&p=<?= $page + 1 ?>&search=<?= urlencode($searchFilter) ?>&domain=<?= urlencode($domainFilter) ?>&date_from=<?= $dateFrom ?>&date_to=<?= $dateTo ?>">
                            Next <i class="bi bi-chevron-right"></i>
                        </a>
                    </li>
                <?php endif; ?>
            </ul>
        </nav>
    <?php endif; ?>
<?php endif; ?>

<script>
function exportAll(format) {
    const params = new URLSearchParams(window.location.search);
    params.set('format', format);

    NEXUS.api('export_results', Object.fromEntries(params)).then(r => {
        if (r.success) {
            NEXUS.toast('Export started. Check exports page.', 'success');
        } else {
            NEXUS.toast('Failed to start export', 'error');
        }
    });
}
</script>
