<?php
/**
 * FLOWB0T NEXUS - Export Manager
 * Manage and download data exports
 */

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

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

// Get exports
$exports = [];
try {
    $stmt = $pdo->query("
        SELECT e.*, j.name as job_name
        FROM nexus_exports e
        LEFT JOIN nexus_jobs j ON e.job_id = j.id
        ORDER BY e.created_at DESC
        LIMIT 50
    ");
    $exports = $stmt->fetchAll();
} catch (Exception $e) {
    // Table might not exist
}

// Get totals
$totalPinfeeds = 0;
$totalUsers = 0;
$totalDomains = 0;
try {
    $stmt = $pdo->query("SELECT COUNT(*) FROM pinfeeds");
    $totalPinfeeds = (int) $stmt->fetchColumn();

    $stmt = $pdo->query("SELECT COUNT(*) FROM user_myhashtag");
    $totalUsers = (int) $stmt->fetchColumn();

    $stmt = $pdo->query("SELECT COUNT(*) FROM feed_data");
    $totalDomains = (int) $stmt->fetchColumn();
} catch (Exception $e) {}
?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-0">Export Manager</h2>
        <small class="text-muted">Export crawled data in various formats</small>
    </div>
</div>

<!-- Quick Export Cards -->
<div class="row g-4 mb-4">
    <div class="col-md-4">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="bi bi-database me-2 text-primary"></i>Pinfeeds Data
                </h5>
                <p class="text-muted"><?= number_format($totalPinfeeds) ?> records</p>
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-success btn-sm" onclick="quickExport('pinfeeds', 'csv')">
                        <i class="bi bi-file-earmark-spreadsheet me-1"></i>CSV
                    </button>
                    <button class="btn btn-outline-info btn-sm" onclick="quickExport('pinfeeds', 'json')">
                        <i class="bi bi-file-earmark-code me-1"></i>JSON
                    </button>
                    <button class="btn btn-outline-warning btn-sm" onclick="quickExport('pinfeeds', 'sql')">
                        <i class="bi bi-file-earmark-text me-1"></i>SQL
                    </button>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="bi bi-people me-2 text-success"></i>Users/Authors
                </h5>
                <p class="text-muted"><?= number_format($totalUsers) ?> users</p>
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-success btn-sm" onclick="quickExport('users', 'csv')">
                        <i class="bi bi-file-earmark-spreadsheet me-1"></i>CSV
                    </button>
                    <button class="btn btn-outline-info btn-sm" onclick="quickExport('users', 'json')">
                        <i class="bi bi-file-earmark-code me-1"></i>JSON
                    </button>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="bi bi-globe me-2 text-warning"></i>Domains/Feed Data
                </h5>
                <p class="text-muted"><?= number_format($totalDomains) ?> domains</p>
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-success btn-sm" onclick="quickExport('domains', 'csv')">
                        <i class="bi bi-file-earmark-spreadsheet me-1"></i>CSV
                    </button>
                    <button class="btn btn-outline-info btn-sm" onclick="quickExport('domains', 'json')">
                        <i class="bi bi-file-earmark-code me-1"></i>JSON
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Custom Export -->
<div class="card mb-4">
    <div class="card-header">
        <h5 class="mb-0"><i class="bi bi-sliders me-2"></i>Custom Export</h5>
    </div>
    <div class="card-body">
        <form id="customExportForm" class="row g-3">
            <div class="col-md-3">
                <label class="form-label">Data Source</label>
                <select name="source" class="form-select">
                    <option value="pinfeeds">Pinfeeds</option>
                    <option value="users">Users</option>
                    <option value="domains">Domains</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Format</label>
                <select name="format" class="form-select">
                    <option value="csv">CSV</option>
                    <option value="json">JSON</option>
                    <option value="sql">SQL</option>
                    <option value="xml">XML</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Limit</label>
                <select name="limit" class="form-select">
                    <option value="1000">1,000</option>
                    <option value="10000">10,000</option>
                    <option value="50000">50,000</option>
                    <option value="100000">100,000</option>
                    <option value="0">All Records</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Date From</label>
                <input type="date" name="date_from" class="form-control">
            </div>
            <div class="col-md-2">
                <label class="form-label">Date To</label>
                <input type="date" name="date_to" class="form-control">
            </div>
            <div class="col-md-1 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="bi bi-download"></i>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Export History -->
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-clock-history me-2"></i>Export History</h5>
        <button class="btn btn-sm btn-outline-danger" onclick="clearOldExports()">
            <i class="bi bi-trash me-1"></i>Clear Old
        </button>
    </div>
    <div class="card-body p-0">
        <?php if (empty($exports)): ?>
            <div class="text-center py-5 text-muted">
                <i class="bi bi-inbox display-4"></i>
                <p class="mt-3">No exports yet</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Export</th>
                            <th>Format</th>
                            <th>Records</th>
                            <th>Size</th>
                            <th>Status</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($exports as $export): ?>
                            <tr>
                                <td>
                                    <?php if ($export['job_name']): ?>
                                        <strong><?= htmlspecialchars($export['job_name']) ?></strong>
                                        <br><small class="text-muted">Job Export</small>
                                    <?php else: ?>
                                        <strong><?= ucfirst($export['export_scope']) ?> Export</strong>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge bg-secondary"><?= strtoupper($export['export_type']) ?></span>
                                </td>
                                <td><?= number_format($export['total_records']) ?></td>
                                <td>
                                    <?php if ($export['file_size']): ?>
                                        <?= number_format($export['file_size'] / 1024 / 1024, 2) ?> MB
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php
                                    $statusClass = [
                                        'completed' => 'badge-completed',
                                        'processing' => 'badge-running',
                                        'pending' => 'badge-paused',
                                        'failed' => 'badge-failed'
                                    ][$export['status']] ?? 'bg-secondary';
                                    ?>
                                    <span class="badge <?= $statusClass ?>">
                                        <?php if ($export['status'] === 'processing'): ?>
                                            <i class="bi bi-circle-fill pulse me-1" style="font-size: 0.5rem;"></i>
                                        <?php endif; ?>
                                        <?= ucfirst($export['status']) ?>
                                    </span>
                                    <?php if ($export['status'] === 'processing'): ?>
                                        <br><small><?= number_format($export['progress_percent'], 1) ?>%</small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <small><?= date('M j, Y H:i', strtotime($export['created_at'])) ?></small>
                                </td>
                                <td>
                                    <?php if ($export['status'] === 'completed' && $export['file_path']): ?>
                                        <a href="<?= htmlspecialchars($export['file_path']) ?>" class="btn btn-sm btn-success" download>
                                            <i class="bi bi-download"></i>
                                        </a>
                                    <?php endif; ?>
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteExport(<?= $export['id'] ?>)">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
function quickExport(source, format) {
    NEXUS.api('create_export', {source: source, format: format}).then(r => {
        if (r.success) {
            NEXUS.toast('Export started', 'success');
            setTimeout(() => location.reload(), 2000);
        } else {
            NEXUS.toast('Export failed: ' + (r.error || 'Unknown error'), 'error');
        }
    });
}

document.getElementById('customExportForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const data = Object.fromEntries(formData);

    NEXUS.api('create_export', data).then(r => {
        if (r.success) {
            NEXUS.toast('Export started', 'success');
            setTimeout(() => location.reload(), 2000);
        } else {
            NEXUS.toast('Export failed', 'error');
        }
    });
});

function deleteExport(id) {
    if (confirm('Delete this export?')) {
        NEXUS.api('delete_export', {id: id}).then(r => {
            if (r.success) location.reload();
            else NEXUS.toast('Failed to delete', 'error');
        });
    }
}

function clearOldExports() {
    if (confirm('Delete all exports older than 7 days?')) {
        NEXUS.api('clear_old_exports', {}).then(r => {
            if (r.success) {
                NEXUS.toast('Old exports cleared', 'success');
                location.reload();
            }
        });
    }
}
</script>
