<?php
$crawler = new Crawler();
$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_source':
                $name = sanitize_input($_POST['name']);
                $url = sanitize_input($_POST['url']);
                $selector = sanitize_input($_POST['selector']);

                if ($crawler->addSource($name, $url, $selector)) {
                    $message = __('source_added_successfully') ?? 'Source added successfully';
                } else {
                    $error = __('source_add_failed') ?? 'Failed to add source';
                }
                break;

            case 'toggle_source':
                $id = (int)$_POST['id'];
                $active = (int)$_POST['active'];

                if ($crawler->toggleSource($id, $active)) {
                    $message = __('source_updated_successfully') ?? 'Source updated successfully';
                } else {
                    $error = __('source_update_failed') ?? 'Failed to update source';
                }
                break;

            case 'remove_source':
                $id = (int)$_POST['id'];

                if ($crawler->removeSource($id)) {
                    $message = __('source_removed_successfully') ?? 'Source removed successfully';
                } else {
                    $error = __('source_remove_failed') ?? 'Failed to remove source';
                }
                break;

            case 'run_crawl':
                if ($crawler->crawlSources()) {
                    $message = __('crawl_completed_successfully') ?? 'Crawling completed successfully';
                } else {
                    $error = __('crawl_failed') ?? 'Crawling failed';
                }
                break;
        }
    }
}

$sources = $crawler->getAllSources();
$crawlHistory = $crawler->getCrawlHistory(10);
$crawlStats = $crawler->getCrawlStats();
$settings = new Settings();
$crawlEnabled = $settings->get('auto_crawl_enabled', '0');
$crawlInterval = $settings->get('crawl_interval', '3600');
?>

