<?php
/**
 * FLOWB0T NEXUS - New Job Page
 * Form for creating new crawl jobs
 */
?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-0">Create New Crawl Job</h2>
        <small class="text-muted">Configure and start a new web crawling job</small>
    </div>
    <a href="?page=jobs" class="btn btn-outline-light">
        <i class="bi bi-arrow-left me-2"></i>Back to Jobs
    </a>
</div>

<form id="newJobForm" method="POST" action="?page=new-job&action=create">
    <div class="row">
        <!-- Main Form Column -->
        <div class="col-lg-8">
            <!-- Job Information -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="bi bi-info-circle me-2"></i>Job Information</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="jobName" class="form-label">Job Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="jobName" name="name" required
                               placeholder="e.g., News Crawler 2024">
                        <div class="form-text">Give your job a memorable name for easy identification</div>
                    </div>
                    <div class="mb-3">
                        <label for="jobDescription" class="form-label">Description</label>
                        <textarea class="form-control" id="jobDescription" name="description" rows="2"
                                  placeholder="Optional description of what this crawl is for"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="jobType" class="form-label">Job Type</label>
                        <select class="form-select" id="jobType" name="job_type">
                            <option value="search" selected>Search-based (use search terms)</option>
                            <option value="domain">Domain-focused (target specific sites)</option>
                            <option value="direct">Direct URLs (crawl specific pages)</option>
                            <option value="mixed">Mixed (combination)</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- Search Terms -->
            <div class="card mb-4" id="searchTermsCard">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="bi bi-search me-2"></i>Search Terms / Keywords</h5>
                    <span class="badge bg-primary" id="termCount">0 terms</span>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="searchTerms" class="form-label">Enter search terms (one per line)</label>
                        <textarea class="form-control" id="searchTerms" name="search_terms" rows="8"
                                  placeholder="climate change news 2024
renewable energy
electric vehicles
technology trends"></textarea>
                        <div class="form-text">
                            <i class="bi bi-info-circle me-1"></i>
                            Each term will search across Bing for web pages, images, and videos
                        </div>
                    </div>
                    <div class="d-flex gap-2">
                        <label class="btn btn-outline-secondary">
                            <i class="bi bi-upload me-2"></i>Upload TXT File
                            <input type="file" id="termsFile" accept=".txt" hidden>
                        </label>
                        <button type="button" class="btn btn-outline-secondary" onclick="clearTerms()">
                            <i class="bi bi-trash me-2"></i>Clear
                        </button>
                    </div>
                </div>
            </div>

            <!-- Target Domains -->
            <div class="card mb-4" id="targetDomainsCard">
                <div class="card-header">
                    <h5 class="mb-0"><i class="bi bi-globe me-2"></i>Target Domains (Optional)</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="targetDomains" class="form-label">Specific domains to crawl</label>
                        <textarea class="form-control" id="targetDomains" name="target_domains" rows="4"
                                  placeholder="nypost.com
cnn.com
bbc.co.uk"></textarea>
                        <div class="form-text">
                            <i class="bi bi-info-circle me-1"></i>
                            Leave empty to crawl the entire web. Add domains to focus crawl.
                        </div>
                    </div>
                </div>
            </div>

            <!-- Direct URLs -->
            <div class="card mb-4" id="directUrlsCard" style="display: none;">
                <div class="card-header">
                    <h5 class="mb-0"><i class="bi bi-link-45deg me-2"></i>Direct URLs</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="directUrls" class="form-label">URLs to crawl directly</label>
                        <textarea class="form-control" id="directUrls" name="direct_urls" rows="4"
                                  placeholder="https://example.com/article1
