<?php
/**
 * ============================================
 * FLOWBOT DCI v3.0 - PROCESS HISTORY
 * ============================================
 * View all past processes with filters and pagination
 */
declare(strict_types=1);

// Variables from controller (with safe defaults)
$baseUrl = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
$pageTitle = 'Process History';
$currentPage = 'history';

// History data with safe defaults
$history = $history ?? ['items' => [], 'total' => 0, 'page' => 1, 'limit' => 20, 'pages' => 1];
$items = $history['items'] ?? [];
$total = $history['total'] ?? 0;
$page = $history['page'] ?? 1;
$limit = $history['limit'] ?? 20;
$totalPages = $history['pages'] ?? max(1, (int)ceil($total / $limit));

// Current filters
$filterStatus = $_GET['status'] ?? '';
$filterDateFrom = $_GET['date_from'] ?? '';
$filterDateTo = $_GET['date_to'] ?? '';
$filterSearch = $_GET['search'] ?? '';

// Sorting
$sortBy = $_GET['sort'] ?? 'created_at';
$sortOrder = $_GET['order'] ?? 'desc';
$validSortColumns = ['id', 'total_urls', 'status', 'mode', 'created_at'];
if (!in_array($sortBy, $validSortColumns)) $sortBy = 'created_at';
if (!in_array($sortOrder, ['asc', 'desc'])) $sortOrder = 'desc';

$hasFilters = !empty($filterStatus) || !empty($filterDateFrom) || !empty($filterDateTo) || !empty($filterSearch);

