<?php
function sw_h($v) {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

$submission = $submission ?? [];
$versions = $versions ?? [];
$assignments = $assignments ?? [];
$reviews = $reviews ?? [];
$rebuttals = $rebuttals ?? [];
$galleys = $galleys ?? [];
$activity = $activity ?? [];

$title = ($submission['title'] ?? '') ?: (($submission['title_en'] ?? '') ?: (($submission['title_ar'] ?? '') ?: ('Submission #' . ($submission['id'] ?? ''))));
?>

<div class="container-fluid py-3">

    <div class="card border-0 shadow-sm mb-4" style="border-radius:24px;background:linear-gradient(135deg,#0f172a,#1d4ed8);color:#fff;">
        <div class="card-body p-4">
            <h3 class="fw-bold mb-1">
                <i class="fa fa-sitemap"></i>
                Submission Workflow Control
            </h3>
            <div class="opacity-75">
                <?= sw_h($submission['submission_no'] ?? '') ?> —
                <?= sw_h($title) ?>
            </div>
            <div class="mt-3">
                <span class="badge bg-light text-dark"><?= sw_h($submission['status'] ?? '') ?></span>
                <span class="badge bg-warning text-dark"><?= sw_h($submission['stage'] ?? '') ?></span>
                <span class="badge bg-info text-dark"><?= sw_h($submission['production_status'] ?? '') ?></span>
            </div>
        </div>
    </div>

    <div class="row g-4 mb-4">

        <div class="col-xl-4">
            <div class="card border-0 shadow-sm h-100" style="border-radius:22px;">
                <div class="card-body p-4">
                    <h5 class="fw-bold mb-3">Submission Info</h5>

                    <table class="table table-bordered">
                        <tr><th>ID</th><td><?= (int)$submission['id'] ?></td></tr>
                        <tr><th>No.</th><td><?= sw_h($submission['submission_no'] ?? '') ?></td></tr>
                        <tr><th>Author</th><td><?= sw_h(trim($submission['author_name'] ?? '') ?: ($submission['author_email'] ?? '')) ?></td></tr>
                        <tr><th>Organization</th><td><?= sw_h($submission['org_name'] ?? ('Org #' . ($submission['org_id'] ?? ''))) ?></td></tr>
                        <tr><th>Conference</th><td><?= sw_h(($submission['conference_short_name'] ?? '') . ' / #' . ($submission['conference_id'] ?? '')) ?></td></tr>
                        <tr><th>Email</th><td><?= sw_h($submission['author_email'] ?? '') ?></td></tr>
                        <tr><th>Decision</th><td><?= sw_h($submission['decision'] ?? '') ?></td></tr>
                        <tr><th>DOI</th><td><?= sw_h($submission['doi'] ?? '') ?></td></tr>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-xl-8">
            <div class="card border-0 shadow-sm h-100" style="border-radius:22px;">
                <div class="card-body p-4">
<?php

$assignedReviews =
    count($assignments);

$completedReviews = 0;

foreach ($assignments as $a) {

    if (
        !empty($a['completed_at'])
        ||
        strtolower(
            (string)($a['status'] ?? '')
        ) === 'completed'
    ) {
        $completedReviews++;
    }
}

$confidence =
    $assignedReviews > 0
    ? round(
        ($completedReviews / $assignedReviews) * 100
    )
    : 0;

$decisionColor = 'secondary';

switch (
    strtolower(
        (string)($submission['recommended_decision'] ?? '')
    )
) {

    case 'accept':
        $decisionColor = 'success';
        break;

    case 'minor_revision':
        $decisionColor = 'primary';
        break;

    case 'major_revision':
        $decisionColor = 'warning';
        break;

    case 'reject':
        $decisionColor = 'danger';
        break;
}

?>

<div
class="card border-0 shadow-sm mb-4"
style="
border-radius:22px;
background:
linear-gradient(
135deg,
#0f172a,
#1d4ed8
);
color:#fff;
">

<div class="card-body p-4">

<h5 class="fw-bold mb-4">

<i class="fa fa-brain"></i>

Decision Intelligence Center

</h5>

<div class="row g-3">

<div class="col-md-3">

<div class="p-3 rounded-4 bg-white text-dark">

<div class="small text-muted">

Average Score

</div>

<div class="fw-bold fs-3">

<?= number_format(
(float)($submission['avg_score'] ?? 0),
2
) ?>

</div>

</div>

</div>

<div class="col-md-3">

<div class="p-3 rounded-4 bg-white text-dark">

<div class="small text-muted">

Recommendation

</div>

<div class="mt-2">

<span
class="badge bg-<?= $decisionColor ?>"
style="font-size:14px;">

<?= sw_h(
$submission['recommended_decision']
?? 'pending'
) ?>

</span>

</div>

</div>

</div>

<div class="col-md-3">

<div class="p-3 rounded-4 bg-white text-dark">

<div class="small text-muted">

Review Progress

</div>

<div class="fw-bold fs-4">

<?= $completedReviews ?>

/

<?= $assignedReviews ?>

</div>

</div>

</div>

<div class="col-md-3">

<div class="p-3 rounded-4 bg-white text-dark">

<div class="small text-muted">

Confidence

</div>

<div class="fw-bold fs-3">

<?= $confidence ?>%

</div>

</div>

</div>

</div>

<?php if (
!empty(
$submission['decision_notes']
)
): ?>

<div
class="mt-4 p-3 rounded-4"
style="
background:
rgba(255,255,255,.12);
">

<strong>

AI / Workflow Notes

</strong>

<div class="mt-2">

<?= nl2br(
sw_h(
$submission['decision_notes']
)
) ?>

</div>

</div>

<?php endif; ?>

</div>

</div>

<?php

$autoStage = '';
$autoStatus = '';

switch (
    strtolower(
        (string)($submission['recommended_decision'] ?? '')
    )
) {

    case 'accept':

        $autoStage  = 'accepted';
        $autoStatus = 'accepted';

        break;

    case 'minor_revision':

        $autoStage  = 'revision_required';
        $autoStatus = 'revision_required';

        break;

    case 'major_revision':

        $autoStage  = 'revision_required';
        $autoStatus = 'revision_required';

        break;

    case 'reject':

        $autoStage  = 'rejected';
        $autoStatus = 'rejected';

        break;
}

?>

<?php if ($autoStage !== ''): ?>

<div class="mt-4 text-center">

<form
method="post"
action="/easychair/admin/submission-workflow/update"
onsubmit="
return confirm(
'Apply workflow recommendation?'
);
">

<input
type="hidden"
name="submission_id"
value="<?= (int)$submission['id'] ?>">

<input
type="hidden"
name="status"
value="<?= sw_h($autoStatus) ?>">

<input
type="hidden"
name="stage"
value="<?= sw_h($autoStage) ?>">

<input
type="hidden"
name="decision"
value="<?= sw_h(
$submission['recommended_decision']
) ?>">