https://example.com/article2"></textarea>
                        <div class="form-text">
                            <i class="bi bi-info-circle me-1"></i>
                            Enter full URLs to crawl directly (one per line)
                        </div>
                    </div>
                </div>
            </div>

            <!-- Filter Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="bi bi-funnel me-2"></i>Filter Settings</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="relevanceThreshold" class="form-label">
                                Relevance Threshold
                                <i class="bi bi-question-circle tooltip-icon" data-bs-toggle="tooltip"
                                   title="Minimum relevance score (0=any, 10=exact match)"></i>
                            </label>
                            <input type="number" class="form-control" id="relevanceThreshold"
                                   name="relevance_threshold" value="2" min="0" max="10">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="minContentLength" class="form-label">
                                Min Content Length
                                <i class="bi bi-question-circle tooltip-icon" data-bs-toggle="tooltip"
                                   title="Minimum content length in characters"></i>
                            </label>
                            <input type="number" class="form-control" id="minContentLength"
                                   name="min_content_length" value="100" min="0">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Languages</label>
                        <div class="d-flex flex-wrap gap-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="langEN" name="languages[]" value="en" checked>
                                <label class="form-check-label" for="langEN">English</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="langPT" name="languages[]" value="pt" checked>
                                <label class="form-check-label" for="langPT">Portuguese</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="langES" name="languages[]" value="es">
                                <label class="form-check-label" for="langES">Spanish</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="langFR" name="languages[]" value="fr">
                                <label class="form-check-label" for="langFR">French</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="langDE" name="languages[]" value="de">
                                <label class="form-check-label" for="langDE">German</label>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="blockedDomains" class="form-label">
                            Blocked Domains (Blacklist)
                            <i class="bi bi-question-circle tooltip-icon" data-bs-toggle="tooltip"
                               title="Domains to exclude from crawling"></i>
                        </label>
                        <input type="text" class="form-control" id="blockedDomains" name="blocked_domains"
                               value="facebook.com, instagram.com, twitter.com, pinterest.com"
                               placeholder="facebook.com, twitter.com">
                    </div>
                </div>
            </div>
        </div>

        <!-- Settings Sidebar -->
        <div class="col-lg-4">
            <!-- Crawler Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="bi bi-gear me-2"></i>Crawler Settings</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="maxDepth" class="form-label">
                            Max Depth
                            <i class="bi bi-question-circle tooltip-icon" data-bs-toggle="tooltip"
                               title="How deep to follow links (1-10)"></i>
                        </label>
                        <input type="number" class="form-control" id="maxDepth" name="max_depth"
                               value="3" min="1" max="10">
                    </div>
                    <div class="mb-3">
                        <label for="maxPages" class="form-label">
                            Max Pages
                            <i class="bi bi-question-circle tooltip-icon" data-bs-toggle="tooltip"
                               title="Maximum pages to crawl per job"></i>
                        </label>
                        <input type="number" class="form-control" id="maxPages" name="max_pages"
                               value="10000" min="1" max="1000000">
                    </div>
                    <div class="mb-3">
                        <label for="maxConcurrent" class="form-label">
                            Concurrent Connections
                            <i class="bi bi-question-circle tooltip-icon" data-bs-toggle="tooltip"
                               title="Simultaneous HTTP connections (1-500)"></i>
                        </label>
                        <input type="number" class="form-control" id="maxConcurrent" name="max_concurrent"
                               value="100" min="1" max="500">
                    </div>
                    <div class="mb-3">
                        <label for="requestTimeout" class="form-label">
                            Request Timeout (seconds)
                            <i class="bi bi-question-circle tooltip-icon" data-bs-toggle="tooltip"
                               title="Seconds to wait per request"></i>
                        </label>
                        <input type="number" class="form-control" id="requestTimeout" name="request_timeout"
                               value="10" min="1" max="60">
                    </div>
                    <div class="mb-3">
                        <label for="delayBetween" class="form-label">
                            Delay Between (seconds)
                            <i class="bi bi-question-circle tooltip-icon" data-bs-toggle="tooltip"
                               title="Delay between requests for politeness"></i>
                        </label>
                        <input type="number" class="form-control" id="delayBetween" name="delay_between"
                               value="0.5" min="0" max="10" step="0.1">
                    </div>
                </div>
            </div>

            <!-- Search Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="bi bi-search me-2"></i>Search Settings</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="searchProvider" class="form-label">Search Provider</label>
                        <select class="form-select" id="searchProvider" name="search_provider">
                            <option value="bing" selected>Bing</option>
                            <option value="google" disabled>Google (coming soon)</option>
                            <option value="duckduckgo" disabled>DuckDuckGo (coming soon)</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="searchPages" class="form-label">
                            Pages per Term
                            <i class="bi bi-question-circle tooltip-icon" data-bs-toggle="tooltip"
                               title="Search result pages to fetch per term (1-100)"></i>
                        </label>
                        <input type="number" class="form-control" id="searchPages" name="search_pages"
                               value="10" min="1" max="100">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Search Types</label>
                        <div class="d-flex flex-wrap gap-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="typeWeb" name="search_types[]" value="web" checked>
                                <label class="form-check-label" for="typeWeb">Web</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="typeImages" name="search_types[]" value="images" checked>
                                <label class="form-check-label" for="typeImages">Images</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="typeVideos" name="search_types[]" value="videos" checked>
                                <label class="form-check-label" for="typeVideos">Videos</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Import Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="bi bi-database me-2"></i>Import Settings</h5>
                </div>
                <div class="card-body">
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="autoImport" name="auto_import" checked>
                        <label class="form-check-label" for="autoImport">
                            Auto-import to database
                        </label>
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="importPinfeeds" name="import_to_pinfeeds" checked>
                        <label class="form-check-label" for="importPinfeeds">
                            Import to pinfeeds table
                        </label>
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="createUsers" name="create_users" checked>
                        <label class="form-check-label" for="createUsers">
                            Create user accounts for authors
                        </label>
                    </div>
                    <div class="mb-3">
                        <label for="dedupeBy" class="form-label">Deduplication</label>
                        <select class="form-select" id="dedupeBy" name="dedupe_by">
                            <option value="url" selected>By URL</option>
                            <option value="title">By Title</option>
                            <option value="content_hash">By Content Hash</option>
                            <option value="all">All methods</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="d-grid gap-2">
                <button type="submit" class="btn btn-primary btn-lg">
                    <i class="bi bi-play-circle me-2"></i>Start Crawl Job
                </button>
                <button type="button" class="btn btn-outline-secondary" onclick="saveDraft()">
                    <i class="bi bi-save me-2"></i>Save as Draft
                </button>
                <a href="?page=jobs" class="btn btn-outline-light">
                    <i class="bi bi-x-circle me-2"></i>Cancel
                </a>
            </div>

            <!-- Estimated Stats -->
            <div class="card mt-4 bg-transparent border-dashed">
                <div class="card-body text-center">
                    <h6 class="text-muted mb-3">Estimated Statistics</h6>
                    <div class="row text-center">
                        <div class="col-6">
                            <div class="display-6" id="estUrls">~0</div>
                            <small class="text-muted">Est. URLs</small>
                        </div>
                        <div class="col-6">
                            <div class="display-6" id="estTime">~0h</div>
                            <small class="text-muted">Est. Time</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

