<?php
$d = $deploymentData ?? [];
$registry = (array) ($d['registry'] ?? []);
$orchestrations = (array) ($d['orchestrations'] ?? []);
$selected = is_array($d['selected'] ?? null) ? $d['selected'] : null;

$h = static fn($value): string =>
    htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');

$statusClass = static fn(string $status): string => match ($status) {
    'COMPLETED', 'DEPLOYED', 'INSTALLED', 'ALREADY_INSTALLED' => 'ok',
    'RUNNING', 'PLANNED', 'PENDING' => 'run',
    'ROLLED_BACK' => 'rollback',
    'FAILED', 'CANCELLED' => 'bad',
    default => 'info',
};
?>
<style>
.orch{display:grid;gap:18px}.orch *{box-sizing:border-box}
.orch-hero{border-radius:24px;padding:26px;background:linear-gradient(135deg,#14213d,#1f4f7a 56%,#2879b2);color:#fff;display:flex;justify-content:space-between;gap:20px;align-items:center;box-shadow:0 18px 44px rgba(15,43,70,.18)}
.orch-hero h1{margin:5px 0 8px;font-size:clamp(28px,4vw,42px)}.orch-hero p{margin:0;color:#dbeafe}
.orch-actions{display:flex;gap:9px;flex-wrap:wrap}.orch-btn{border:1px solid #cbd8e6;border-radius:11px;background:#fff;color:#1c4e77;padding:10px 14px;font-weight:800;text-decoration:none;cursor:pointer;display:inline-flex;justify-content:center}
.orch-btn.primary{background:#1f67a2;border-color:#1f67a2;color:#fff}.orch-btn.danger{background:#b91c1c;border-color:#b91c1c;color:#fff}.orch-btn.ghost{background:rgba(255,255,255,.1);border-color:rgba(255,255,255,.35);color:#fff}
.orch-card{background:#fff;border:1px solid #dbe5ef;border-radius:18px;padding:18px;box-shadow:0 8px 26px rgba(23,50,77,.055)}
.orch-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px}.orch-kpi small{color:#64748b}.orch-kpi strong{display:block;font-size:28px;color:#173b5a;margin-top:4px}
.orch-layout{display:grid;grid-template-columns:minmax(300px,.75fr) minmax(0,1.25fr);gap:14px}
.orch-form{display:grid;gap:13px}.orch-form select,.orch-form input{width:100%;padding:11px;border:1px solid #cbd5e1;border-radius:10px}.orch-check{display:flex;gap:9px;align-items:flex-start}.orch-check input{width:auto;margin-top:3px}
.orch-list{display:grid;gap:9px;max-height:700px;overflow:auto}.orch-item{display:flex;justify-content:space-between;gap:12px;padding:12px;border:1px solid #e1e9f1;border-radius:13px;text-decoration:none;color:#173b5a}.orch-item.active{background:#eef7fe;border-color:#2d76ad}.orch-item small{display:block;color:#64748b}
.orch-badge{display:inline-flex;padding:5px 8px;border-radius:999px;font-size:11px;font-weight:900}.orch-badge.ok{background:#dcfce7;color:#166534}.orch-badge.run{background:#dbeafe;color:#1d4ed8}.orch-badge.rollback{background:#ede9fe;color:#6d28d9}.orch-badge.bad{background:#fee2e2;color:#991b1b}.orch-badge.info{background:#e2e8f0;color:#334155}
.orch-progress{height:18px;background:#e5edf6;border-radius:999px;overflow:hidden}.orch-progress>div{height:100%;background:linear-gradient(90deg,#2563eb,#7c3aed);transition:width .25s ease}
.orch-steps{display:grid;gap:10px}.orch-step{display:grid;grid-template-columns:44px 1fr auto;gap:12px;align-items:center;padding:13px;border:1px solid #e1e9f1;border-radius:14px}.orch-step-number{width:36px;height:36px;border-radius:50%;background:#e2e8f0;color:#334155;display:grid;place-items:center;font-weight:900}.orch-step.running .orch-step-number{background:#2563eb;color:#fff}.orch-step.completed .orch-step-number{background:#16a34a;color:#fff}.orch-step.failed .orch-step-number{background:#dc2626;color:#fff}.orch-step.rolled_back .orch-step-number{background:#7c3aed;color:#fff}
.orch-error{border:1px solid #fecaca;background:#fff1f2;color:#9f1239;border-radius:12px;padding:12px}
@media(max-width:900px){.orch-hero{align-items:flex-start;flex-direction:column}.orch-layout{grid-template-columns:1fr}.orch-step{grid-template-columns:40px 1fr}.orch-step>div:last-child{grid-column:2}}
</style>

<div class="orch">
<section class="orch-hero">
    <div>
        <small>PLATFORM-023.5.5 · AXIOM 10.2.6.4</small>
        <h1>Enterprise Deployment Orchestrator PRO</h1>
        <p>Planification par dépendances, reprise, déploiement séquentiel et rollback automatique.</p>
    </div>
    <div class="orch-actions">
        <a class="orch-btn ghost" href="/public/studio/mises-a-jour">Centre de mises à jour</a>
        <a class="orch-btn ghost" href="/public/administration/plateforme/packages/dependances">Dependency Graph</a>
        <a class="orch-btn ghost" href="/public/administration/plateforme/rollback">Rollback Manager</a>
    </div>
</section>

<div class="orch-grid">
    <article class="orch-card orch-kpi"><small>Version active</small><strong><?= $h($d['current_version'] ?? '') ?></strong></article>
    <article class="orch-card orch-kpi"><small>Packages orchestrables</small><strong><?= count($registry) ?></strong></article>
    <article class="orch-card orch-kpi"><small>Orchestrations visibles</small><strong><?= count($orchestrations) ?></strong></article>
    <article class="orch-card orch-kpi"><small>Actualisé le</small><strong style="font-size:17px"><?= $h($d['generated_at'] ?? '') ?></strong></article>
</div>

<section class="orch-layout">
<aside class="orch-card">
    <h2>Nouvelle orchestration</h2>
    <form class="orch-form" method="post" action="/public/administration/plateforme/deploiement-orchestre/creer">
        <?= \App\Core\Csrf::field() ?>

        <label>
            <strong>Package racine</strong>
            <select name="root_registry_id" required>
                <option value="">Sélectionner…</option>
                <?php foreach ($registry as $package): ?>
                    <option value="<?= (int) $package['id'] ?>">
                        <?= $h($package['package_name']) ?>
                        · <?= $h($package['version']) ?>
                        · <?= $h($package['package_status']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </label>

        <label class="orch-check">
            <input type="checkbox" name="automatic_rollback" checked>
            <span>
                <strong>Rollback automatique</strong><br>
                <small>Restaurer l’état précédant la vague si une étape échoue.</small>
            </span>
        </label>

        <label class="orch-check">
            <input type="checkbox" name="stop_on_warning">
            <span>
                <strong>Bloquer sur avertissement</strong><br>
                <small>Refuser le plan si le Dependency Graph retourne WARNING.</small>
            </span>
        </label>

        <button class="orch-btn primary" type="submit">Calculer le plan</button>
    </form>

    <h2 style="margin-top:24px">Historique</h2>
    <div class="orch-list">
    <?php foreach ($orchestrations as $item): ?>
        <a
            class="orch-item <?= $selected && (int) $selected['orchestration']['id'] === (int) $item['id'] ? 'active' : '' ?>"
            href="?id=<?= (int) $item['id'] ?>"
        >
            <div>
                <strong>#<?= (int) $item['id'] ?> · <?= $h($item['root_package_name'] ?? 'Package') ?></strong>
                <small>
                    <?= $h($item['root_version'] ?? '') ?>
                    · <?= (int) $item['current_step'] ?>/<?= (int) $item['total_steps'] ?>
                    · <?= $h($item['created_at']) ?>
                </small>
            </div>
            <span class="orch-badge <?= $statusClass((string) $item['status']) ?>">
                <?= $h($item['status']) ?>
            </span>
        </a>
    <?php endforeach; ?>

    <?php if ($orchestrations === []): ?>
        <p>Aucune orchestration créée.</p>
    <?php endif; ?>
    </div>
</aside>

<main class="orch-card">
<?php if ($selected): ?>
    <?php $orchestration = $selected['orchestration']; ?>
    <div style="display:flex;justify-content:space-between;gap:12px;align-items:flex-start;flex-wrap:wrap">
        <div>
            <small>ORCHESTRATION #<?= (int) $orchestration['id'] ?></small>
            <h2 style="margin:4px 0"><?= $h($orchestration['message']) ?></h2>
            <span class="orch-badge <?= $statusClass((string) $orchestration['status']) ?>">
                <?= $h($orchestration['status']) ?>
            </span>
            <span class="orch-badge <?= $statusClass((string) $orchestration['decision']) ?>">
                <?= $h($orchestration['decision']) ?>
            </span>
        </div>

        <?php if (in_array((string) $orchestration['status'], ['PLANNED', 'RUNNING'], true)): ?>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
            <button
                class="orch-btn primary"
                type="button"
                id="orchestrator-start"
                data-id="<?= (int) $orchestration['id'] ?>"
            >Démarrer / reprendre</button>

            <form method="post" action="/public/administration/plateforme/deploiement-orchestre/annuler"
                  onsubmit="return confirm('Annuler l’orchestration avant la prochaine étape ?');">
                <?= \App\Core\Csrf::field() ?>
                <input type="hidden" name="orchestration_id" value="<?= (int) $orchestration['id'] ?>">
                <button class="orch-btn danger" type="submit">Annuler</button>
            </form>
        </div>
        <?php endif; ?>
    </div>

    <div style="margin:18px 0">
        <div class="orch-progress">
            <div id="orchestrator-progress-bar" style="width:<?= (int) $selected['progress'] ?>%"></div>
        </div>
        <div style="display:flex;justify-content:space-between;margin-top:7px">
            <strong id="orchestrator-progress-text"><?= (int) $selected['progress'] ?> %</strong>
            <span>
                <?= (int) $selected['completed_steps'] ?>
                / <?= (int) $selected['total_steps'] ?> étape(s)
            </span>
        </div>
    </div>

    <div id="orchestrator-error" class="orch-error" hidden></div>

    <div class="orch-steps" id="orchestrator-steps">
    <?php foreach ((array) $selected['steps'] as $step): ?>
        <?php $stepClass = strtolower((string) $step['status']); ?>
        <article class="orch-step <?= $h($stepClass) ?>">
            <div class="orch-step-number"><?= (int) $step['step_order'] ?></div>
            <div>
                <strong><?= $h($step['package_name']) ?></strong>
                <small>
                    <?= $h($step['package_key']) ?>
                    · <?= $h($step['package_version']) ?>
                    · <?= (int) $step['duration_ms'] ?> ms
                </small>
                <?php if (!empty($step['message'])): ?>
                    <p style="margin:5px 0 0"><?= $h($step['message']) ?></p>
                <?php endif; ?>
            </div>
            <div>
                <span class="orch-badge <?= $statusClass((string) $step['status']) ?>">
                    <?= $h($step['status']) ?>
                </span>
                <span class="orch-badge <?= $statusClass((string) $step['decision']) ?>">
                    <?= $h($step['decision']) ?>
                </span>
            </div>
        </article>
    <?php endforeach; ?>
    </div>
<?php else: ?>
    <div style="text-align:center;padding:50px 20px;color:#64748b">
        <h2>Sélectionnez ou créez une orchestration</h2>
        <p>Le plan sera calculé depuis le Dependency Graph, puis exécuté package par package.</p>
    </div>
<?php endif; ?>
</main>
</section>
</div>

<script>
window.AXIOM_ORCHESTRATOR_CSRF =
    <?= json_encode(\App\Core\Csrf::token(), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
</script>
<script src="/public/assets/js/axiom-deployment-orchestrator-10264.js" defer></script>