<div class="row">
    <div class="col-lg-8">
        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle"></i> <?= htmlspecialchars($message) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-rss"></i> <?= __('crawl_sources') ?? 'Crawl Sources' ?>
                </h5>
            </div>
            <div class="card-body">
                <?php if (empty($sources)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-rss fa-4x text-muted mb-3"></i>
                        <h5 class="text-muted"><?= __('no_sources') ?? 'No crawl sources configured' ?></h5>
                        <p class="text-muted"><?= __('add_first_source') ?? 'Add your first crawl source to get started' ?></p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th><?= __('name') ?? 'Name' ?></th>
                                    <th><?= __('url') ?? 'URL' ?></th>
                                    <th><?= __('status') ?? 'Status' ?></th>
                                    <th><?= __('last_crawled') ?? 'Last Crawled' ?></th>
                                    <th width="150"><?= __('actions') ?? 'Actions' ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($sources as $source): ?>
                                    <tr>
                                        <td>
                                            <strong><?= htmlspecialchars($source['name']) ?></strong>
                                            <?php if ($source['selector']): ?>
                                                <br><small class="text-muted">Selector: <?= htmlspecialchars($source['selector']) ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <a href="<?= htmlspecialchars($source['url']) ?>" target="_blank" class="text-decoration-none">
                                                <?= htmlspecialchars(substr($source['url'], 0, 50)) ?><?= strlen($source['url']) > 50 ? '...' : '' ?>
                                            </a>
                                        </td>
                                        <td>
                                            <span class="badge <?= $source['is_active'] ? 'bg-success' : 'bg-secondary' ?>">
                                                <?= $source['is_active'] ? (__('active') ?? 'Active') : (__('inactive') ?? 'Inactive') ?>
                                            </span>
                                        </td>
                                        <td>
                                            <small class="text-muted">
                                                <?= $source['last_crawled'] ? date('M j, Y H:i', strtotime($source['last_crawled'])) : (__('never') ?? 'Never') ?>
                                            </small>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <form method="POST" class="d-inline">
                                                    <input type="hidden" name="action" value="toggle_source">
                                                    <input type="hidden" name="id" value="<?= $source['id'] ?>">
                                                    <input type="hidden" name="active" value="<?= $source['is_active'] ? 0 : 1 ?>">
                                                    <button type="submit" class="btn btn-outline-<?= $source['is_active'] ? 'warning' : 'success' ?>" title="<?= $source['is_active'] ? (__('deactivate') ?? 'Deactivate') : (__('activate') ?? 'Activate') ?>">
                                                        <i class="fas fa-<?= $source['is_active'] ? 'pause' : 'play' ?>"></i>
                                                    </button>
                                                </form>

                                                <form method="POST" class="d-inline" onsubmit="return confirm('<?= __('confirm_remove_source') ?? 'Are you sure you want to remove this source?' ?>')">
                                                    <input type="hidden" name="action" value="remove_source">
                                                    <input type="hidden" name="id" value="<?= $source['id'] ?>">
                                                    <button type="submit" class="btn btn-outline-danger" title="<?= __('remove') ?? 'Remove' ?>">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="card mt-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-plus"></i> <?= __('add_new_source') ?? 'Add New Source' ?>
                </h6>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="add_source">

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="name" class="form-label"><?= __('source_name') ?? 'Source Name' ?> <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="name" name="name" required placeholder="<?= __('source_name_placeholder') ?? 'e.g., Tech News' ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="url" class="form-label"><?= __('source_url') ?? 'Source URL' ?> <span class="text-danger">*</span></label>
                            <input type="url" class="form-control" id="url" name="url" required placeholder="https://example.com/rss">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="selector" class="form-label"><?= __('css_selector') ?? 'CSS Selector' ?> <small class="text-muted">(<?= __('optional') ?? 'Optional' ?>)</small></label>
                        <input type="text" class="form-control" id="selector" name="selector" placeholder="article, .post, .news-item">
                        <div class="form-text">
                            <?= __('css_selector_help') ?? 'CSS selector to target specific content elements. Leave empty for automatic detection.' ?>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-plus"></i> <?= __('add_source') ?? 'Add Source' ?>
                    </button>
                </form>
            </div>
        </div>

        <div class="card mt-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-history"></i> <?= __('crawl_history') ?? 'Crawl History' ?>
                </h6>
            </div>
            <div class="card-body">
                <?php if (empty($crawlHistory)): ?>
                    <div class="text-center py-3">
                        <i class="fas fa-history fa-2x text-muted mb-2"></i>
                        <p class="text-muted small"><?= __('no_crawl_history') ?? 'No crawl history yet' ?></p>
                    </div>
                <?php else: ?>
                    <div class="timeline">
                        <?php foreach ($crawlHistory as $history): ?>
                            <div class="timeline-item mb-3">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <div class="fw-semibold small"><?= htmlspecialchars($history['source_name'] ?: 'Unknown Source') ?></div>
                                        <div class="small text-muted">
                                            <?= date('M j, H:i', strtotime($history['started_at'])) ?>
                                        </div>
                                    </div>
                                    <span class="badge <?= $history['status'] === 'success' ? 'bg-success' : ($history['status'] === 'failed' ? 'bg-danger' : 'bg-warning') ?>">
                                        <?= ucfirst($history['status']) ?>
                                    </span>
                                </div>
                                <div class="small mt-1">
                                    <span class="text-info">
                                        <i class="fas fa-search"></i> <?= $history['articles_found'] ?? 0 ?> found
                                    </span>
                                    <?php if ($history['articles_created'] > 0): ?>
                                        <span class="text-success ms-2">
                                            <i class="fas fa-plus-circle"></i> <?= $history['articles_created'] ?> created
                                        </span>
                                    <?php endif; ?>
                                    <?php if ($history['articles_skipped'] > 0): ?>
                                        <span class="text-warning ms-2">
                                            <i class="fas fa-skip-forward"></i> <?= $history['articles_skipped'] ?> skipped
                                        </span>
                                    <?php endif; ?>
                                    <?php if ($history['execution_time']): ?>
                                        <span class="text-muted ms-2">
                                            <i class="fas fa-clock"></i> <?= $history['execution_time'] ?>ms
                                        </span>
                                    <?php endif; ?>
                                </div>
                                <?php if ($history['error_message']): ?>
                                    <div class="small text-danger mt-1">
                                        <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($history['error_message']) ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="text-center">
                        <small class="text-muted"><?= __('showing_recent') ?? 'Showing 10 most recent crawls' ?></small>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-chart-bar"></i> <?= __('crawl_statistics') ?? 'Crawl Statistics' ?>
                </h6>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6 mb-3">
                        <div class="h4 mb-1 text-primary"><?= $crawlStats['crawls_today'] ?? 0 ?></div>
                        <small class="text-muted"><?= __('crawls_today') ?? 'Crawls Today' ?></small>
                    </div>
                    <div class="col-6 mb-3">
                        <div class="h4 mb-1 text-success"><?= $crawlStats['articles_today'] ?? 0 ?></div>
                        <small class="text-muted"><?= __('articles_today') ?? 'Articles Today' ?></small>
                    </div>
                    <div class="col-6">
                        <div class="h4 mb-1 text-info"><?= $crawlStats['success_rate'] ?? 0 ?>%</div>
                        <small class="text-muted"><?= __('success_rate') ?? 'Success Rate (24h)' ?></small>
                    </div>
                    <div class="col-6">
                        <div class="h4 mb-1 text-warning"><?= $crawlStats['avg_execution_time'] ?? 0 ?>ms</div>
                        <small class="text-muted"><?= __('avg_time') ?? 'Avg Time' ?></small>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mt-3">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-cogs"></i> <?= __('crawler_settings') ?? 'Crawler Settings' ?>
                </h6>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label class="form-label"><?= __('auto_crawling') ?? 'Auto Crawling' ?></label>
                    <div>
                        <span class="badge <?= $crawlEnabled ? 'bg-success' : 'bg-secondary' ?>">
                            <?= $crawlEnabled ? (__('enabled') ?? 'Enabled') : (__('disabled') ?? 'Disabled') ?>
                        </span>
                    </div>
                    <small class="text-muted"><?= __('crawl_interval') ?? 'Crawl Interval' ?>: <?= round($crawlInterval / 3600, 1) ?> hours</small>
                </div>

                <form method="POST" class="mb-3">
                    <input type="hidden" name="action" value="run_crawl">
                    <button type="submit" class="btn btn-info w-100">
                        <i class="fas fa-sync"></i> <?= __('run_crawl_now') ?? 'Run Crawl Now' ?>
                    </button>
                </form>

                <div class="small text-muted">
                    <p><strong><?= __('note') ?? 'Note' ?>:</strong></p>
                    <ul class="mb-0">
                        <li><?= __('crawler_note_1') ?? 'Crawling may take several minutes' ?></li>
                        <li><?= __('crawler_note_2') ?? 'Duplicate articles are automatically filtered' ?></li>
                        <li><?= __('crawler_note_3') ?? 'Content is processed by AI for quality' ?></li>
                    </ul>
                </div>
            </div>
        </div>

        <div class="card mt-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-info-circle"></i> <?= __('how_to_use') ?? 'How to Use' ?>
                </h6>
            </div>
            <div class="card-body">
                <div class="small">
                    <p><strong><?= __('step') ?? 'Step' ?> 1:</strong> <?= __('crawler_step_1') ?? 'Add RSS feeds or website URLs as sources' ?></p>
                    <p><strong><?= __('step') ?? 'Step' ?> 2:</strong> <?= __('crawler_step_2') ?? 'Activate sources you want to crawl' ?></p>
                    <p><strong><?= __('step') ?? 'Step' ?> 3:</strong> <?= __('crawler_step_3') ?? 'Run manual crawl or enable auto-crawling' ?></p>
                    <p><strong><?= __('step') ?? 'Step' ?> 4:</strong> <?= __('crawler_step_4') ?? 'Review and publish crawled articles' ?></p>
                </div>
            </div>
        </div>
    </div>
</div>