<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/layout.php';
require_once dirname(__DIR__) . '/includes/admin_jobs.php';

requirePermission('job_queue_view');
ensureAdminJobsTable();

$statusFilter = (string)($_GET['status'] ?? '');
$typeFilter = (string)($_GET['type'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$statusLabels = adminJobStatusLabels();
$typeLabels = adminJobTypeLabels();

if ($statusFilter !== '' && !isset($statusLabels[$statusFilter])) $statusFilter = '';
if ($typeFilter !== '' && !isset($typeLabels[$typeFilter])) $typeFilter = '';

$summary = getAdminJobDashboardSummary();
$jobsResult = getAdminJobs([
    'status' => $statusFilter,
    'type' => $typeFilter,
    'page' => $page,
    'limit' => 24,
]);
$jobs = $jobsResult['items'];

function adminJobFilterUrl($overrides = []) {
    $query = array_merge([
        'status' => $_GET['status'] ?? '',
        'type' => $_GET['type'] ?? '',
        'page' => $_GET['page'] ?? 1,
    ], $overrides);
    $query = array_filter($query, static function ($value) {
        return $value !== '' && $value !== null;
    });
    return 'jobs.php' . ($query ? '?' . http_build_query($query) : '');
}

renderHeader('작업 큐', 'jobs');
?>
<div class="admin-dashboard admin-jobs-page">
    <div class="page-title-section">
        <h1 class="page-main-title">작업 큐 / 진행 상태</h1>
        <p class="page-subtitle">음악 스캔, 백업, 가져오기, 점검 작업의 진행 상태를 확인합니다. 작업 상세에는 실제 파일 경로를 표시하지 않습니다.</p>
    </div>

    <?php renderStatGrid([
        ['label' => '진행 중', 'value' => number_format($summary['active'])],
        ['label' => '최근 24시간 완료', 'value' => number_format($summary['completed_24h'])],
        ['label' => '최근 24시간 실패', 'value' => number_format($summary['failed_24h'])],
        ['label' => '누적 작업', 'value' => number_format($summary['total'])],
    ]); ?>

    <section class="settings-card admin-job-filter-card">
        <div class="section-heading-row">
            <div>
                <h2 class="section-title">작업 필터</h2>
                <p class="settings-muted">상태와 작업 유형별로 최근 작업을 좁혀 봅니다.</p>
            </div>
            <a class="btn btn-secondary btn-sm" href="jobs.php"><i class="fa-solid fa-rotate-right"></i> 초기화</a>
        </div>
        <form method="GET" class="admin-job-filter-form">
            <label>
                <span>상태</span>
                <select name="status">
                    <option value="">전체 상태</option>
                    <?php foreach ($statusLabels as $key => $label): ?>
                        <option value="<?php echo h($key); ?>" <?php echo $statusFilter === $key ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                    <?php endforeach; ?>
                </select>
            </label>
            <label>
                <span>작업 유형</span>
                <select name="type">
                    <option value="">전체 유형</option>
                    <?php foreach ($typeLabels as $key => $label): ?>
                        <option value="<?php echo h($key); ?>" <?php echo $typeFilter === $key ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                    <?php endforeach; ?>
                </select>
            </label>
            <button type="submit" class="btn btn-primary"><i class="fa-solid fa-filter"></i> 적용</button>
        </form>
    </section>

    <section class="home-section admin-job-list-section">
        <div class="section-heading-row">
            <div>
                <h2 class="section-title">작업 목록</h2>
                <p class="settings-muted">총 <?php echo number_format($jobsResult['total']); ?>개 작업</p>
            </div>
            <a class="section-more-link" href="index.php">관리자 센터</a>
        </div>

        <?php if (empty($jobs)): ?>
            <div class="admin-job-empty-state">
                <i class="fa-solid fa-list-check" aria-hidden="true"></i>
                <strong>표시할 작업이 없습니다.</strong>
                <p>스캔, 백업, 가져오기 또는 유지보수 작업을 실행하면 이곳에 진행 상태가 기록됩니다.</p>
            </div>
        <?php else: ?>
            <div class="table-responsive admin-job-table-wrap">
                <table class="data-table admin-jobs-table">
                    <thead>
                    <tr>
                        <th>작업</th>
                        <th>상태</th>
                        <th>진행률</th>
                        <th>처리</th>
                        <th>시작 / 종료</th>
                        <th>요청자</th>
                        <th>요약</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($jobs as $job): ?>
                        <?php
                        $progress = max(0, min(100, (int)($job['progress'] ?? 0)));
                        $status = (string)($job['status'] ?? '');
                        $requester = trim((string)($job['requested_display_name'] ?: $job['requested_username'] ?: 'system'));
                        ?>
                        <tr>
                            <td>
                                <div class="admin-job-name-cell">
                                    <span class="job-type-chip"><?php echo h(adminJobTypeLabel($job['job_type'] ?? '')); ?></span>
                                    <strong><?php echo h($job['job_name']); ?></strong>
                                    <small>#<?php echo h($job['id']); ?> · <?php echo h($job['job_key']); ?></small>
                                </div>
                            </td>
                            <td>
                                <span class="status-badge job-status-<?php echo h(adminJobStatusClass($status)); ?>">
                                    <?php echo h(adminJobStatusLabel($status)); ?>
                                </span>
                            </td>
                            <td>
                                <div class="admin-job-progress" aria-label="진행률 <?php echo h($progress); ?>%">
                                    <div class="admin-job-progress-bar" style="width: <?php echo h($progress); ?>%;"></div>
                                </div>
                                <small class="settings-muted"><?php echo number_format($progress); ?>%</small>
                            </td>
                            <td>
                                <strong><?php echo number_format((int)$job['processed_count']); ?></strong>
                                <?php if ((int)$job['failed_count'] > 0): ?>
                                    <small class="job-failed-count">실패 <?php echo number_format((int)$job['failed_count']); ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="admin-job-time-cell">
                                    <span><?php echo h($job['started_at'] ?: $job['created_at']); ?></span>
                                    <small><?php echo h($job['finished_at'] ?: '진행 정보 갱신: ' . ($job['updated_at'] ?: '-')); ?></small>
                                </div>
                            </td>
                            <td><?php echo h($requester); ?></td>
                            <td>
                                <div class="admin-job-summary-cell">
                                    <span><?php echo h(maskInternalPathText($job['summary_message'] ?? '')); ?></span>
                                    <?php if (!empty($job['error_type'])): ?><small>오류 유형: <?php echo h($job['error_type']); ?></small><?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($jobsResult['pages'] > 1): ?>
                <nav class="pagination admin-job-pagination" aria-label="작업 큐 페이지">
                    <?php for ($i = 1; $i <= $jobsResult['pages']; $i++): ?>
                        <a class="<?php echo $i === $jobsResult['page'] ? 'active' : ''; ?>" href="<?php echo h(adminJobFilterUrl(['page' => $i])); ?>"><?php echo number_format($i); ?></a>
                    <?php endfor; ?>
                </nav>
            <?php endif; ?>
        <?php endif; ?>
    </section>
</div>
<?php renderFooter(); ?>
