<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';

$recentJobs = Db::listJobs(10);

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product Image Extractor HD</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="app-header">
    <div class="container">
        <div class="logo">
            <svg width="32" height="32" viewBox="0 0 32 32" fill="none"><rect width="32" height="32" rx="8" fill="#2563eb"/><path d="M8 22l6-8 4 5 3-3 5 6H8z" fill="white"/><circle cx="22" cy="11" r="3" fill="#fbbf24"/></svg>
            <span>Product Image Extractor <span class="badge">HD</span></span>
        </div>
        <nav class="header-nav">
            <a href="#single-section">Single URL</a>
            <a href="#batch-section">Batch Excel</a>
            <a href="#history-section">History</a>
        </nav>
    </div>
</header>

<main class="container">

    <!-- ── SINGLE URL ── -->
    <section id="single-section" class="hero-section">
        <h1>Extract Product Image URL</h1>
        <p>Paste a product page URL below — the tool visits the page and gives you the main image URL.</p>

        <div class="single-box">
            <div class="single-input-row">
                <input type="url"
                       id="single-url"
                       placeholder="https://your-shop.com/product/blue-shirt"
                       autocomplete="off"
                       spellcheck="false">
                <button id="single-btn" class="btn btn-primary">
                    <span id="single-btn-text">Extract Image URL</span>
                </button>
            </div>

            <div id="single-result" class="single-result hidden">
                <div id="single-result-inner"></div>
            </div>
        </div>
    </section>

    <!-- ── BATCH EXCEL ── -->
    <section id="batch-section" class="card">
        <h2>Batch Extraction — Excel File</h2>
        <p class="section-sub">Have many products? Upload an Excel or CSV file and process thousands of URLs at once.</p>

        <form id="upload-form" action="upload.php" method="POST" enctype="multipart/form-data">

            <div id="drop-zone" class="drop-zone">
                <div class="drop-zone-inner">
                    <svg width="40" height="40" viewBox="0 0 48 48" fill="none"><path d="M24 8L8 24h10v12h12V24h10L24 8z" fill="#2563eb" opacity=".7"/></svg>
                    <p><strong>Drag & drop your Excel file here</strong></p>
                    <p class="sub">or click to browse — .xlsx, .xls, .csv — max <?= MAX_UPLOAD_SIZE_MB ?>MB</p>
                </div>
                <input type="file" id="file-input" name="excel_file" accept=".xlsx,.xls,.csv" class="file-input-hidden">
            </div>
            <div id="file-preview" class="file-preview hidden"></div>

            <details class="settings-panel">
                <summary>⚙️ Advanced Settings</summary>
                <div class="settings-grid">
                    <div class="field">
                        <label for="url_column">URL Column</label>
                        <input type="text" id="url_column" name="url_column" value="A" placeholder="A, B, C..." maxlength="3">
                        <small>Leave blank to auto-detect</small>
                    </div>
                    <div class="field">
                        <label for="max_rows">Max Rows</label>
                        <input type="number" id="max_rows" name="max_rows" value="0" min="0" max="10000">
                        <small>0 = no limit</small>
                    </div>
                    <div class="field">
                        <label for="timeout_s">Timeout (seconds)</label>
                        <input type="number" id="timeout_s" name="timeout_s" value="<?= DEFAULT_TIMEOUT ?>" min="5" max="120">
                    </div>
                    <div class="field">
                        <label for="delay_ms">Delay between requests (ms)</label>
                        <input type="number" id="delay_ms" name="delay_ms" value="<?= DEFAULT_DELAY_MS ?>" min="0" max="10000">
                        <small>Higher = more polite crawling</small>
                    </div>
                    <div class="field">
                        <label for="max_retries">Max Retries</label>
                        <input type="number" id="max_retries" name="max_retries" value="<?= DEFAULT_MAX_RETRIES ?>" min="1" max="10">
                    </div>
                    <div class="field field-wide">
                        <label for="user_agent">Custom User-Agent</label>
                        <input type="text" id="user_agent" name="user_agent" placeholder="Leave blank for default Chrome UA">
                    </div>
                </div>
            </details>

            <div class="form-actions">
                <button type="submit" class="btn btn-primary" id="submit-btn" disabled>
                    🚀 Start Batch Extraction
                </button>
                <span class="upload-hint" id="upload-hint">Select a file to enable this button</span>
            </div>
        </form>
    </section>

    <!-- ── PROGRESS ── -->
    <section id="progress-section" class="card hidden">
        <h2>Processing Job <span id="progress-job-id"></span></h2>
        <div class="progress-stats">
            <div class="stat-box"><div class="stat-value" id="stat-total">—</div><div class="stat-label">Total</div></div>
            <div class="stat-box success"><div class="stat-value" id="stat-success">0</div><div class="stat-label">Success</div></div>
            <div class="stat-box error"><div class="stat-value" id="stat-failed">0</div><div class="stat-label">Failed</div></div>
            <div class="stat-box"><div class="stat-value" id="stat-pct">0%</div><div class="stat-label">Progress</div></div>
            <div class="stat-box"><div class="stat-value" id="stat-eta">—</div><div class="stat-label">Est. Remaining</div></div>
        </div>
        <div class="progress-bar-wrap"><div class="progress-bar" id="progress-bar" style="width:0%"></div></div>
        <div class="progress-status" id="progress-status">Initializing...</div>
        <div class="progress-actions">
            <button class="btn btn-danger" id="stop-btn">⏹ Stop Job</button>
            <a class="btn btn-secondary hidden" id="download-btn">⬇ Download Results</a>
        </div>
        <details class="log-panel">
            <summary>📋 Live Logs</summary>
            <div id="log-output" class="log-output"></div>
        </details>
    </section>

    <!-- ── HISTORY ── -->
    <section id="history-section" class="card">
        <h2>Batch Job History</h2>
        <?php if (empty($recentJobs)): ?>
            <p class="empty-state">No batch jobs yet.</p>
        <?php else: ?>
        <div class="table-wrap">
            <table class="jobs-table">
                <thead><tr><th>#</th><th>File</th><th>Status</th><th>Progress</th><th>Created</th><th>Actions</th></tr></thead>
                <tbody>
                <?php foreach ($recentJobs as $job): ?>
                <tr>
                    <td><?= (int)$job['id'] ?></td>
                    <td class="filename"><?= htmlspecialchars($job['original_name']) ?></td>
                    <td><span class="status-badge status-<?= htmlspecialchars($job['status']) ?>"><?= ucfirst(htmlspecialchars($job['status'])) ?></span></td>
                    <td>
                        <?php if ($job['total_rows'] > 0): ?>
                            <?= (int)$job['processed_rows'] ?> / <?= (int)$job['total_rows'] ?>
                            <span class="success-count">(✓ <?= (int)$job['success_rows'] ?>)</span>
                        <?php else: ?>—<?php endif ?>
                    </td>
                    <td><?= htmlspecialchars(substr($job['created_at'], 0, 16)) ?></td>
                    <td>
                        <?php if ($job['status'] === 'done'): ?>
                            <a href="download.php?token=<?= urlencode($job['token']) ?>" class="btn btn-sm">⬇ Download</a>
                        <?php elseif (in_array($job['status'], ['running','pending'])): ?>
                            <button class="btn btn-sm btn-primary" onclick="resumeJob('<?= htmlspecialchars($job['token']) ?>')">👁 Watch</button>
                        <?php endif ?>
                    </td>
                </tr>
                <?php endforeach ?>
                </tbody>
            </table>
        </div>
        <?php endif ?>
    </section>

</main>

<footer class="app-footer">
    <div class="container">
        <p>Product Image Extractor HD v<?= APP_VERSION ?> — PHP <?= PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION ?> + SQLite + PhpSpreadsheet</p>
    </div>
</footer>

<script src="script.js"></script>
</body>
</html>
