<?php
/**
 * Author Dashboard - full replacement view
 * Safe, conservative rebuild for /app/views/author/dashboard.php
 * Keeps existing variables/routes and moves the submissions list to the top.
 */

if (!function_exists('ad_h')) {
    function ad_h($v): string
    {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('ad_t')) {
    function ad_t(string $key, string $ar, string $en = ''): string
    {
        if (function_exists('ec_t')) {
            return (string)ec_t($key, $ar);
        }

        $lang = $_SESSION['lang'] ?? 'ar';
        return $lang === 'ar' ? $ar : ($en !== '' ? $en : $ar);
    }
}

if (!function_exists('ad_status_badge_class')) {
    function ad_status_badge_class($status): string
    {
        return match (strtolower((string)$status)) {
            'accepted', 'published', 'camera_ready', 'camera-ready' => 'ad-badge-success',
            'rejected', 'declined' => 'ad-badge-danger',
            'under_review', 'reviewing', 'review', 'screening' => 'ad-badge-primary',
            'revision_required', 'revised', 'revision', 'minor_revision', 'major_revision' => 'ad-badge-warning',
            'draft' => 'ad-badge-muted',
            'submitted' => 'ad-badge-info',
            default => 'ad-badge-soft',
        };
    }
}

if (!function_exists('ad_status_label')) {
    function ad_status_label($status, bool $isArabic): string
    {
        $key = strtolower((string)$status);
        $labels = [
            'draft' => ['ar' => 'مسودة', 'en' => 'Draft'],
            'submitted' => ['ar' => 'تم التقديم', 'en' => 'Submitted'],
            'screening' => ['ar' => 'الفحص', 'en' => 'Screening'],
            'under_review' => ['ar' => 'قيد التحكيم', 'en' => 'Under Review'],
            'reviewing' => ['ar' => 'قيد التحكيم', 'en' => 'Reviewing'],
            'revision_required' => ['ar' => 'تعديل مطلوب', 'en' => 'Revision Required'],
            'revised' => ['ar' => 'تم التعديل', 'en' => 'Revised'],
            'accepted' => ['ar' => 'مقبول', 'en' => 'Accepted'],
            'rejected' => ['ar' => 'مرفوض', 'en' => 'Rejected'],
            'published' => ['ar' => 'منشور', 'en' => 'Published'],
            'camera_ready' => ['ar' => 'النسخة النهائية', 'en' => 'Camera Ready'],
        ];
        return $labels[$key][$isArabic ? 'ar' : 'en'] ?? (($status !== null && $status !== '') ? (string)$status : '-');
    }
}

if (!function_exists('ad_submission_title')) {
    function ad_submission_title(array $s): string
    {
        return (string)(
            $s['display_title']
            ?? $s['title']
            ?? $s['title_ar']
            ?? $s['title_en']
            ?? ('Submission #' . ($s['id'] ?? $s['submission_id'] ?? ''))
        );
    }
}

if (!function_exists('ad_submission_progress')) {
    function ad_submission_progress($status, $stage = null): int
    {
        $status = strtolower((string)$status);
        $stage = strtolower((string)$stage);
        $key = $status ?: $stage;
        return match ($key) {
            'draft' => 10,
            'submitted', 'submission' => 25,
            'screening' => 40,
            'under_review', 'reviewing', 'review' => 60,
            'revision_required', 'revised', 'revision' => 75,
            'decision' => 82,
            'accepted', 'camera_ready', 'camera-ready', 'production' => 90,
            'published' => 100,
            default => 15,
        };
    }
}

if (!function_exists('ad_file_url')) {
    function ad_file_url($path): string
    {
        $path = trim((string)$path);
        if ($path === '') {
            return '#';
        }
        if (preg_match('~^https?://~i', $path)) {
            return $path;
        }
        $path = ltrim($path, '/');
        if (str_starts_with($path, 'easychair/')) {
            return '/' . $path;
        }
        return '/easychair/' . $path;
    }
}

if (!function_exists('ad_count')) {
    function ad_count($v): int
    {
        return is_countable($v) ? count($v) : 0;
    }
}

$submissions = is_array($submissions ?? null) ? $submissions : [];
$stats = is_array($stats ?? null) ? $stats : [];
$conference = is_array($conference ?? null) ? $conference : [];
$workflow = is_array($workflow ?? null) ? $workflow : [];
$workflowSummary = is_array($workflowSummary ?? null) ? $workflowSummary : [];
$publicationReadiness = is_array($publicationReadiness ?? null) ? $publicationReadiness : [];
$collaborationWorkspace = is_array($collaborationWorkspace ?? null) ? $collaborationWorkspace : [];
$submissionWorkspace = is_array($submissionWorkspace ?? null) ? $submissionWorkspace : [];
$reviewExplorer = is_array($reviewExplorer ?? null) ? $reviewExplorer : [];

$workflowSummary = array_merge([
    'revision_queue' => 0,
    'decision_pending' => 0,
    'unread_reviews' => 0,
    'camera_ready' => 0,
], $workflowSummary);

$publicationReadiness = array_merge([
    'ready_score' => 0,
    'accepted' => [],
    'camera_ready' => [],
    'blockers' => [],
], $publicationReadiness);

$collaborationWorkspace = array_merge([
    'multi_author' => [],
    'needs_coordination' => [],
    'governance_alert' => [],
    'ready_to_submit' => [],
], $collaborationWorkspace);

$submissionWorkspace = array_merge([
    'reupload' => [],
    'response' => [],
    'camera' => [],
], $submissionWorkspace);

$reviewExplorer = array_merge([
    'decision_ready' => [],
    'version_ready' => [],
    'needs_response' => [],
    'accepted' => [],
], $reviewExplorer);

$lang = $_SESSION['lang'] ?? 'ar';
$isArabic = $lang === 'ar';
$dir = $isArabic ? 'rtl' : 'ltr';
$textAlign = $isArabic ? 'right' : 'left';

$confTitle = ($conference['title_ar'] ?? '') ?: (($conference['title_en'] ?? '') ?: ($isArabic ? 'المؤتمر' : 'Conference'));
$conferenceSlug = $_SESSION['conference_slug'] ?? ($conference['slug'] ?? ('conference-' . (int)($_SESSION['conference_id'] ?? 0)));

$totalSubmissions = (int)($stats['total'] ?? count($submissions));
$acceptedCount = (int)($stats['accepted'] ?? 0);
$pendingRevision = (int)($stats['revision_required'] ?? 0);

$revisionRows = array_values(array_filter($submissions, static function ($x) {
    return in_array(strtolower((string)($x['status'] ?? '')), ['revision_required', 'revised', 'minor_revision', 'major_revision'], true);
}));

$reviewRows = array_values(array_filter($submissions, static function ($x) {
    return ((int)($x['reviews_count'] ?? 0)) > 0;
}));

$deadlineCards = [];
foreach ([
    'submission_deadline' => ['fa-file-circle-plus', $isArabic ? 'آخر موعد للتقديم' : 'Submission Deadline', 'primary'],
    'review_deadline' => ['fa-user-check', $isArabic ? 'آخر موعد للتحكيم' : 'Review Deadline', 'warning'],
    'camera_ready_deadline' => ['fa-upload', $isArabic ? 'آخر موعد للنسخة النهائية' : 'Camera Ready Deadline', 'success'],
] as $field => $meta) {
    if (!empty($conference[$field])) {
        $deadlineCards[] = ['field' => $field, 'icon' => $meta[0], 'title' => $meta[1], 'date' => $conference[$field], 'tone' => $meta[2]];
    }
}

$workflowLabels = [
    'submission' => ['ar' => 'التقديم', 'en' => 'Submission'],
    'screening' => ['ar' => 'الفحص', 'en' => 'Screening'],
    'review' => ['ar' => 'التحكيم', 'en' => 'Review'],
    'revision' => ['ar' => 'التعديل', 'en' => 'Revision'],
    'decision' => ['ar' => 'القرار', 'en' => 'Decision'],
    'production' => ['ar' => 'الإنتاج', 'en' => 'Production'],
    'published' => ['ar' => 'النشر', 'en' => 'Published'],
];

$kpiCards = [
    ['icon' => 'fa-layer-group', 'label_ar' => 'كل التقديمات', 'label_en' => 'All Submissions', 'value' => $totalSubmissions, 'tone' => 'primary'],
    ['icon' => 'fa-pen-to-square', 'label_ar' => 'مسودة', 'label_en' => 'Drafts', 'value' => (int)($stats['draft'] ?? 0), 'tone' => 'muted'],
    ['icon' => 'fa-paper-plane', 'label_ar' => 'تم التقديم', 'label_en' => 'Submitted', 'value' => (int)($stats['submitted'] ?? 0), 'tone' => 'info'],
    ['icon' => 'fa-user-check', 'label_ar' => 'قيد التحكيم', 'label_en' => 'Under Review', 'value' => (int)($stats['under_review'] ?? $stats['reviewing'] ?? 0), 'tone' => 'primary'],
    ['icon' => 'fa-rotate', 'label_ar' => 'تعديل مطلوب', 'label_en' => 'Revisions', 'value' => $pendingRevision, 'tone' => 'warning'],
    ['icon' => 'fa-circle-check', 'label_ar' => 'مقبول', 'label_en' => 'Accepted', 'value' => $acceptedCount, 'tone' => 'success'],
];
?>

<?php if (!empty($_SESSION['success'])): ?>
    <div class="alert alert-success border-0 shadow-sm rounded-4 mb-3">
        <i class="fa fa-check-circle me-1"></i>
        <?= ad_h($_SESSION['success']) ?>
    </div>
    <?php unset($_SESSION['success']); ?>
<?php endif; ?>

<?php if (!empty($_SESSION['error'])): ?>
    <div class="alert alert-danger border-0 shadow-sm rounded-4 mb-3">
        <i class="fa fa-triangle-exclamation me-1"></i>
        <?= ad_h($_SESSION['error']) ?>
    </div>
    <?php unset($_SESSION['error']); ?>
<?php endif; ?>

<style>
    .ad-wrap{
        direction:<?= $dir ?>;
        text-align:<?= $textAlign ?>;
        font-family:'Cairo','Almarai','Tajawal',system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;
        color:#0f172a;
    }
    .ad-wrap *{box-sizing:border-box;}
    .ad-hero{
        position:relative;
        overflow:hidden;
        border-radius:30px;
        background:linear-gradient(135deg,#0f172a 0%,#1e3a8a 52%,#2563eb 100%);
        color:#fff;
        box-shadow:0 24px 60px rgba(15,23,42,.18);
    }
    .ad-hero:before,.ad-hero:after{content:"";position:absolute;border-radius:999px;background:rgba(255,255,255,.09);}
    .ad-hero:before{width:280px;height:280px;top:-120px;<?= $isArabic ? 'left' : 'right' ?>:-80px;}
    .ad-hero:after{width:180px;height:180px;bottom:-90px;<?= $isArabic ? 'right' : 'left' ?>:12%;}
    .ad-hero-body{position:relative;z-index:2;padding:34px;}
    .ad-eyebrow{font-size:13px;font-weight:900;letter-spacing:.06em;text-transform:uppercase;opacity:.78;}
    .ad-title{font-size:clamp(26px,3vw,42px);font-weight:950;line-height:1.25;margin:8px 0 10px;}
    .ad-subtitle{opacity:.85;font-size:16px;}
    .ad-chip{display:inline-flex;align-items:center;gap:8px;border-radius:999px;padding:10px 15px;font-weight:900;background:rgba(255,255,255,.14);border:1px solid rgba(255,255,255,.22);color:#fff;backdrop-filter:blur(8px);}
    .ad-card{border:0;border-radius:24px;background:#fff;box-shadow:0 16px 42px rgba(15,23,42,.08);}
    .ad-card-soft{border:1px solid #e2e8f0;border-radius:22px;background:linear-gradient(180deg,#fff,#f8fafc);}
    .ad-section-title{font-weight:950;margin:0;color:#0f172a;}
    .ad-section-subtitle{color:#64748b;font-size:13px;margin-top:4px;}
    .ad-toolbar{display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap;}
    .ad-search{position:relative;min-width:min(420px,100%);}
    .ad-search input{border-radius:999px;border:1px solid #dbe4ef;padding:11px 18px 11px 42px;font-weight:700;background:#f8fafc;width:100%;}
    .ad-search i{position:absolute;left:16px;top:50%;transform:translateY(-50%);color:#64748b;}
    [dir="rtl"] .ad-search input{padding-right:42px;padding-left:18px;}
    [dir="rtl"] .ad-search i{right:16px;left:auto;}
    .ad-table{border-collapse:separate;border-spacing:0 12px;margin-bottom:0;}
    .ad-table thead th{border:0;color:#64748b;font-size:12px;text-transform:uppercase;letter-spacing:.04em;background:#f8fafc;padding:13px 14px;white-space:nowrap;}
    .ad-table tbody tr{box-shadow:0 8px 28px rgba(15,23,42,.07);border-radius:18px;}
    .ad-table tbody td{background:#fff;border-top:1px solid #eef2f7;border-bottom:1px solid #eef2f7;padding:16px 14px;vertical-align:middle;}
    .ad-table tbody td:first-child{border-<?= $isArabic ? 'right' : 'left' ?>:1px solid #eef2f7;border-radius:0 18px 18px 0;}
    .ad-table tbody td:last-child{border-<?= $isArabic ? 'left' : 'right' ?>:1px solid #eef2f7;border-radius:18px 0 0 18px;}
    [dir="ltr"] .ad-table tbody td:first-child{border-radius:18px 0 0 18px;}
    [dir="ltr"] .ad-table tbody td:last-child{border-radius:0 18px 18px 0;}
    .ad-badge{display:inline-flex;align-items:center;gap:6px;border-radius:999px;padding:7px 11px;font-size:12px;font-weight:950;white-space:nowrap;}
    .ad-badge-primary{background:#dbeafe;color:#1d4ed8;}
    .ad-badge-success{background:#dcfce7;color:#166534;}
    .ad-badge-danger{background:#fee2e2;color:#991b1b;}
    .ad-badge-warning{background:#fef3c7;color:#92400e;}
    .ad-badge-info{background:#e0f2fe;color:#075985;}
    .ad-badge-muted{background:#f1f5f9;color:#475569;}
    .ad-badge-soft{background:#eef2ff;color:#3730a3;}
    .ad-progress{height:8px;border-radius:999px;background:#e2e8f0;overflow:hidden;min-width:120px;}
    .ad-progress span{display:block;height:100%;border-radius:999px;background:linear-gradient(90deg,#2563eb,#22c55e);}
    .ad-kpi{height:100%;padding:20px;border-radius:22px;background:#fff;border:1px solid #e2e8f0;box-shadow:0 12px 34px rgba(15,23,42,.06);}
    .ad-kpi-icon{width:48px;height:48px;border-radius:16px;display:flex;align-items:center;justify-content:center;background:#eff6ff;color:#1d4ed8;font-size:20px;margin-bottom:14px;}
    .ad-kpi-value{font-size:31px;font-weight:950;line-height:1;color:#0f172a;}
    .ad-kpi-label{color:#64748b;font-size:13px;font-weight:900;margin-top:6px;}
    .ad-pill{display:inline-flex;align-items:center;gap:8px;border-radius:999px;padding:9px 13px;font-weight:950;background:#eff6ff;color:#1e3a8a;border:1px solid #bfdbfe;font-size:13px;}
    .ad-pill.off{background:#f8fafc;color:#64748b;border-color:#e2e8f0;}
    .ad-action-stack{display:flex;gap:7px;flex-wrap:wrap;justify-content:flex-start;}
    .ad-action-stack .btn{border-radius:999px;font-weight:900;}
    .ad-mini-row{padding:14px;border:1px solid #e2e8f0;border-radius:18px;background:#fff;margin-bottom:12px;}
    .ad-mini-title{font-weight:950;color:#0f172a;line-height:1.45;}
    .ad-empty{padding:34px;border:1px dashed #cbd5e1;border-radius:22px;background:#f8fafc;color:#64748b;text-align:center;font-weight:800;}
    .ad-deadline{border-radius:20px;border:1px solid #e2e8f0;background:#fff;padding:17px;height:100%;}
    .ad-deadline-icon{width:50px;height:50px;border-radius:16px;display:flex;align-items:center;justify-content:center;color:#fff;background:#2563eb;font-size:20px;}
    .ad-readiness{font-size:48px;font-weight:950;color:#2563eb;line-height:1;}
    .ad-timeline{display:flex;gap:10px;flex-wrap:wrap;align-items:center;}
    .ad-timeline-step{display:flex;align-items:center;gap:10px;}
    .ad-timeline-node{width:36px;height:36px;border-radius:999px;display:flex;align-items:center;justify-content:center;font-weight:950;background:#dbeafe;color:#1d4ed8;border:1px solid #bfdbfe;}
    .ad-timeline-step.off .ad-timeline-node{background:#f1f5f9;color:#94a3b8;border-color:#e2e8f0;}
    .ad-timeline-label{font-size:12px;font-weight:950;color:#334155;}
    .ad-timeline-step.off .ad-timeline-label{color:#94a3b8;}
    @media (max-width: 768px){
        .ad-hero-body{padding:24px;}
        .ad-table{border-spacing:0;}
        .ad-table thead{display:none;}
        .ad-table tbody tr{display:block;margin-bottom:14px;box-shadow:0 10px 30px rgba(15,23,42,.08);border-radius:18px;background:#fff;}
        .ad-table tbody td{display:flex;justify-content:space-between;gap:16px;border:0!important;border-bottom:1px solid #eef2f7!important;border-radius:0!important;}
        .ad-table tbody td:before{content:attr(data-label);font-weight:950;color:#64748b;min-width:110px;}
        .ad-action-stack{justify-content:flex-end;}
    }
</style>

<div class="container-fluid ad-wrap py-3" dir="<?= ad_h($dir) ?>">

    <div class="ad-hero mb-4">
        <div class="ad-hero-body">
            <div class="d-flex justify-content-between align-items-start flex-wrap gap-4">
                <div class="flex-grow-1">
                    <div class="ad-eyebrow">
                        <?= $isArabic ? 'مساحة المؤلف' : 'Author Workspace' ?>
                    </div>
                    <h1 class="ad-title"><?= ad_h($confTitle) ?></h1>
                    <div class="ad-subtitle">
                        <?= $isArabic ? 'إدارة الأبحاث والتحكيم والنسخ النهائية من لوحة واحدة' : 'Manage submissions, reviews, revisions, and publication readiness from one workspace' ?>
                    </div>
                    <div class="mt-4 d-flex flex-wrap gap-2">
                        <span class="ad-chip"><i class="fa fa-file-lines"></i><?= $totalSubmissions ?> <?= $isArabic ? 'بحث' : 'Submissions' ?></span>
                        <span class="ad-chip"><i class="fa fa-check-circle"></i><?= $acceptedCount ?> <?= $isArabic ? 'مقبول' : 'Accepted' ?></span>
                        <span class="ad-chip"><i class="fa fa-rotate"></i><?= $pendingRevision ?> <?= $isArabic ? 'تعديل' : 'Revisions' ?></span>
                    </div>
                </div>
                <div class="d-flex flex-column gap-2">
                    <a class="btn btn-light btn-lg rounded-pill fw-bold" href="/easychair/author/submit">
                        <i class="fa fa-file-circle-plus"></i>
                        <?= $isArabic ? 'إرسال بحث جديد' : 'Submit New Paper' ?>
                    </a>
                    <a class="btn btn-outline-light rounded-pill fw-bold" href="/easychair/conference/<?= ad_h(urlencode((string)$conferenceSlug)) ?>">
                        <i class="fa fa-house"></i>
                        <?= $isArabic ? 'صفحة المؤتمر' : 'Conference Homepage' ?>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <?php if ($pendingRevision > 0): ?>
        <div class="alert alert-warning border-0 shadow-sm rounded-4 mb-4">
            <i class="fa fa-rotate me-1"></i>
            <?= $isArabic ? 'لديك ' . $pendingRevision . ' بحث يحتاج إلى تعديل.' : 'You have ' . $pendingRevision . ' submissions requiring revision.' ?>
        </div>
    <?php endif; ?>

    <?php if ($acceptedCount > 0): ?>
        <div class="alert alert-success border-0 shadow-sm rounded-4 mb-4">
            <i class="fa fa-check-circle me-1"></i>
            <?= $isArabic ? 'تهانينا! لديك ' . $acceptedCount . ' بحث مقبول.' : 'Congratulations! You have ' . $acceptedCount . ' accepted submissions.' ?>
        </div>
    <?php endif; ?>

    <!-- SUBMISSIONS FIRST: requested top position -->
    <div class="ad-card mb-4" id="author-submissions-top">
        <div class="card-body p-4">
            <div class="ad-toolbar mb-3">
                <div>
                    <h3 class="ad-section-title">
                        <i class="fa fa-layer-group text-primary"></i>
                        <?= $isArabic ? 'أبحاثي' : 'My Submissions' ?>
                    </h3>
                    <div class="ad-section-subtitle">
                        <?= $isArabic ? 'قائمة التقديمات في أعلى لوحة المؤلف مع إجراءات سريعة.' : 'Submission list is now at the top with quick actions.' ?>
                    </div>
                </div>
                <div class="d-flex gap-2 flex-wrap align-items-center">
                    <div class="ad-search">
                        <i class="fa fa-search"></i>
                        <input type="search" id="adSubmissionSearch" placeholder="<?= $isArabic ? 'بحث في العنوان أو رقم التقديم...' : 'Search title or submission number...' ?>">
                    </div>
                    <select id="adStatusFilter" class="form-select rounded-pill fw-bold" style="max-width:220px;">
                        <option value=""><?= $isArabic ? 'كل الحالات' : 'All Statuses' ?></option>
                        <?php
                        $statusOptions = array_unique(array_filter(array_map(static fn($s) => (string)($s['status'] ?? ''), $submissions)));
                        sort($statusOptions);
                        foreach ($statusOptions as $statusOption):
                        ?>
                            <option value="<?= ad_h(strtolower($statusOption)) ?>"><?= ad_h(ad_status_label($statusOption, $isArabic)) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <a class="btn btn-primary rounded-pill fw-bold" href="/easychair/author/submit">
                        <i class="fa fa-plus"></i>
                        <?= $isArabic ? 'بحث جديد' : 'New Paper' ?>
                    </a>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table ad-table align-middle" id="adSubmissionTable">
                    <thead>
                    <tr>
                        <th><?= $isArabic ? 'البحث' : 'Paper' ?></th>
                        <th><?= $isArabic ? 'رقم التقديم' : 'Submission No.' ?></th>
                        <th><?= $isArabic ? 'الحالة' : 'Status' ?></th>
                        <th><?= $isArabic ? 'المرحلة' : 'Stage' ?></th>
                        <th><?= $isArabic ? 'المراجعات' : 'Reviews' ?></th>
                        <th><?= $isArabic ? 'المعدل' : 'Average' ?></th>
                        <th><?= $isArabic ? 'القرار' : 'Decision' ?></th>
                        <th><?= $isArabic ? 'الملفات' : 'Files' ?></th>
                        <th><?= $isArabic ? 'آخر تحديث' : 'Last Update' ?></th>
                        <th><?= $isArabic ? 'الإجراءات' : 'Actions' ?></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($submissions as $s): ?>
                        <?php
                        $sid = (int)($s['id'] ?? $s['submission_id'] ?? 0);
                        $status = (string)($s['status'] ?? '');
                        $stage = (string)($s['stage'] ?? '');
                        $progress = ad_submission_progress($status, $stage);
                        $title = ad_submission_title($s);
                        $searchText = strtolower(trim(($s['submission_no'] ?? '') . ' ' . $title . ' ' . $status . ' ' . $stage));
                        ?>
                        <tr data-status="<?= ad_h(strtolower($status)) ?>" data-search="<?= ad_h($searchText) ?>">
                            <td data-label="<?= $isArabic ? 'البحث' : 'Paper' ?>" style="min-width:300px;">
                                <div class="ad-mini-title"><?= ad_h($title) ?></div>
                                <?php if (!empty($s['keywords']) || !empty($s['keywords_ar'])): ?>
                                    <div class="small text-muted mt-1">
                                        <i class="fa fa-tags"></i>
                                        <?= ad_h(($s['keywords_ar'] ?? '') ?: ($s['keywords'] ?? '')) ?>
                                    </div>
                                <?php endif; ?>
                                <div class="small text-muted mt-1">
                                    ID: <?= $sid ?: '-' ?>
                                </div>
                            </td>
                            <td data-label="<?= $isArabic ? 'رقم التقديم' : 'Submission No.' ?>">
                                <span class="ad-badge ad-badge-muted"><?= ad_h($s['submission_no'] ?? ('#' . $sid)) ?></span>
                            </td>
                            <td data-label="<?= $isArabic ? 'الحالة' : 'Status' ?>">
                                <span class="ad-badge <?= ad_status_badge_class($status) ?>">
                                    <?= ad_h(ad_status_label($status, $isArabic)) ?>
                                </span>
                            </td>
                            <td data-label="<?= $isArabic ? 'المرحلة' : 'Stage' ?>" style="min-width:180px;">
                                <div class="fw-bold small mb-1"><?= ad_h($stage ?: '-') ?></div>
                                <div class="ad-progress"><span style="width:<?= $progress ?>%"></span></div>
                                <div class="small text-muted mt-1"><?= $progress ?>%</div>
                            </td>
                            <td data-label="<?= $isArabic ? 'المراجعات' : 'Reviews' ?>">
                                <span class="ad-badge ad-badge-primary"><?= (int)($s['reviews_count'] ?? 0) ?></span>
                            </td>
                            <td data-label="<?= $isArabic ? 'المعدل' : 'Average' ?>">
                                <?= ad_h(($s['avg_score'] ?? '') ?: (($s['reviews_avg_score'] ?? '') ?: '-')) ?>
                            </td>
                            <td data-label="<?= $isArabic ? 'القرار' : 'Decision' ?>">
                                <?= ad_h($s['decision'] ?? '-') ?>
                            </td>
                            <td data-label="<?= $isArabic ? 'الملفات' : 'Files' ?>" style="min-width:160px;">
                                <div class="d-flex flex-column gap-1">
                                    <?php if (!empty($s['file_path'])): ?>
                                        <a class="btn btn-sm btn-outline-primary rounded-pill fw-bold" target="_blank" href="<?= ad_h(ad_file_url($s['file_path'])) ?>">
                                            <i class="fa fa-file-arrow-down"></i>
                                            <?= $isArabic ? 'الأصلي' : 'Original' ?>
                                        </a>
                                    <?php endif; ?>
                                    <?php if (!empty($s['revision_file'])): ?>
                                        <a class="btn btn-sm btn-outline-warning rounded-pill fw-bold" target="_blank" href="<?= ad_h(ad_file_url($s['revision_file'])) ?>">
                                            <i class="fa fa-upload"></i>
                                            <?= $isArabic ? 'التعديل' : 'Revision' ?>
                                        </a>
                                    <?php endif; ?>
                                    <?php if (!empty($s['response_letter_path'])): ?>
                                        <a class="btn btn-sm btn-outline-success rounded-pill fw-bold" target="_blank" href="<?= ad_h(ad_file_url($s['response_letter_path'])) ?>">
                                            <i class="fa fa-comments"></i>
                                            <?= $isArabic ? 'خطاب الرد' : 'Response' ?>
                                        </a>
                                    <?php endif; ?>
                                    <?php if (empty($s['file_path']) && empty($s['revision_file']) && empty($s['response_letter_path'])): ?>
                                        <span class="text-muted small"><?= $isArabic ? 'لا يوجد' : 'None' ?></span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td data-label="<?= $isArabic ? 'آخر تحديث' : 'Last Update' ?>">
                                <div class="small fw-bold"><?= ad_h($s['updated_at'] ?? $s['submitted_at'] ?? $s['created_at'] ?? '-') ?></div>
                                <div class="small text-muted"><?= $isArabic ? 'الجولة' : 'Round' ?> <?= (int)($s['current_round_no'] ?? 1) ?></div>
                            </td>
                            <td data-label="<?= $isArabic ? 'الإجراءات' : 'Actions' ?>" style="min-width:220px;">
                                <div class="ad-action-stack">
                                    <?php if ($sid > 0): ?>
                                        <a class="btn btn-sm btn-primary" href="/easychair/author/submission/show?id=<?= $sid ?>">
                                            <i class="fa fa-eye"></i>
                                            <?= $isArabic ? 'تفاصيل' : 'Details' ?>
                                        </a>
                                        <a class="btn btn-sm btn-outline-primary" href="/easychair/author/workflow?submission_id=<?= $sid ?>">
                                            <i class="fa fa-diagram-project"></i>
                                            <?= function_exists('ec_t') ? ad_h(ec_t('author.dashboard.workflow','Workflow')) : ($isArabic ? 'المسار' : 'Workflow') ?>
                                        </a>
                                        <?php if (((int)($s['reviews_count'] ?? 0)) > 0): ?>
                                            <a class="btn btn-sm btn-outline-dark" href="/easychair/author/submission/reviews?id=<?= $sid ?>">
                                                <i class="fa fa-comments"></i>
                                                <?= $isArabic ? 'المراجعات' : 'Reviews' ?>
                                            </a>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>

                    <?php if (empty($submissions)): ?>
                        <tr>
                            <td colspan="10">
                                <div class="ad-empty">
                                    <i class="fa fa-inbox fa-2x d-block mb-3"></i>
                                    <?= $isArabic ? 'لا توجد تقديمات لهذا المؤلف في المؤتمر الحالي.' : 'No submissions for this author in the current conference.' ?>
                                    <div class="mt-3">
                                        <a class="btn btn-primary rounded-pill fw-bold" href="/easychair/author/submit">
                                            <?= $isArabic ? 'تقديم أول بحث' : 'Submit First Paper' ?>
                                        </a>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="row g-3 mb-4">
        <?php foreach ($kpiCards as $card): ?>
            <div class="col-xl-2 col-md-4 col-6">
                <div class="ad-kpi">
                    <div class="ad-kpi-icon"><i class="fa <?= ad_h($card['icon']) ?>"></i></div>
                    <div class="ad-kpi-value"><?= (int)$card['value'] ?></div>
                    <div class="ad-kpi-label"><?= ad_h($isArabic ? $card['label_ar'] : $card['label_en']) ?></div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <?php if (!empty($deadlineCards)): ?>
        <div class="row g-3 mb-4">
            <?php foreach ($deadlineCards as $d): ?>
                <div class="col-lg-4">
                    <div class="ad-deadline d-flex align-items-center gap-3">
                        <div class="ad-deadline-icon"><i class="fa <?= ad_h($d['icon']) ?>"></i></div>
                        <div>
                            <div class="fw-bold"><?= ad_h($d['title']) ?></div>
                            <div class="text-muted"><?= ad_h($d['date']) ?></div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <div class="row g-4 mb-4">
        <div class="col-xl-8">
            <div class="ad-card h-100">
                <div class="card-body p-4">
                    <h4 class="ad-section-title mb-3">
                        <i class="fa fa-route text-primary"></i>
                        <?= $isArabic ? 'مراحل سير العمل' : 'Workflow Progress' ?>
                    </h4>
                    <div class="ad-timeline">
                        <?php $stepNo = 1; foreach ($workflowLabels as $k => $label): ?>
                            <?php $enabled = !empty($workflow[$k]); ?>
                            <div class="ad-timeline-step <?= $enabled ? '' : 'off' ?>">
                                <div class="ad-timeline-node"><?= $enabled ? '✓' : $stepNo ?></div>
                                <div class="ad-timeline-label"><?= ad_h($isArabic ? $label['ar'] : $label['en']) ?></div>
                            </div>
                            <?php $stepNo++; ?>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-4">
            <div class="ad-card h-100">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-start gap-3">
                        <div>
                            <h4 class="ad-section-title"><?= $isArabic ? 'جاهزية النشر' : 'Publication Readiness' ?></h4>
                            <div class="ad-section-subtitle"><?= $isArabic ? 'تتبع جاهزية النسخة النهائية' : 'Track final publication readiness' ?></div>
                        </div>
                        <div class="ad-readiness"><?= (int)($publicationReadiness['ready_score'] ?? 0) ?>%</div>
                    </div>
                    <div class="ad-progress my-3" style="height:11px;"><span style="width:<?= (int)($publicationReadiness['ready_score'] ?? 0) ?>%"></span></div>
                    <div class="row g-2 text-center">
                        <div class="col-4"><div class="ad-card-soft p-3"><div class="fw-bold fs-4"><?= ad_count($publicationReadiness['accepted'] ?? []) ?></div><small><?= $isArabic ? 'مقبولة' : 'Accepted' ?></small></div></div>
                        <div class="col-4"><div class="ad-card-soft p-3"><div class="fw-bold fs-4"><?= ad_count($publicationReadiness['camera_ready'] ?? []) ?></div><small>Camera Ready</small></div></div>
                        <div class="col-4"><div class="ad-card-soft p-3"><div class="fw-bold fs-4"><?= ad_count($publicationReadiness['blockers'] ?? []) ?></div><small><?= $isArabic ? 'عوائق' : 'Blockers' ?></small></div></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="ad-card mb-4">
        <div class="card-body p-4">
            <h4 class="ad-section-title mb-3">
                <i class="fa fa-gauge-high text-primary"></i>
                <?= $isArabic ? 'مركز أوامر المؤلف' : 'Author Command Center' ?>
            </h4>
            <div class="row g-3">
                <?php
                $commandCards = [
                    [$isArabic ? 'التعديلات' : 'Revisions', $workflowSummary['revision_queue'], 'fa-rotate', 'warning'],
                    [$isArabic ? 'القرارات' : 'Pending Decisions', $workflowSummary['decision_pending'], 'fa-scale-balanced', 'primary'],
                    [$isArabic ? 'المراجعات' : 'Unread Reviews', $workflowSummary['unread_reviews'], 'fa-comments', 'info'],
                    [$isArabic ? 'جاهز للنشر' : 'Camera Ready', $workflowSummary['camera_ready'], 'fa-file-circle-check', 'success'],
                ];
                foreach ($commandCards as $c):
                ?>
                    <div class="col-lg-3 col-md-6">
                        <div class="ad-card-soft p-4 text-center h-100">
                            <div class="display-6 fw-bold text-primary"><i class="fa <?= ad_h($c[2]) ?> small"></i> <?= (int)$c[1] ?></div>
                            <div class="text-muted fw-bold"><?= ad_h($c[0]) ?></div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <div class="row g-4 mb-4">
        <div class="col-lg-6">
            <div class="ad-card h-100">
                <div class="card-body p-4">
                    <h4 class="ad-section-title mb-3"><i class="fa fa-rotate text-warning"></i> <?= $isArabic ? 'مركز التعديلات' : 'Revision Center' ?></h4>
                    <?php if (!empty($revisionRows)): ?>
                        <?php foreach (array_slice($revisionRows, 0, 5) as $r): ?>
                            <?php $rid = (int)($r['id'] ?? $r['submission_id'] ?? 0); ?>
                            <div class="ad-mini-row">
                                <div class="ad-mini-title"><?= ad_h(ad_submission_title($r)) ?></div>
                                <div class="small text-muted mb-3"><?= ad_h(ad_status_label($r['status'] ?? '', $isArabic)) ?></div>
                                <?php if ($rid > 0): ?>
                                    <a class="btn btn-warning btn-sm rounded-pill fw-bold" href="/easychair/author/workflow?submission_id=<?= $rid ?>">
                                        <i class="fa fa-upload"></i> <?= $isArabic ? 'فتح التعديل' : 'Open Revision' ?>
                                    </a>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="ad-empty"><?= $isArabic ? 'لا توجد تعديلات مطلوبة حالياً' : 'No revisions required' ?></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="ad-card h-100">
                <div class="card-body p-4">
                    <h4 class="ad-section-title mb-3"><i class="fa fa-comments text-primary"></i> <?= $isArabic ? 'ملخص التحكيم' : 'Review Summary' ?></h4>
                    <?php if (!empty($reviewRows)): ?>
                        <?php foreach (array_slice($reviewRows, 0, 5) as $r): ?>
                            <?php $rid = (int)($r['id'] ?? $r['submission_id'] ?? 0); ?>
                            <div class="ad-mini-row">
                                <div class="ad-mini-title"><?= ad_h(ad_submission_title($r)) ?></div>
                                <div class="small text-muted mb-2"><?= $isArabic ? 'عدد المراجعات' : 'Reviews' ?>: <?= (int)($r['reviews_count'] ?? 0) ?></div>
                                <div class="small text-muted mb-3"><?= $isArabic ? 'المعدل' : 'Average' ?>: <?= ad_h(($r['reviews_avg_score'] ?? $r['avg_score'] ?? '-') ?: '-') ?></div>
                                <?php if ($rid > 0): ?>
                                    <a class="btn btn-outline-primary btn-sm rounded-pill fw-bold" href="/easychair/author/submission/reviews?id=<?= $rid ?>">
                                        <i class="fa fa-eye"></i> <?= $isArabic ? 'عرض المراجعات' : 'View Reviews' ?>
                                    </a>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="ad-empty"><?= $isArabic ? 'لا توجد مراجعات منشورة' : 'No published reviews' ?></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 mb-4">
        <?php
        $workspacePanels = [
            ['label' => $isArabic ? 'إعادة الرفع' : 'Reupload', 'key' => 'reupload', 'icon' => 'fa-upload', 'btn' => $isArabic ? 'Upload' : 'Upload'],
            ['label' => $isArabic ? 'الرد على المراجعات' : 'Review Response', 'key' => 'response', 'icon' => 'fa-comments', 'btn' => $isArabic ? 'فتح' : 'Open'],
            ['label' => $isArabic ? 'الإصدارات الجاهزة' : 'Camera Ready', 'key' => 'camera', 'icon' => 'fa-file-circle-check', 'btn' => $isArabic ? 'فتح' : 'Open'],
        ];
        foreach ($workspacePanels as $panel):
        ?>
            <div class="col-lg-4">
                <div class="ad-card h-100">
                    <div class="card-body p-4">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="ad-section-title fs-5"><i class="fa <?= ad_h($panel['icon']) ?> text-primary"></i> <?= ad_h($panel['label']) ?></h5>
                            <span class="ad-badge ad-badge-primary"><?= ad_count($submissionWorkspace[$panel['key']] ?? []) ?></span>
                        </div>
                        <?php $items = array_slice($submissionWorkspace[$panel['key']] ?? [], 0, 3); ?>
                        <?php if (!empty($items)): ?>
                            <?php foreach ($items as $x): ?>
                                <?php $xid = (int)($x['id'] ?? $x['submission_id'] ?? 0); ?>
                                <div class="ad-mini-row">
                                    <div class="ad-mini-title"><?= ad_h(ad_submission_title($x)) ?></div>
                                    <div class="small text-muted mb-2"><?= ad_h(ad_status_label($x['status'] ?? '', $isArabic)) ?></div>
                                    <?php if ($xid > 0): ?>
                                        <a class="btn btn-sm btn-outline-primary rounded-pill fw-bold" href="/easychair/author/workflow?submission_id=<?= $xid ?>"><?= ad_h($panel['btn']) ?></a>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="ad-empty py-4"><?= $isArabic ? 'لا يوجد عناصر' : 'No items' ?></div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <div class="ad-card mb-4">
        <div class="card-body p-4">
            <h4 class="ad-section-title mb-3"><i class="fa fa-magnifying-glass-chart text-primary"></i> <?= $isArabic ? 'مستكشف المراجعات' : 'Review Explorer' ?></h4>
            <div class="row g-3">
                <?php
                $reviewGroups = [
                    ['decision_ready', $isArabic ? 'جاهز للقرار' : 'Decision Ready', 'ad-badge-success'],
                    ['version_ready', $isArabic ? 'مقارنة الإصدارات' : 'Version Compare', 'ad-badge-warning'],
                    ['needs_response', $isArabic ? 'بانتظار الرد' : 'Response Required', 'ad-badge-primary'],
                    ['accepted', $isArabic ? 'مقبول' : 'Accepted', 'ad-badge-muted'],
                ];
                foreach ($reviewGroups as $g):
                ?>
                    <div class="col-lg-3 col-md-6">
                        <div class="ad-card-soft p-3 h-100">
                            <span class="ad-badge <?= ad_h($g[2]) ?> mb-3"><?= ad_count($reviewExplorer[$g[0]] ?? []) ?></span>
                            <h6 class="fw-bold"><?= ad_h($g[1]) ?></h6>
                            <?php foreach (array_slice($reviewExplorer[$g[0]] ?? [], 0, 3) as $x): ?>
                                <div class="small mb-3 border-top pt-2">
                                    <div class="fw-bold"><?= ad_h(ad_submission_title($x)) ?></div>
                                    <div class="text-muted"><?= ad_h(ad_status_label($x['status'] ?? '', $isArabic)) ?></div>
                                </div>
                            <?php endforeach; ?>
                            <?php if (empty($reviewExplorer[$g[0]] ?? [])): ?>
                                <div class="text-muted small"><?= $isArabic ? 'لا يوجد عناصر' : 'No items' ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <div class="row g-4 mb-4">
        <div class="col-lg-6">
            <div class="ad-card h-100">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <h4 class="ad-section-title"><i class="fa fa-award text-success"></i> <?= $isArabic ? 'رحلة القبول' : 'Acceptance Journey' ?></h4>
                            <div class="ad-section-subtitle"><?= $isArabic ? 'متابعة الأبحاث المقبولة والنشر' : 'Track accepted submissions and publication path' ?></div>
                        </div>
                        <span class="ad-badge ad-badge-success"><?= ad_count($publicationReadiness['accepted'] ?? []) ?></span>
                    </div>
                    <?php $acceptedJourney = array_slice($publicationReadiness['accepted'] ?? [], 0, 10); ?>
                    <?php if (!empty($acceptedJourney)): ?>
                        <?php foreach ($acceptedJourney as $x): ?>
                            <?php
                            $xid = (int)($x['id'] ?? $x['submission_id'] ?? 0);
                            $cameraReady = !empty($x['camera_ready_file']) || !empty($x['final_file']);
                            ?>
                            <div class="ad-mini-row border-start border-4 border-success">
                                <div class="ad-mini-title"><?= ad_h(ad_submission_title($x)) ?></div>
                                <div class="small text-muted mb-2"><?= ad_h(ad_status_label($x['status'] ?? '', $isArabic)) ?></div>
                                <span class="ad-badge <?= $cameraReady ? 'ad-badge-success' : 'ad-badge-warning' ?>">
                                    <?= $cameraReady ? ($isArabic ? 'النسخة النهائية جاهزة' : 'Camera Ready') : ($isArabic ? 'بانتظار النسخة النهائية' : 'Awaiting Final Version') ?>
                                </span>
                                <?php if (!empty($x['published_at'])): ?>
                                    <span class="ad-badge ad-badge-primary"><?= $isArabic ? 'منشور' : 'Published' ?></span>
                                <?php endif; ?>
                                <?php if ($xid > 0): ?>
                                    <div class="mt-3 ad-action-stack">
                                        <a class="btn btn-sm btn-outline-primary" href="/easychair/author/submission/show?id=<?= $xid ?>"><?= $isArabic ? 'فتح' : 'Open' ?></a>
                                        <?php if (!$cameraReady): ?>
                                            <a class="btn btn-sm btn-warning" href="/easychair/author/workflow?submission_id=<?= $xid ?>"><?= $isArabic ? 'رفع النسخة النهائية' : 'Upload Final' ?></a>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="ad-empty"><i class="fa fa-award fa-2x d-block mb-3"></i><?= $isArabic ? 'لا توجد أبحاث مقبولة حتى الآن' : 'No accepted submissions yet' ?></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="ad-card h-100">
                <div class="card-body p-4">
                    <h4 class="ad-section-title mb-3"><i class="fa fa-users text-primary"></i> <?= $isArabic ? 'مساحة تعاون المؤلفين' : 'Collaboration Workspace' ?></h4>
                    <div class="row g-2 mb-3 text-center">
                        <?php
                        $collabCards = [
                            ['multi_author', $isArabic ? 'مشاريع مشتركة' : 'Shared Papers'],
                            ['needs_coordination', $isArabic ? 'بحاجة لتنسيق' : 'Needs Coordination'],
                            ['governance_alert', $isArabic ? 'تنبيهات' : 'Governance'],
                            ['ready_to_submit', $isArabic ? 'جاهزة' : 'Ready'],
                        ];
                        foreach ($collabCards as $c):
                        ?>
                            <div class="col-6 col-md-3"><div class="ad-card-soft p-3"><div class="fw-bold fs-4"><?= ad_count($collaborationWorkspace[$c[0]] ?? []) ?></div><small><?= ad_h($c[1]) ?></small></div></div>
                        <?php endforeach; ?>
                    </div>
                    <?php $coordinationRows = array_slice($collaborationWorkspace['needs_coordination'] ?? [], 0, 4); ?>
                    <?php if (!empty($coordinationRows)): ?>
                        <?php foreach ($coordinationRows as $x): ?>
                            <?php $xid = (int)($x['id'] ?? $x['submission_id'] ?? 0); ?>
                            <div class="ad-mini-row">
                                <div class="ad-mini-title"><?= ad_h(ad_submission_title($x)) ?></div>
                                <div class="small text-muted mb-2"><?= $isArabic ? 'عدد المؤلفين' : 'Authors' ?>: <?= (int)($x['authors_count'] ?? 1) ?></div>
                                <?php if ($xid > 0): ?><a class="btn btn-sm btn-outline-primary rounded-pill fw-bold" href="/easychair/author/submission/show?id=<?= $xid ?>"><?= $isArabic ? 'فتح' : 'Open' ?></a><?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="ad-empty py-4"><?= $isArabic ? 'لا توجد عناصر تحتاج إلى تنسيق حالياً' : 'No coordination items currently' ?></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

</div>

<script>
(function(){
    const search = document.getElementById('adSubmissionSearch');
    const filter = document.getElementById('adStatusFilter');
    const rows = Array.from(document.querySelectorAll('#adSubmissionTable tbody tr[data-search]'));

    function applyFilters(){
        const q = (search && search.value ? search.value : '').toLowerCase().trim();
        const st = (filter && filter.value ? filter.value : '').toLowerCase().trim();
        rows.forEach(function(row){
            const haystack = row.getAttribute('data-search') || '';
            const status = row.getAttribute('data-status') || '';
            const okSearch = !q || haystack.indexOf(q) !== -1;
            const okStatus = !st || status === st;
            row.style.display = (okSearch && okStatus) ? '' : 'none';
        });
    }

    if (search) search.addEventListener('input', applyFilters);
    if (filter) filter.addEventListener('change', applyFilters);
})();
</script>