<input
type="hidden"
name="decision_notes"
value="<?= sw_h(
'Applied automatically from Decision Intelligence Center. Avg Score: '
. ($submission['avg_score'] ?? 0)
) ?>">

<button
type="submit"
class="btn btn-success btn-lg px-5">

<i class="fa fa-bolt"></i>

Apply Recommendation

</button>

</form>

</div>

<?php endif; ?>

                    <h5 class="fw-bold mb-3">Update Workflow Stage</h5>

                    <form method="post" action="/easychair/admin/submission-workflow/update" class="row g-2">
                        <input type="hidden" name="submission_id" value="<?= (int)$submission['id'] ?>">

                        <div class="col-md-3">
                            <label class="form-label fw-bold">Status</label>
                            <select name="status" class="form-select">
                                <?php foreach (['submitted','under_review','revision_required','revision_submitted','accepted','rejected','camera_ready','production','assigned_to_issue','published'] as $s): ?>
                                    <option value="<?= sw_h($s) ?>" <?= (($submission['status'] ?? '') === $s) ? 'selected' : '' ?>>
                                        <?= sw_h($s) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-3">
                            <label class="form-label fw-bold">Stage</label>
                            <select name="stage" class="form-select">
                                <?php foreach (['submitted','screening','reviewing','rebuttal','revision_required','revision_submitted','accepted','rejected','camera_ready','production','galley','assigned_to_issue','issue','published'] as $s): ?>
                                    <option value="<?= sw_h($s) ?>" <?= (($submission['stage'] ?? '') === $s) ? 'selected' : '' ?>>
                                        <?= sw_h($s) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-3">
                            <label class="form-label fw-bold">Production</label>
                            <select name="production_status" class="form-select">
                                <?php foreach (['pending','camera_ready_uploaded','galley_uploaded','approved','published'] as $s): ?>
                                    <option value="<?= sw_h($s) ?>" <?= (($submission['production_status'] ?? '') === $s) ? 'selected' : '' ?>>
                                        <?= sw_h($s) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-3">
                            <label class="form-label fw-bold">Decision</label>
                            <select name="decision" class="form-select">
                                <?php foreach (['','accept','minor_revision','major_revision','reject','withdraw'] as $d): ?>
                                    <option value="<?= sw_h($d) ?>" <?= (($submission['decision'] ?? '') === $d) ? 'selected' : '' ?>>
                                        <?= $d === '' ? 'None' : sw_h($d) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-12">
                            <label class="form-label fw-bold">Decision / Workflow Notes</label>
                            <textarea name="decision_notes" rows="4" class="form-control"><?= sw_h($submission['decision_notes'] ?? '') ?></textarea>
                        </div>

                        <div class="col-12">
                            <label class="fw-bold">
                                <input type="checkbox" name="send_workflow_email" value="1" checked>
                                Send workflow notification email based on selected stage
                            </label>
                            <div class="text-muted small">
                                Rules can be managed from /admin/workflow-notifications.
                            </div>
                        </div>

                        <div class="col-12">
                            <button class="btn btn-success rounded-pill px-5">
                                <i class="fa fa-save"></i>
                                Save Workflow Update
                            </button>
                            <a class="btn btn-outline-secondary rounded-pill px-4" href="/easychair/admin/submissions">Back to Submissions</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

    </div>

    <div class="row g-4 mb-4">

        <div class="col-xl-6">
            <div class="card border-0 shadow-sm h-100" style="border-radius:22px;">
                <div class="card-body p-4">
                    <h5 class="fw-bold mb-3">Files / Versions</h5>

                    <div class="table-responsive">
                        <table class="table table-bordered align-middle">
                            <thead class="table-dark">
                                <tr>
                                    <th>Type</th>
                                    <th>Version</th>
                                    <th>File</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($versions as $v): ?>
                                <tr>
                                    <td><span class="badge bg-primary"><?= sw_h($v['upload_type'] ?? 'submission') ?></span></td>
                                    <td><?= (int)$v['version_no'] ?></td>
                                    <td>
                                        <?php if (!empty($v['file_path'])): ?>
                                            <a target="_blank" href="/easychair/storage/<?= sw_h($v['file_path']) ?>">
                                                <?= sw_h($v['original_filename'] ?: $v['file_path']) ?>
                                            </a>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= sw_h($v['created_at'] ?? '') ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (!$versions): ?>
                                <tr><td colspan="4" class="text-center text-muted py-4">No files.</td></tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                </div>
            </div>
        </div>

        <div class="col-xl-6">
            <div class="card border-0 shadow-sm h-100" style="border-radius:22px;">
                <div class="card-body p-4">
                    <h5 class="fw-bold mb-3">Review Assignments</h5>

                    <div class="table-responsive">
                        <table class="table table-bordered align-middle">
                            <thead class="table-dark">
                                <tr>
                                    <th>Reviewer</th>
                                    <th>Status</th>
                                    <th>Due</th>
                                    <th>Completed</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($assignments as $a): ?>
                                <tr>
                                    <td>
                                        <strong><?= sw_h(trim($a['reviewer_name'] ?? '') ?: ($a['reviewer_email'] ?? '')) ?></strong>
                                        <div class="text-muted small"><?= sw_h($a['reviewer_email'] ?? '') ?></div>
                                    </td>
                                    <td><span class="badge bg-primary"><?= sw_h($a['status'] ?? '') ?></span></td>
                                    <td><?= sw_h($a['due_date'] ?? '') ?></td>
                                    <td><?= sw_h($a['completed_at'] ?? '') ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (!$assignments): ?>
                                <tr><td colspan="4" class="text-center text-muted py-4">No assignments.</td></tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                </div>
            </div>
        </div>

    </div>

    <div class="row g-4">

        <div class="col-xl-6">
            <div class="card border-0 shadow-sm h-100" style="border-radius:22px;">
                <div class="card-body p-4">
                    <h5 class="fw-bold mb-3">Reviews</h5>

                    <?php foreach ($reviews as $rv): ?>
                        <div class="border rounded-4 p-3 mb-2">
                            <div class="fw-bold">
                                Score:
                                <?= sw_h($rv['overall_score'] ?? $rv['score'] ?? '-') ?>
                            </div>
                            <div class="text-muted small">Review #<?= (int)$rv['id'] ?></div>
                            <div class="mt-2">
                                <?= nl2br(sw_h($rv['comments_to_author'] ?? $rv['comments'] ?? $rv['review_text'] ?? '')) ?>
                            </div>
                        </div>
                    <?php endforeach; ?>

                    <?php if (!$reviews): ?>
                        <div class="alert alert-info">No reviews.</div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="col-xl-6">
            <div class="card border-0 shadow-sm h-100" style="border-radius:22px;">
                <div class="card-body p-4">
                    <h5 class="fw-bold mb-3">Author Rebuttals</h5>

                    <?php foreach ($rebuttals as $r): ?>
                        <div class="border rounded-4 p-3 mb-2">
                            <div class="text-muted small"><?= sw_h($r['created_at'] ?? '') ?> | <?= sw_h($r['status'] ?? '') ?></div>
                            <div><?= nl2br(sw_h($r['rebuttal_text'] ?? '')) ?></div>
                        </div>
                    <?php endforeach; ?>

                    <?php if (!$rebuttals): ?>
                        <div class="alert alert-info">No rebuttals.</div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

    </div>

    
    <div class="card border-0 shadow-sm mt-4" style="border-radius:22px;">
        <div class="card-body p-4">
            <h5 class="fw-bold mb-3">
                <i class="fa fa-envelope"></i>
                Send Conference Email Template
            </h5>

            <?php if (!empty($_GET['email_sent']) && $_GET['email_sent'] === '1'): ?>
                <div class="alert alert-success">Email sent successfully.</div>
            <?php elseif (isset($_GET['email_sent']) && $_GET['email_sent'] === '0'): ?>
                <div class="alert alert-danger">Email sending failed. Check outbox/error log below.</div>
            <?php endif; ?>

            <form method="post" action="/easychair/admin/submission-workflow/send-email" class="row g-2 align-items-end">
                <input type="hidden" name="submission_id" value="<?= (int)$submission['id'] ?>">

                <div class="col-md-5">
                    <label class="form-label fw-bold">Template</label>
                    <select name="template_key" class="form-select" required>
                        <option value="">Select active template</option>
                        <?php foreach (($emailTemplates ?? []) as $tpl): ?>
                            <option value="<?= sw_h(($tpl['template_key'] ?? '') ?: ($tpl['event_key'] ?? '')) ?>">
                                <?= sw_h((($tpl['template_key'] ?? '') ?: ($tpl['event_key'] ?? '')) . ' — ' . (($tpl['subject_en'] ?? '') ?: ($tpl['subject_ar'] ?? ''))) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-2">
                    <label class="form-label fw-bold">Language</label>
                    <select name="lang" class="form-select">
                        <option value="en">English</option>
                        <option value="ar">Arabic</option>
                    </select>
                </div>

                <div class="col-md-3">
                    <label class="form-label fw-bold">Recipient</label>
                    <input class="form-control" value="<?= sw_h($submission['author_email'] ?? '') ?>" disabled>
                </div>

                <div class="col-md-2">
                    <button class="btn btn-success w-100">
                        Send
                    </button>
                </div>
            </form>

            <hr>

            <h6 class="fw-bold">Recent Email Outbox</h6>

            <div class="table-responsive">
                <table class="table table-bordered align-middle">
                    <thead class="table-dark">
                        <tr>
                            <th>ID</th>
                            <th>Template</th>
                            <th>Recipient</th>
                            <th>Subject</th>
                            <th>Status</th>
                            <th>Sent</th>
                            <th>Error</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach (($mailOutbox ?? []) as $m): ?>
                        <tr>
                            <td><?= (int)$m['id'] ?></td>
                            <td>
                                <span class="badge bg-primary"><?= sw_h($m['template_key'] ?? '') ?></span>
                                <span class="badge bg-secondary"><?= sw_h($m['event_key'] ?? '') ?></span>
                            </td>
                            <td><?= sw_h($m['recipient_email'] ?? '') ?></td>
                            <td><?= sw_h($m['subject'] ?? '') ?></td>
                            <td>
                                <span class="badge <?= ($m['status'] ?? '') === 'sent' ? 'bg-success' : (($m['status'] ?? '') === 'failed' ? 'bg-danger' : 'bg-warning text-dark') ?>">
                                    <?= sw_h($m['status'] ?? '') ?>
                                </span>
                            </td>
                            <td><?= sw_h($m['sent_at'] ?? '') ?></td>
                            <td class="small text-danger"><?= sw_h(mb_substr((string)($m['error_message'] ?? ''), 0, 250)) ?></td>
                        </tr>
                    <?php endforeach; ?>

                    <?php if (empty($mailOutbox)): ?>
                        <tr><td colspan="7" class="text-center text-muted py-4">No emails sent for this submission yet.</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

<div class="card border-0 shadow-sm mt-4" style="border-radius:22px;">
        <div class="card-body p-4">
            <h5 class="fw-bold mb-3">Activity Timeline</h5>

            <?php foreach ($activity as $a): ?>
                <div class="border-start border-4 border-primary ps-3 mb-3">
                    <div class="fw-bold"><?= sw_h($a['event_title'] ?? '') ?></div>
                    <div class="text-muted small">
                        <?= sw_h($a['event_key'] ?? '') ?> |
                        <?= sw_h($a['actor_role'] ?? '') ?> |
                        <?= sw_h($a['created_at'] ?? '') ?>
                    </div>
                    <?php if (!empty($a['event_body'])): ?>
                        <pre style="white-space:pre-wrap;background:#f8fafc;border-radius:12px;padding:10px;margin-top:8px;"><?= sw_h($a['event_body']) ?></pre>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>

            <?php if (!$activity): ?>
                <div class="alert alert-info">No activity.</div>
            <?php endif; ?>
        </div>
    </div>

</div>
