<?php
require_once '../../includes/header.php';
require_once '../../classes/MraEisOnboarding.php';

if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    header('Location: ../../unauthorized.php');
    exit;
}

$eis = new MraEisOnboarding($conn);
$message = null;
$messageType = 'success';
$terminalId = $_GET['id'] ?? $_POST['id'] ?? '';
$terminal = null;
$hmacSelfTestPassed = $eis->hmacSelfTestPassed();

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_terminal'])) {
        $eis->confirm($_POST['id'] ?? null);
        $message = 'Terminal confirmation completed successfully.';
    }

    if ($terminalId !== '') {
        $terminal = $eis->find($terminalId);
    }
} catch (Exception $e) {
    $message = $e->getMessage();
    $messageType = 'danger';
    if ($terminalId !== '') {
        $terminal = $eis->find($terminalId);
    }
}

$signature = '';
$signatureAttempts = [];
$confirmationPayload = null;
if ($terminal && !empty($terminal['secret_key']) && !empty($terminal['terminal_activation_code']) && !empty($terminal['mra_terminal_id'])) {
    $signature = $eis->computeXSignature($terminal['terminal_activation_code'], $terminal['secret_key']);
    $signatureAttempts = $eis->confirmationSignatureAttempts($terminal);
    $confirmationPayload = ['terminalId' => $terminal['mra_terminal_id']];
}
?>

<style>
    body { background: #f4f6f8; }
    .eis-shell { max-width: 1180px; margin: 30px auto; padding: 0 15px; }
    .eis-topbar { display: flex; justify-content: space-between; gap: 16px; align-items: center; margin-bottom: 20px; }
    .eis-title { font-weight: 800; color: #172033; }
    .eis-card { border: 0; border-radius: 8px; box-shadow: 0 2px 12px rgba(15, 23, 42, 0.08); }
    .eis-card .card-header { background: #1f2937; color: #fff; border-radius: 8px 8px 0 0; }
    .data-line { display: flex; justify-content: space-between; gap: 16px; padding: 12px 0; border-bottom: 1px solid #e5e7eb; }
    .data-line:last-child { border-bottom: 0; }
    .data-label { font-weight: 700; color: #344054; }
    .data-value { color: #667085; text-align: right; overflow-wrap: anywhere; }
    .request-preview { white-space: pre-wrap; min-height: 260px; font-size: 0.875rem; }
    @media (max-width: 768px) {
        .eis-topbar, .data-line { display: block; }
        .eis-topbar .btn { width: 100%; margin-top: 10px; }
        .data-value { text-align: left; margin-top: 4px; }
    }
</style>

<div class="eis-shell">
    <?php $eisNavCurrent = 'onboarding'; require __DIR__ . '/../../includes/eis_admin_nav.php'; ?>

    <div class="eis-topbar">
        <div>
            <h2 class="eis-title mb-1"><i class="fas fa-check-circle"></i> Terminal Confirmation</h2>
            <p class="text-muted mb-0">Confirm that terminal configuration was persisted after activation.</p>
        </div>
        <div class="d-flex flex-wrap" style="gap: 8px;">
            <a href="mra_eis_onboarding.php" class="btn btn-outline-primary">
                <i class="fas fa-list"></i> Onboarding
            </a>
            <?php if ($terminal): ?>
                <a href="mra_eis_terminal_activation.php?id=<?php echo urlencode($terminal['id']); ?>" class="btn btn-outline-secondary">
                    <i class="fas fa-edit"></i> Activation
                </a>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
            <?php echo htmlspecialchars($message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (!$hmacSelfTestPassed): ?>
        <div class="alert alert-danger">
            Local HMAC-SHA512 self-test failed. Confirmation signatures will not be accepted until PHP hashing is corrected.
        </div>
    <?php endif; ?>

    <?php if (!$terminal): ?>
        <div class="alert alert-warning">Select a terminal from the onboarding list before sending confirmation.</div>
    <?php else: ?>
        <div class="row">
            <div class="col-lg-6 mb-4">
                <div class="card eis-card h-100">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-id-card"></i> Activation State</h5>
                    </div>
                    <div class="card-body">
                        <div class="data-line">
                            <span class="data-label">Terminal</span>
                            <span class="data-value"><?php echo htmlspecialchars($terminal['terminal_label']); ?></span>
                        </div>
                        <div class="data-line">
                            <span class="data-label">Status</span>
                            <span class="data-value"><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $terminal['status']))); ?></span>
                        </div>
                        <div class="data-line">
                            <span class="data-label">MRA Terminal ID</span>
                            <span class="data-value"><?php echo htmlspecialchars($terminal['mra_terminal_id'] ?: 'Not issued'); ?></span>
                        </div>
                        <div class="data-line">
                            <span class="data-label">Secret Key</span>
                            <span class="data-value"><?php echo $terminal['secret_key'] ? 'Stored' : 'Missing'; ?></span>
                        </div>
                        <div class="data-line">
                            <span class="data-label">Activated At</span>
                            <span class="data-value"><?php echo htmlspecialchars($terminal['activated_at'] ?: 'Pending'); ?></span>
                        </div>
                        <div class="data-line">
                            <span class="data-label">Confirmed At</span>
                            <span class="data-value"><?php echo htmlspecialchars($terminal['confirmed_at'] ?: 'Pending'); ?></span>
                        </div>

                        <?php if (!empty($terminal['last_error'])): ?>
                            <div class="alert alert-danger mt-3 mb-0">
                                <pre class="mb-0" style="white-space: pre-wrap;"><?php echo htmlspecialchars($terminal['last_error']); ?></pre>
                            </div>
                        <?php endif; ?>

                        <form method="POST" class="mt-4">
                            <input type="hidden" name="id" value="<?php echo htmlspecialchars($terminal['id']); ?>">
                            <button type="submit" name="confirm_terminal" value="1" class="btn btn-success" <?php echo $confirmationPayload ? '' : 'disabled'; ?>>
                                <i class="fas fa-paper-plane"></i> Send Confirmation
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-lg-6 mb-4">
                <div class="card eis-card h-100">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-code"></i> Confirmation Request</h5>
                    </div>
                    <div class="card-body">
                        <?php if ($confirmationPayload): ?>
                            <?php foreach ($signatureAttempts as $index => $attempt): ?>
                                <div class="mb-3">
                                    <label class="form-label">
                                        x-signature attempt <?php echo $index + 1; ?>:
                                        <?php echo htmlspecialchars($attempt['method']); ?>
                                    </label>
                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($attempt['signature']); ?>" readonly>
                                </div>
                            <?php endforeach; ?>
                            <pre class="bg-light border rounded p-3 request-preview"><?php echo htmlspecialchars(json_encode($confirmationPayload, JSON_PRETTY_PRINT)); ?></pre>
                        <?php else: ?>
                            <div class="alert alert-info mb-0">
                                Activation must return a terminal ID and secret key before confirmation can be sent.
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<?php include '../../includes/footer.php'; ?>