// Statistics
$completedCount = 0;
$failedCount = 0;
$runningCount = 0;
$totalUrls = 0;
foreach ($items as $item) {
    $status = $item['status'] ?? '';
    if ($status === 'completed') $completedCount++;
    elseif ($status === 'failed' || $status === 'cancelled') $failedCount++;
    elseif ($status === 'running' || $status === 'pending') $runningCount++;
    $totalUrls += $item['total_urls'] ?? 0;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($pageTitle) ?> - Flowb0t DCI v3.0</title>
    <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><rect width='32' height='32' rx='8' fill='%233B82F6'/><path d='M8 10h16M8 16h12M8 22h8' stroke='white' stroke-width='2.5' stroke-linecap='round'/></svg>">
    <link rel="stylesheet" href="<?= $baseUrl ?>/assets/css/v3-styles.css?v=<?= time() ?>">
</head>
<body>
    <!-- Navigation -->
    <nav class="main-nav">
        <div class="nav-container">
            <div class="nav-brand">
                <a href="<?= $baseUrl ?>/" class="brand-link">
                    <span class="brand-logo">
                        <svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <rect width="32" height="32" rx="8" fill="url(#brand-gradient)"/>
                            <path d="M8 10h16M8 16h12M8 22h8" stroke="white" stroke-width="2.5" stroke-linecap="round"/>
                            <circle cx="24" cy="22" r="4" fill="#10B981"/>
                            <defs>
                                <linearGradient id="brand-gradient" x1="0" y1="0" x2="32" y2="32">
                                    <stop stop-color="#3B82F6"/>
                                    <stop offset="1" stop-color="#8B5CF6"/>
                                </linearGradient>
                            </defs>
                        </svg>
                    </span>
                    <span class="brand-text">Flowb0t DCI</span>
                    <span class="brand-version">v3.0</span>
                </a>
            </div>

            <div class="nav-main">
                <a href="<?= $baseUrl ?>/" class="nav-link">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <rect x="3" y="3" width="7" height="7" rx="1"/>
                        <rect x="14" y="3" width="7" height="7" rx="1"/>
                        <rect x="3" y="14" width="7" height="7" rx="1"/>
                        <rect x="14" y="14" width="7" height="7" rx="1"/>
                    </svg>
                    <span>Dashboard</span>
                </a>
                <a href="<?= $baseUrl ?>/new" class="nav-link">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="9"/>
                        <line x1="12" y1="8" x2="12" y2="16"/>
                        <line x1="8" y1="12" x2="16" y2="12"/>
                    </svg>
                    <span>New Process</span>
                </a>
                <a href="/flowb0t.com/v2/views/crawler-ultimate.php" class="nav-link">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="11" cy="11" r="8"/>
                        <line x1="21" y1="21" x2="16.65" y2="16.65"/>
                    </svg>
                    <span>Crawler</span>
                </a>
                <a href="<?= $baseUrl ?>/history" class="nav-link active">
                    <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="9"/>
                        <polyline points="12,7 12,12 16,14"/>
                    </svg>
                    <span>History</span>
                </a>
            </div>

            <div class="nav-right">
                <a href="<?= $baseUrl ?>/new" class="btn btn-primary btn-sm">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                        <line x1="12" y1="5" x2="12" y2="19"/>
                        <line x1="5" y1="12" x2="19" y2="12"/>
                    </svg>
                    New
                </a>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <main class="main-content">
        <!-- Page Header -->
        <div class="page-header">
            <div class="page-header-content">
                <h1 class="page-title">
                    <svg class="page-title-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="10"/>
                        <polyline points="12,6 12,12 16,14"/>
                    </svg>
                    Process History
                    <?php if ($runningCount > 0): ?>
                    <span class="live-indicator" id="liveIndicator" title="Auto-updating every 3 seconds">
                        <span class="live-dot"></span>
                        LIVE
                    </span>
                    <?php endif; ?>
                </h1>
                <p class="page-subtitle">View and manage all your URL processing operations</p>
            </div>
            <div class="page-header-actions">
                <a href="<?= $baseUrl ?>/new" class="btn btn-primary">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18">
                        <line x1="12" y1="5" x2="12" y2="19"/>
                        <line x1="5" y1="12" x2="19" y2="12"/>
                    </svg>
                    New Process
                </a>
            </div>
        </div>

        <!-- Quick Stats -->
        <div class="history-stats">
            <div class="stat-mini">
                <span class="stat-mini-value"><?= number_format($total) ?></span>
                <span class="stat-mini-label">Total Processes</span>
            </div>
            <div class="stat-mini stat-success">
                <span class="stat-mini-value"><?= number_format($completedCount) ?></span>
                <span class="stat-mini-label">Completed</span>
            </div>
            <div class="stat-mini stat-error">
                <span class="stat-mini-value"><?= number_format($failedCount) ?></span>
                <span class="stat-mini-label">Failed</span>
            </div>
            <div class="stat-mini stat-info">
                <span class="stat-mini-value"><?= number_format($totalUrls) ?></span>
                <span class="stat-mini-label">URLs Processed</span>
            </div>
        </div>

        <!-- Filters Section -->
        <div class="section filters-section">
            <form method="GET" action="<?= $baseUrl ?>/history" class="filters-form">
                <!-- Hidden fields for sorting -->
                <input type="hidden" name="sort" value="<?= htmlspecialchars($sortBy) ?>">
                <input type="hidden" name="order" value="<?= htmlspecialchars($sortOrder) ?>">

                <div class="filters-row">
                    <div class="filter-group filter-group-search">
                        <label class="filter-label">Search</label>
                        <div class="search-input-wrapper">
                            <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                                <circle cx="11" cy="11" r="8"/>
                                <line x1="21" y1="21" x2="16.65" y2="16.65"/>
                            </svg>
                            <input type="text" name="search" value="<?= htmlspecialchars($filterSearch) ?>"
                                   class="filter-input search-input" placeholder="Search by ID...">
                        </div>
                    </div>
                    <div class="filter-group">
                        <label class="filter-label">Status</label>
                        <select name="status" class="filter-select">
                            <option value="">All Status</option>
                            <option value="completed" <?= $filterStatus === 'completed' ? 'selected' : '' ?>>Completed</option>
                            <option value="running" <?= $filterStatus === 'running' ? 'selected' : '' ?>>Running</option>
                            <option value="pending" <?= $filterStatus === 'pending' ? 'selected' : '' ?>>Pending</option>
                            <option value="paused" <?= $filterStatus === 'paused' ? 'selected' : '' ?>>Paused</option>
                            <option value="failed" <?= $filterStatus === 'failed' ? 'selected' : '' ?>>Failed</option>
                            <option value="cancelled" <?= $filterStatus === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label class="filter-label">From Date</label>
                        <input type="date" name="date_from" value="<?= htmlspecialchars($filterDateFrom) ?>" class="filter-input">
                    </div>
                    <div class="filter-group">
                        <label class="filter-label">To Date</label>
                        <input type="date" name="date_to" value="<?= htmlspecialchars($filterDateTo) ?>" class="filter-input">
                    </div>
                    <div class="filter-actions">
                        <button type="submit" class="btn btn-primary btn-sm">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                                <circle cx="11" cy="11" r="8"/>
                                <line x1="21" y1="21" x2="16.65" y2="16.65"/>
                            </svg>
                            Filter
                        </button>
                        <?php if ($hasFilters): ?>
                        <a href="<?= $baseUrl ?>/history" class="btn btn-ghost btn-sm">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                                <line x1="18" y1="6" x2="6" y2="18"/>
                                <line x1="6" y1="6" x2="18" y2="18"/>
                            </svg>
                            Clear
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
            </form>
        </div>

        <!-- Bulk Actions Bar -->
        <div class="bulk-actions-bar" id="bulkActionsBar" style="display: none;">
            <div class="bulk-actions-content">
                <div class="bulk-selection-info">
                    <span class="bulk-checkbox-icon">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18">
                            <polyline points="9,11 12,14 22,4"/>
                            <path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/>
                        </svg>
                    </span>
                    <span class="bulk-count"><strong id="selectedCount">0</strong> processes selected</span>
                    <button type="button" class="btn btn-ghost btn-xs" id="clearSelectionBtn">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
                            <line x1="18" y1="6" x2="6" y2="18"/>
                            <line x1="6" y1="6" x2="18" y2="18"/>
                        </svg>
                        Clear
                    </button>
                </div>
                <div class="bulk-actions-buttons">
                    <button type="button" class="btn btn-primary btn-sm" id="bulkReprocessBtn">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                            <polyline points="23,4 23,10 17,10"/>
                            <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
                        </svg>
                        Reprocess
                    </button>
                    <button type="button" class="btn btn-ghost btn-sm" id="bulkExportBtn">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                            <polyline points="7,10 12,15 17,10"/>
                            <line x1="12" y1="15" x2="12" y2="3"/>
                        </svg>
                        Export
                    </button>
                    <button type="button" class="btn btn-danger btn-sm" id="bulkDeleteBtn">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                            <polyline points="3,6 5,6 21,6"/>
                            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                        </svg>
                        Delete
                    </button>
                </div>
            </div>
        </div>

        <!-- History Table -->
        <div class="section">
            <div class="section-header">
                <h2 class="section-title">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                        <polyline points="14,2 14,8 20,8"/>
                        <line x1="16" y1="13" x2="8" y2="13"/>
                        <line x1="16" y1="17" x2="8" y2="17"/>
                        <line x1="10" y1="9" x2="8" y2="9"/>
                    </svg>
                    Process Records
                </h2>
                <span class="section-badge"><?= number_format($total) ?> total</span>
            </div>

            <?php if (empty($items)): ?>
            <div class="empty-state">
                <svg class="empty-state-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <circle cx="12" cy="12" r="10"/>
                    <path d="M8 12h8M12 8v8"/>
                </svg>
                <p class="empty-state-title">No Processes Found</p>
                <p class="empty-state-text">
                    <?php if ($hasFilters): ?>
                        No processes match your filters. Try adjusting or clearing them.
                    <?php else: ?>
                        You haven't started any processes yet. Start your first one!
                    <?php endif; ?>
                </p>
                <a href="<?= $baseUrl ?>/new" class="btn btn-primary">Start New Process</a>
            </div>
            <?php else: ?>
            <div class="table-container">
                <table class="history-table">
                    <thead>
                        <tr>
                            <th class="col-checkbox">
                                <label class="checkbox-wrapper">
                                    <input type="checkbox" id="selectAllCheckbox" class="bulk-checkbox">
                                    <span class="checkbox-custom"></span>
                                </label>
                            </th>
                            <th class="sortable <?= $sortBy === 'id' ? 'sorted-' . $sortOrder : '' ?>" data-sort="id">
                                <span class="th-content">
                                    ID
                                    <svg class="sort-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
                                        <path d="M7 10l5-5 5 5M7 14l5 5 5-5"/>
                                    </svg>
                                </span>
                            </th>
                            <th class="sortable <?= $sortBy === 'total_urls' ? 'sorted-' . $sortOrder : '' ?>" data-sort="total_urls">
                                <span class="th-content">
                                    URLs
                                    <svg class="sort-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
                                        <path d="M7 10l5-5 5 5M7 14l5 5 5-5"/>
                                    </svg>
                                </span>
                            </th>
                            <th>Progress</th>
                            <th class="sortable <?= $sortBy === 'mode' ? 'sorted-' . $sortOrder : '' ?>" data-sort="mode">
                                <span class="th-content">
                                    Mode
                                    <svg class="sort-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
                                        <path d="M7 10l5-5 5 5M7 14l5 5 5-5"/>
                                    </svg>
                                </span>
                            </th>
                            <th class="sortable <?= $sortBy === 'status' ? 'sorted-' . $sortOrder : '' ?>" data-sort="status">
                                <span class="th-content">
                                    Status
                                    <svg class="sort-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
                                        <path d="M7 10l5-5 5 5M7 14l5 5 5-5"/>
                                    </svg>
                                </span>
                            </th>
                            <th class="sortable <?= $sortBy === 'created_at' ? 'sorted-' . $sortOrder : '' ?>" data-sort="created_at">
                                <span class="th-content">
                                    Created
                                    <svg class="sort-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
                                        <path d="M7 10l5-5 5 5M7 14l5 5 5-5"/>
                                    </svg>
                                </span>
                            </th>
                            <th>Duration</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($items as $item):
                            $itemId = $item['id'] ?? '';
                            $itemTotalUrls = (int)($item['total_urls'] ?? 0);
                            $itemProcessed = (int)($item['processed_urls'] ?? 0);
                            $itemSuccess = (int)($item['success_count'] ?? 0);
                            $itemFailed = (int)($item['failed_count'] ?? 0);
                            $itemStatus = $item['status'] ?? 'pending';
                            $itemMode = $item['mode'] ?? 'standard';
                            $itemCreated = $item['created_at'] ?? null;
                            $itemStarted = $item['started_at'] ?? null;
                            $itemCompleted = $item['completed_at'] ?? null;

                            // Extra fields for expandable details
                            $itemOptions = json_decode($item['options'] ?? '{}', true) ?: [];
                            $itemErrorMessage = $item['error_message'] ?? '';
                            $itemCurrentPhase = (int)($item['current_phase'] ?? 0);

                            // Calculate success rate
                            $successRate = ($itemSuccess + $itemFailed) > 0
                                ? round(($itemSuccess / ($itemSuccess + $itemFailed)) * 100, 1)
                                : 0;

                            // Calculate progress
                            $progressPercent = $itemTotalUrls > 0 ? round(($itemProcessed / $itemTotalUrls) * 100, 1) : 0;

                            // Calculate duration
                            $duration = '-';
                            if ($itemStarted && $itemCompleted) {
                                $start = strtotime($itemStarted);
                                $end = strtotime($itemCompleted);
                                $diff = $end - $start;
                                if ($diff >= 3600) {
                                    $duration = round($diff / 3600, 1) . 'h';
                                } elseif ($diff >= 60) {
                                    $duration = round($diff / 60) . 'm';
                                } else {
                                    $duration = $diff . 's';
                                }
                            } elseif ($itemStarted && $itemStatus === 'running') {
                                $diff = time() - strtotime($itemStarted);
                                if ($diff >= 3600) {
                                    $duration = round($diff / 3600, 1) . 'h...';
                                } elseif ($diff >= 60) {
                                    $duration = round($diff / 60) . 'm...';
                                } else {
                                    $duration = $diff . 's...';
                                }
                            }

                            // Status class
                            $statusClass = match($itemStatus) {
                                'completed' => 'success',
                                'running' => 'info',
                                'pending' => 'warning',
                                'paused' => 'warning',
                                'failed', 'cancelled' => 'error',
                                default => 'muted'
                            };

                            // Mode label
                            $modeLabel = match($itemMode) {
                                'fast' => 'Fast',
                                'thorough' => 'Thorough',
                                default => 'Standard'
                            };
                        ?>
                        <tr class="history-row" data-process-id="<?= htmlspecialchars($itemId) ?>">
                            <td class="col-checkbox">
                                <label class="checkbox-wrapper">
                                    <input type="checkbox" class="row-checkbox bulk-checkbox" value="<?= htmlspecialchars($itemId) ?>">
                                    <span class="checkbox-custom"></span>
                                </label>
                            </td>
                            <td class="col-id">
                                <a href="<?= $baseUrl ?>/process/<?= htmlspecialchars($itemId) ?>" class="process-link" title="<?= htmlspecialchars($itemId) ?>">
                                    #<?= htmlspecialchars(substr($itemId, 6, 8)) ?>
                                </a>
                            </td>
                            <td class="col-urls">
                                <div class="urls-info">
                                    <span class="urls-total"><?= number_format($itemTotalUrls) ?></span>
                                    <div class="urls-breakdown">
                                        <span class="urls-success" data-field="success"><?= number_format($itemSuccess) ?></span>
                                        <span class="urls-divider">/</span>
                                        <span class="urls-failed" data-field="failed"><?= number_format($itemFailed) ?></span>
                                    </div>
                                </div>
                            </td>
                            <td class="col-progress">
                                <div class="mini-progress">
                                    <div class="mini-progress-bar">
                                        <div class="mini-progress-fill" data-field="progress-bar" style="width: <?= $progressPercent ?>%"></div>
                                    </div>
                                    <span class="mini-progress-text" data-field="progress-text"><?= $progressPercent ?>%</span>
                                </div>
                            </td>
                            <td class="col-mode">
                                <span class="mode-badge mode-<?= $itemMode ?>"><?= $modeLabel ?></span>
                            </td>
                            <td class="col-status">
                                <span class="badge badge-<?= $statusClass ?>" data-field="status" data-status="<?= $itemStatus ?>">
                                    <?= ucfirst(htmlspecialchars($itemStatus)) ?>
                                </span>
                            </td>
                            <td class="col-date">
                                <?php if ($itemCreated): ?>
                                <div class="date-info">
                                    <span class="date-main"><?= date('M j, Y', strtotime($itemCreated)) ?></span>
                                    <span class="date-time"><?= date('H:i', strtotime($itemCreated)) ?></span>
                                </div>
                                <?php else: ?>
                                <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td class="col-duration">
                                <span class="duration" data-field="duration"><?= $duration ?></span>
                            </td>
                            <td class="col-actions">
                                <div class="action-buttons">
                                    <!-- Expand Details -->
                                    <button type="button"
                                            class="btn-action btn-expand"
                                            data-process-id="<?= htmlspecialchars($itemId) ?>"
                                            title="Show Details">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <polyline points="6,9 12,15 18,9"/>
                                        </svg>
                                    </button>
                                    <!-- View Progress -->
                                    <a href="<?= $baseUrl ?>/process/<?= htmlspecialchars($itemId) ?>"
                                       class="btn-action"
                                       title="View Progress">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                                            <circle cx="12" cy="12" r="3"/>
                                        </svg>
                                    </a>
                                    <!-- Reprocess (for ALL statuses) -->
                                    <button type="button"
                                            class="btn-action btn-reprocess"
                                            data-process-id="<?= htmlspecialchars($itemId) ?>"
                                            title="Reprocess URLs">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <polyline points="23,4 23,10 17,10"/>
                                            <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
                                        </svg>
                                    </button>
                                    <?php if ($itemStatus === 'completed'): ?>
                                    <!-- Export -->
                                    <a href="<?= $baseUrl ?>/process/<?= htmlspecialchars($itemId) ?>?page=export"
                                       class="btn-action"
                                       title="Export Results">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                                            <polyline points="7,10 12,15 17,10"/>
                                            <line x1="12" y1="15" x2="12" y2="3"/>
                                        </svg>
                                    </a>
                                    <?php endif; ?>
                                    <!-- Delete -->
                                    <button type="button"
                                            class="btn-action btn-delete"
                                            data-process-id="<?= htmlspecialchars($itemId) ?>"
                                            title="Delete Process">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <polyline points="3,6 5,6 21,6"/>
                                            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                                        </svg>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <!-- Expandable Details Row -->
                        <tr class="expand-row" id="expand-<?= htmlspecialchars($itemId) ?>" style="display: none;">
                            <td colspan="9">
                                <div class="expand-content">
                                    <?php if (!empty($itemErrorMessage)): ?>
                                    <div class="expand-section expand-error">
                                        <div class="expand-label">Error Message</div>
                                        <div class="expand-value error-text"><?= htmlspecialchars($itemErrorMessage) ?></div>
                                    </div>
                                    <?php endif; ?>

                                    <div class="expand-grid">
                                        <div class="expand-section">
                                            <div class="expand-label">Processing Options</div>
                                            <div class="expand-value">
                                                <span class="option-tag">Mode: <?= ucfirst($itemMode) ?></span>
                                                <?php if (!empty($itemOptions['auto_export'])): ?>
                                                <span class="option-tag">Auto-export</span>
                                                <?php endif; ?>
                                                <?php if (!empty($itemOptions['notifications'])): ?>
                                                <span class="option-tag">Notifications</span>
                                                <?php endif; ?>
                                                <?php if (!empty($itemOptions['include_failed'])): ?>
                                                <span class="option-tag">Include Failed</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>

                                        <div class="expand-section">
                                            <div class="expand-label">Phase Progress</div>
                                            <div class="expand-value">
                                                <div class="mini-phases">
                                                    <?php for ($p = 0; $p < 4; $p++): ?>
                                                    <span class="mini-phase <?= $p < $itemCurrentPhase ? 'completed' : ($p === $itemCurrentPhase ? 'active' : '') ?>">
                                                        P<?= $p ?>
                                                    </span>
                                                    <?php endfor; ?>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="expand-section">
                                            <div class="expand-label">Success Rate</div>
                                            <div class="expand-value">
                                                <span class="rate-badge <?= $successRate >= 80 ? 'good' : ($successRate >= 50 ? 'medium' : 'bad') ?>">
                                                    <?= $successRate ?>%
                                                </span>
                                            </div>
                                        </div>

                                        <div class="expand-section">
                                            <div class="expand-label">URLs Breakdown</div>
                                            <div class="expand-value">
                                                <span class="stat-mini success"><?= number_format($itemSuccess) ?> success</span>
                                                <span class="stat-mini error"><?= number_format($itemFailed) ?> failed</span>
                                                <span class="stat-mini muted"><?= number_format($itemTotalUrls - $itemProcessed) ?> pending</span>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="expand-actions">
                                        <a href="<?= $baseUrl ?>/process/<?= htmlspecialchars($itemId) ?>" class="btn btn-sm btn-ghost">
                                            View Full Details
                                        </a>
                                        <button type="button" class="btn btn-sm btn-primary btn-reprocess" data-process-id="<?= htmlspecialchars($itemId) ?>">
                                            Reprocess All URLs
                                        </button>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
            <div class="pagination">
                <div class="pagination-info">
                    Showing <?= (($page - 1) * $limit) + 1 ?> to <?= min($page * $limit, $total) ?> of <?= number_format($total) ?> processes
                </div>
                <div class="pagination-controls">
                    <?php if ($page > 1): ?>
                    <a href="<?= $baseUrl ?>/history?p=1<?= $hasFilters ? '&status=' . urlencode($filterStatus) . '&date_from=' . urlencode($filterDateFrom) . '&date_to=' . urlencode($filterDateTo) : '' ?>"
                       class="pagination-btn" title="First Page">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="11,17 6,12 11,7"/>
                            <polyline points="18,17 13,12 18,7"/>
                        </svg>
                    </a>
                    <a href="<?= $baseUrl ?>/history?p=<?= $page - 1 ?><?= $hasFilters ? '&status=' . urlencode($filterStatus) . '&date_from=' . urlencode($filterDateFrom) . '&date_to=' . urlencode($filterDateTo) : '' ?>"
                       class="pagination-btn" title="Previous">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="15,18 9,12 15,6"/>
                        </svg>
                    </a>
                    <?php endif; ?>

                    <div class="pagination-pages">
                        <?php
                        $startPage = max(1, $page - 2);
                        $endPage = min($totalPages, $page + 2);

                        if ($startPage > 1): ?>
                        <a href="<?= $baseUrl ?>/history?p=1<?= $hasFilters ? '&status=' . urlencode($filterStatus) . '&date_from=' . urlencode($filterDateFrom) . '&date_to=' . urlencode($filterDateTo) : '' ?>"
                           class="pagination-page">1</a>
                        <?php if ($startPage > 2): ?>
                        <span class="pagination-ellipsis">...</span>
                        <?php endif; ?>
                        <?php endif; ?>

                        <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                        <a href="<?= $baseUrl ?>/history?p=<?= $i ?><?= $hasFilters ? '&status=' . urlencode($filterStatus) . '&date_from=' . urlencode($filterDateFrom) . '&date_to=' . urlencode($filterDateTo) : '' ?>"
                           class="pagination-page <?= $i === $page ? 'active' : '' ?>"><?= $i ?></a>
                        <?php endfor; ?>

                        <?php if ($endPage < $totalPages): ?>
                        <?php if ($endPage < $totalPages - 1): ?>
                        <span class="pagination-ellipsis">...</span>
                        <?php endif; ?>
                        <a href="<?= $baseUrl ?>/history?p=<?= $totalPages ?><?= $hasFilters ? '&status=' . urlencode($filterStatus) . '&date_from=' . urlencode($filterDateFrom) . '&date_to=' . urlencode($filterDateTo) : '' ?>"
                           class="pagination-page"><?= $totalPages ?></a>
                        <?php endif; ?>
                    </div>

                    <?php if ($page < $totalPages): ?>
                    <a href="<?= $baseUrl ?>/history?p=<?= $page + 1 ?><?= $hasFilters ? '&status=' . urlencode($filterStatus) . '&date_from=' . urlencode($filterDateFrom) . '&date_to=' . urlencode($filterDateTo) : '' ?>"
                       class="pagination-btn" title="Next">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="9,18 15,12 9,6"/>
                        </svg>
                    </a>
                    <a href="<?= $baseUrl ?>/history?p=<?= $totalPages ?><?= $hasFilters ? '&status=' . urlencode($filterStatus) . '&date_from=' . urlencode($filterDateFrom) . '&date_to=' . urlencode($filterDateTo) : '' ?>"
                       class="pagination-btn" title="Last Page">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="13,17 18,12 13,7"/>
                            <polyline points="6,17 11,12 6,7"/>
                        </svg>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
            <?php endif; ?>
        </div>
    </main>

    <!-- Delete Confirmation Modal -->
    <div id="deleteModal" class="modal">
        <div class="modal-backdrop"></div>
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="24" height="24">
                        <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
                        <line x1="12" y1="9" x2="12" y2="13"/>
                        <line x1="12" y1="17" x2="12.01" y2="17"/>
                    </svg>
                    Delete Process
                </h3>
                <button type="button" class="modal-close" onclick="closeDeleteModal()">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <line x1="18" y1="6" x2="6" y2="18"/>
                        <line x1="6" y1="6" x2="18" y2="18"/>
                    </svg>
                </button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete this process? This action cannot be undone.</p>
                <p class="modal-process-id">Process ID: <strong id="deleteProcessId"></strong></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-ghost" onclick="closeDeleteModal()">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                        <polyline points="3,6 5,6 21,6"/>
                        <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                    </svg>
                    Delete
                </button>
            </div>
        </div>
    </div>

    <!-- Toast Container -->
    <div id="toastContainer" class="toast-container"></div>

    <script src="<?= $baseUrl ?>/assets/js/app.js?v=<?= time() ?>"></script>
    <script>
    // Delete functionality
    let deleteProcessId = null;
    const deleteModal = document.getElementById('deleteModal');
    const deleteProcessIdEl = document.getElementById('deleteProcessId');
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');

    document.querySelectorAll('.btn-delete').forEach(btn => {
        btn.addEventListener('click', function() {
            deleteProcessId = this.dataset.processId;
            deleteProcessIdEl.textContent = '#' + deleteProcessId.substring(0, 8);
            deleteModal.classList.add('active');
        });
    });

    function closeDeleteModal() {
        deleteModal.classList.remove('active');
        deleteProcessId = null;
    }

    deleteModal.querySelector('.modal-backdrop').addEventListener('click', closeDeleteModal);

    confirmDeleteBtn.addEventListener('click', async function() {
        if (!deleteProcessId) return;

        this.disabled = true;
        this.innerHTML = '<span class="spinner-small"></span> Deleting...';

        try {
            // v5.0-beta FIX: Use POST with /delete subaction (not DELETE method)
            const response = await fetch(`<?= $baseUrl ?>/api/v1/process/${deleteProcessId}/delete`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            });

            if (response.ok) {
                showToast('Process deleted successfully', 'success');
                closeDeleteModal();
                // Reload after short delay
                setTimeout(() => window.location.reload(), 1000);
            } else {
                const data = await response.json();
                showToast(data.error || 'Failed to delete process', 'error');
            }
        } catch (error) {
            showToast('Failed to delete process', 'error');
        }

        this.disabled = false;
        this.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><polyline points="3,6 5,6 21,6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg> Delete';
    });

    // Expand/Collapse functionality
    document.querySelectorAll('.btn-expand').forEach(btn => {
        btn.addEventListener('click', function() {
            const processId = this.dataset.processId;
            const expandRow = document.getElementById('expand-' + processId);
            const isExpanded = expandRow.style.display !== 'none';

            // Close all other expanded rows
            document.querySelectorAll('.expand-row').forEach(row => {
                row.style.display = 'none';
            });
            document.querySelectorAll('.btn-expand').forEach(b => {
                b.classList.remove('expanded');
            });

            // Toggle this row
            if (!isExpanded) {
                expandRow.style.display = 'table-row';
                this.classList.add('expanded');
            }
        });
    });

    // Reprocess functionality
    document.querySelectorAll('.btn-reprocess').forEach(btn => {
        btn.addEventListener('click', async function() {
            const processId = this.dataset.processId;

            if (!confirm('Create a new process with the same URLs?\n\nThis will queue all URLs from this process for reprocessing.')) {
                return;
            }

            this.disabled = true;
            const originalHtml = this.innerHTML;
            this.innerHTML = '<span class="spinner-small"></span>';

            try {
                const response = await fetch(`<?= $baseUrl ?>/api/v1/process/${processId}/reprocess`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });

                const data = await response.json();

                if (response.ok && data.success) {
                    showToast('Process queued for reprocessing!', 'success');
                    setTimeout(() => {
                        window.location.href = `<?= $baseUrl ?>/process/${data.data.new_process_id}`;
                    }, 1000);
                } else {
                    showToast(data.error?.message || data.error || 'Failed to reprocess', 'error');
                    this.disabled = false;
                    this.innerHTML = originalHtml;
                }
            } catch (error) {
                showToast('Failed to reprocess', 'error');
                this.disabled = false;
                this.innerHTML = originalHtml;
            }
        });
    });

    // Toast helper
    function showToast(message, type = 'info') {
        if (typeof window.showToast === 'function') {
            window.showToast(message, type);
        } else {
            const container = document.getElementById('toastContainer');
            const toast = document.createElement('div');
            toast.className = `toast toast-${type}`;
            toast.textContent = message;
            container.appendChild(toast);
            setTimeout(() => toast.remove(), 3000);
        }
    }

    // ============================================
    // AUTO-REFRESH LIVE UPDATES
    // ============================================
    const AUTO_REFRESH_INTERVAL = 3000; // 3 seconds
    let autoRefreshTimer = null;
    let hasActiveProcesses = <?= $runningCount > 0 ? 'true' : 'false' ?>;

    // Status class mapping
    const statusClasses = {
        'completed': 'success',
        'running': 'info',
        'pending': 'warning',
        'paused': 'warning',
        'failed': 'error',
        'cancelled': 'error'
    };

    // Fetch latest history data
    async function fetchHistoryUpdates() {
        try {
            const response = await fetch('<?= $baseUrl ?>/api/v1/dashboard/history?limit=50');
            if (!response.ok) return null;
            const data = await response.json();
            return data.success ? data.data : null;
        } catch (error) {
            console.error('Auto-refresh fetch error:', error);
            return null;
        }
    }

    // Update a single row with new data
    function updateRow(row, item) {
        const processId = row.dataset.processId;
        let updated = false;

        // Update success count
        const successEl = row.querySelector('[data-field="success"]');
        if (successEl) {
            const newSuccess = Number(item.success_count || 0).toLocaleString();
            if (successEl.textContent !== newSuccess) {
                successEl.textContent = newSuccess;
                flashElement(successEl);
                updated = true;
            }
        }

        // Update failed count
        const failedEl = row.querySelector('[data-field="failed"]');
        if (failedEl) {
            const newFailed = Number(item.failed_count || 0).toLocaleString();
            if (failedEl.textContent !== newFailed) {
                failedEl.textContent = newFailed;
                flashElement(failedEl);
                updated = true;
            }
        }

        // Update progress bar
        const progressBar = row.querySelector('[data-field="progress-bar"]');
        const progressText = row.querySelector('[data-field="progress-text"]');
        if (progressBar && progressText) {
            const total = Number(item.total_urls || 0);
            const processed = Number(item.processed_urls || 0);
            const percent = total > 0 ? Math.round((processed / total) * 1000) / 10 : 0;
            const newPercent = percent + '%';

            if (progressText.textContent !== newPercent) {
                progressBar.style.width = newPercent;
                progressText.textContent = newPercent;
                flashElement(progressText);
                updated = true;
            }
        }

        // Update status badge
        const statusEl = row.querySelector('[data-field="status"]');
        if (statusEl) {
            const newStatus = item.status || 'pending';
            const currentStatus = statusEl.dataset.status;

            if (currentStatus !== newStatus) {
                statusEl.textContent = newStatus.charAt(0).toUpperCase() + newStatus.slice(1);
                statusEl.dataset.status = newStatus;

                // Update badge class
                const newClass = statusClasses[newStatus] || 'muted';
                statusEl.className = `badge badge-${newClass}`;
                flashElement(statusEl);
                updated = true;
            }
        }

        // Update duration for running processes
        const durationEl = row.querySelector('[data-field="duration"]');
        if (durationEl && item.status === 'running' && item.started_at) {
            const start = new Date(item.started_at).getTime();
            const now = Date.now();
            const diff = Math.floor((now - start) / 1000);
            let duration;
            if (diff >= 3600) {
                duration = (diff / 3600).toFixed(1) + 'h...';
            } else if (diff >= 60) {
                duration = Math.round(diff / 60) + 'm...';
            } else {
                duration = diff + 's...';
            }
            durationEl.textContent = duration;
        }

        return updated;
    }

    // Flash element to show update
    function flashElement(el) {
        el.classList.add('flash-update');
        setTimeout(() => el.classList.remove('flash-update'), 500);
    }

    // Main auto-refresh function
    async function autoRefresh() {
        const data = await fetchHistoryUpdates();
        if (!data || !data.items) return;

        let anyRunning = false;
        let anyUpdated = false;

        data.items.forEach(item => {
            const row = document.querySelector(`tr[data-process-id="${item.id}"]`);
            if (row) {
                const updated = updateRow(row, item);
                if (updated) anyUpdated = true;
            }

            if (item.status === 'running' || item.status === 'pending') {
                anyRunning = true;
            }
        });

        // Update live indicator
        const liveIndicator = document.getElementById('liveIndicator');
        if (anyRunning) {
            if (!liveIndicator) {
                // Add live indicator if not present
                const titleEl = document.querySelector('.page-title');
                if (titleEl && !titleEl.querySelector('.live-indicator')) {
                    const indicator = document.createElement('span');
                    indicator.id = 'liveIndicator';
                    indicator.className = 'live-indicator';
                    indicator.title = 'Auto-updating every 3 seconds';
                    indicator.innerHTML = '<span class="live-dot"></span>LIVE';
                    titleEl.appendChild(indicator);
                }
            }
            hasActiveProcesses = true;
        } else {
            if (liveIndicator) {
                liveIndicator.remove();
            }
            hasActiveProcesses = false;
        }

        // Continue or stop auto-refresh based on active processes
        if (hasActiveProcesses) {
            scheduleAutoRefresh();
        } else {
            stopAutoRefresh();
        }
    }

    // Schedule next auto-refresh
    function scheduleAutoRefresh() {
        if (autoRefreshTimer) clearTimeout(autoRefreshTimer);
        autoRefreshTimer = setTimeout(autoRefresh, AUTO_REFRESH_INTERVAL);
    }

    // Stop auto-refresh
    function stopAutoRefresh() {
        if (autoRefreshTimer) {
            clearTimeout(autoRefreshTimer);
            autoRefreshTimer = null;
        }
    }

    // Start auto-refresh if there are active processes
    if (hasActiveProcesses) {
        scheduleAutoRefresh();
    }

    // Cleanup on page unload
    window.addEventListener('beforeunload', stopAutoRefresh);

    // ============================================
    // BULK ACTIONS FUNCTIONALITY
    // ============================================
    const bulkActionsBar = document.getElementById('bulkActionsBar');
    const selectAllCheckbox = document.getElementById('selectAllCheckbox');
    const selectedCountEl = document.getElementById('selectedCount');
    const clearSelectionBtn = document.getElementById('clearSelectionBtn');
    const bulkReprocessBtn = document.getElementById('bulkReprocessBtn');
    const bulkExportBtn = document.getElementById('bulkExportBtn');
    const bulkDeleteBtn = document.getElementById('bulkDeleteBtn');
    const rowCheckboxes = document.querySelectorAll('.row-checkbox');

    // Get selected process IDs
    function getSelectedIds() {
        return Array.from(document.querySelectorAll('.row-checkbox:checked')).map(cb => cb.value);
    }

    // Update bulk actions bar visibility
    function updateBulkActionsBar() {
        const selectedIds = getSelectedIds();
        const count = selectedIds.length;

        selectedCountEl.textContent = count;

        if (count > 0) {
            bulkActionsBar.style.display = 'block';
            bulkActionsBar.classList.add('visible');
        } else {
            bulkActionsBar.classList.remove('visible');
            setTimeout(() => {
                if (getSelectedIds().length === 0) {
                    bulkActionsBar.style.display = 'none';
                }
            }, 200);
        }

        // Update select all checkbox state
        const totalCheckboxes = rowCheckboxes.length;
        if (count === 0) {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = false;
        } else if (count === totalCheckboxes) {
            selectAllCheckbox.checked = true;
            selectAllCheckbox.indeterminate = false;
        } else {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = true;
        }
    }

    // Select All checkbox handler
    selectAllCheckbox.addEventListener('change', function() {
        const isChecked = this.checked;
        rowCheckboxes.forEach(cb => {
            cb.checked = isChecked;
            cb.closest('tr').classList.toggle('selected', isChecked);
        });
        updateBulkActionsBar();
    });

    // Individual row checkbox handler
    rowCheckboxes.forEach(cb => {
        cb.addEventListener('change', function() {
            this.closest('tr').classList.toggle('selected', this.checked);
            updateBulkActionsBar();
        });
    });

    // Clear selection button
    clearSelectionBtn.addEventListener('click', function() {
        rowCheckboxes.forEach(cb => {
            cb.checked = false;
            cb.closest('tr').classList.remove('selected');
        });
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = false;
        updateBulkActionsBar();
    });

    // Bulk Reprocess
    bulkReprocessBtn.addEventListener('click', async function() {
        const selectedIds = getSelectedIds();
        if (selectedIds.length === 0) return;

        if (!confirm(`Reprocess ${selectedIds.length} selected process(es)?\n\nThis will create new processes with the same URLs.`)) {
            return;
        }

        this.disabled = true;
        const originalHtml = this.innerHTML;
        this.innerHTML = '<span class="spinner-small"></span> Processing...';

        let successCount = 0;
        let failCount = 0;

        for (const processId of selectedIds) {
            try {
                const response = await fetch(`<?= $baseUrl ?>/api/v1/process/${processId}/reprocess`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });

                if (response.ok) {
                    successCount++;
                } else {
                    failCount++;
                }
            } catch (error) {
                failCount++;
            }
        }

        this.disabled = false;
        this.innerHTML = originalHtml;

        if (successCount > 0) {
            showToast(`${successCount} process(es) queued for reprocessing!`, 'success');
        }
        if (failCount > 0) {
            showToast(`${failCount} process(es) failed to reprocess`, 'error');
        }

        // Clear selection and reload after delay
        clearSelectionBtn.click();
        setTimeout(() => window.location.reload(), 1500);
    });

    // Bulk Export
    bulkExportBtn.addEventListener('click', async function() {
        const selectedIds = getSelectedIds();
        if (selectedIds.length === 0) return;

        this.disabled = true;
        const originalHtml = this.innerHTML;
        this.innerHTML = '<span class="spinner-small"></span> Exporting...';

        try {
            // Fetch all process data and combine for export
            let allResults = [];
            let processedCount = 0;

            for (const processId of selectedIds) {
                try {
                    const response = await fetch(`<?= $baseUrl ?>/api/v1/process/${processId}/results?limit=10000`);
                    if (response.ok) {
                        const data = await response.json();
                        if (data.success && data.data.results) {
                            allResults = allResults.concat(data.data.results.map(r => ({
                                ...r,
                                process_id: processId
                            })));
                            processedCount++;
                        }
                    }
                } catch (error) {
                    console.error(`Failed to fetch results for ${processId}:`, error);
                }
            }

            if (allResults.length === 0) {
                showToast('No results found to export', 'warning');
                this.disabled = false;
                this.innerHTML = originalHtml;
                return;
            }

            // Generate CSV
            const headers = ['Process ID', 'URL', 'Title', 'Description', 'Status', 'Created'];
            const csvRows = [headers.join(',')];

            allResults.forEach(result => {
                const row = [
                    result.process_id || '',
                    `"${(result.url || '').replace(/"/g, '""')}"`,
                    `"${(result.title || '').replace(/"/g, '""')}"`,
                    `"${(result.description || '').replace(/"/g, '""')}"`,
                    result.status || '',
                    result.created_at || ''
                ];
                csvRows.push(row.join(','));
            });

            // Download CSV
            const csv = csvRows.join('\n');
            const blob = new Blob([csv], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `bulk-export-${selectedIds.length}-processes-${new Date().toISOString().split('T')[0]}.csv`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);

            showToast(`Exported ${allResults.length} results from ${processedCount} process(es)`, 'success');
        } catch (error) {
            showToast('Export failed', 'error');
        }

        this.disabled = false;
        this.innerHTML = originalHtml;
    });

    // Bulk Delete
    bulkDeleteBtn.addEventListener('click', async function() {
        const selectedIds = getSelectedIds();
        if (selectedIds.length === 0) return;

        if (!confirm(`Delete ${selectedIds.length} selected process(es)?\n\nThis action cannot be undone!`)) {
            return;
        }

        this.disabled = true;
        const originalHtml = this.innerHTML;
        this.innerHTML = '<span class="spinner-small"></span> Deleting...';

        let successCount = 0;
        let failCount = 0;

        for (const processId of selectedIds) {
            try {
                // v5.0-beta FIX: Use POST with /delete subaction (not DELETE method)
                const response = await fetch(`<?= $baseUrl ?>/api/v1/process/${processId}/delete`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });

                if (response.ok) {
                    successCount++;
                    // Remove row from table
                    const row = document.querySelector(`tr[data-process-id="${processId}"]`);
                    const expandRow = document.getElementById(`expand-${processId}`);
                    if (row) row.remove();
                    if (expandRow) expandRow.remove();
                } else {
                    failCount++;
                }
            } catch (error) {
                failCount++;
            }
        }

        this.disabled = false;
        this.innerHTML = originalHtml;

        if (successCount > 0) {
            showToast(`${successCount} process(es) deleted successfully`, 'success');
        }
        if (failCount > 0) {
            showToast(`${failCount} process(es) failed to delete`, 'error');
        }

        // Clear selection and update counts
        clearSelectionBtn.click();

        // Update total count in UI
        const totalBadge = document.querySelector('.section-badge');
        if (totalBadge) {
            const currentTotal = parseInt(totalBadge.textContent.replace(/[^0-9]/g, '')) || 0;
            const newTotal = Math.max(0, currentTotal - successCount);
            totalBadge.textContent = newTotal.toLocaleString() + ' total';
        }
    });

    // ============================================
    // SORTABLE COLUMNS FUNCTIONALITY
    // ============================================
    document.querySelectorAll('th.sortable').forEach(th => {
        th.addEventListener('click', function() {
            const sortField = this.dataset.sort;
            const currentSort = '<?= $sortBy ?>';
            const currentOrder = '<?= $sortOrder ?>';

            let newOrder = 'asc';
            if (sortField === currentSort) {
                newOrder = currentOrder === 'asc' ? 'desc' : 'asc';
            }

            // Update hidden form fields and submit
            const form = document.querySelector('.filters-form');
            const sortInput = form.querySelector('input[name="sort"]');
            const orderInput = form.querySelector('input[name="order"]');

            if (sortInput && orderInput) {
                sortInput.value = sortField;
                orderInput.value = newOrder;
                form.submit();
            }
        });
    });
    </script>
</body>
</html>