<script>
// Count terms and update UI
document.getElementById('searchTerms').addEventListener('input', function() {
    const terms = this.value.split('\n').filter(t => t.trim());
    document.getElementById('termCount').textContent = terms.length + ' terms';
    updateEstimates();
});

// File upload handler
document.getElementById('termsFile').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('searchTerms').value = e.target.result;
            document.getElementById('searchTerms').dispatchEvent(new Event('input'));
        };
        reader.readAsText(file);
    }
});

// Clear terms
function clearTerms() {
    document.getElementById('searchTerms').value = '';
    document.getElementById('searchTerms').dispatchEvent(new Event('input'));
}

// Job type change handler
document.getElementById('jobType').addEventListener('change', function() {
    const searchCard = document.getElementById('searchTermsCard');
    const domainCard = document.getElementById('targetDomainsCard');
    const urlsCard = document.getElementById('directUrlsCard');

    searchCard.style.display = 'block';
    domainCard.style.display = 'block';
    urlsCard.style.display = 'none';

    switch(this.value) {
        case 'domain':
            searchCard.style.display = 'none';
            break;
        case 'direct':
            searchCard.style.display = 'none';
            domainCard.style.display = 'none';
            urlsCard.style.display = 'block';
            break;
    }
});

// Update estimates
function updateEstimates() {
    const terms = document.getElementById('searchTerms').value.split('\n').filter(t => t.trim()).length;
    const pages = parseInt(document.getElementById('searchPages').value) || 10;
    const estUrls = terms * pages * 10; // ~10 results per page

    document.getElementById('estUrls').textContent = '~' + NEXUS.formatNumber(estUrls);

    const urlsPerSec = 50; // Conservative estimate
    const seconds = estUrls / urlsPerSec;
    if (seconds < 3600) {
        document.getElementById('estTime').textContent = '~' + Math.ceil(seconds / 60) + 'm';
    } else {
        document.getElementById('estTime').textContent = '~' + (seconds / 3600).toFixed(1) + 'h';
    }
}

// Save draft
function saveDraft() {
    NEXUS.toast('Draft saving coming soon', 'info');
}

// Initialize tooltips
document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => {
    new bootstrap.Tooltip(el);
});

// Initial estimate
updateEstimates();
</script>
