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

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

$eis = new MraEisOnboarding($conn);
$compliance = new MraEisCompliance($conn);
$blockMessage = null;
$blockMessageType = 'success';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'refresh_block_status') {
    try {
        $terminal = $compliance->refreshTerminalBlockStatus($_POST['terminal_id'] ?? 0);
        $blockMessage = !empty($terminal['is_blocked'])
            ? 'Terminal is still blocked by MRA: ' . trim((string)($terminal['block_reason'] ?: 'No reason given.'))
            : 'Terminal is not blocked.';
        $blockMessageType = !empty($terminal['is_blocked']) ? 'warning' : 'success';
    } catch (Throwable $e) {
        $blockMessage = $e->getMessage();
        $blockMessageType = 'danger';
    }
}

$terminals = $eis->all();

function mra_eis_status_badge($status) {
    $classes = [
        'draft' => 'secondary',
        'activation_pending' => 'warning',
        'activated' => 'success',
        'failed' => 'danger',
    ];

    return $classes[$status] ?? 'secondary';
}
?>

<style>
    body { background: #f4f6f8; }
    .eis-shell { max-width: 1280px; 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; }
    .flow-step { display: flex; gap: 14px; align-items: flex-start; padding: 16px; border: 1px solid #e5e7eb; border-radius: 8px; background: #fff; height: 100%; }
    .flow-step-number { width: 34px; height: 34px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; background: #0d6efd; color: #fff; font-weight: 700; flex: 0 0 auto; }
    .flow-step h6 { font-weight: 700; margin-bottom: 4px; }
    .flow-step p { margin: 0; color: #667085; font-size: 0.9rem; }
    .terminal-meta { color: #667085; font-size: 0.875rem; line-height: 1.5; }
    .table td, .table th { vertical-align: middle; }
    @media (max-width: 768px) {
        .eis-topbar { display: block; }
        .eis-topbar .btn { width: 100%; margin-top: 10px; }
    }
</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-network-wired"></i> MRA EIS Onboarding</h2>
            <p class="text-muted mb-0">Activate and confirm POS terminals using the official MRA EIS onboarding flow.</p>
        </div>
        <div class="d-flex flex-wrap" style="gap: 8px;">
            <a href="mra_eis_terminal_activation.php" class="btn btn-primary">
                <i class="fas fa-plus-circle"></i> New Terminal
            </a>
            <a href="../dashboard/admin.php" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left"></i> Dashboard
            </a>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-md-4 mb-3">
            <div class="flow-step">
                <span class="flow-step-number">1</span>
                <div>
                    <h6>Prepare Terminal</h6>
                    <p>Enter the TAC from the MRA EIS Portal plus platform and POS product details.</p>
                </div>
            </div>
        </div>
        <div class="col-md-4 mb-3">
            <div class="flow-step">
                <span class="flow-step-number">2</span>
                <div>
                    <h6>Activate</h6>
                    <p>Send the activation request to `/onboarding/activate-terminal` and store the returned credentials.</p>
                </div>
            </div>
        </div>
        <div class="col-md-4 mb-3">
            <div class="flow-step">
                <span class="flow-step-number">3</span>
                <div>
                    <h6>Confirm</h6>
                    <p>Confirm with `/onboarding/terminal-activated-confirmation` using the HMAC `x-signature`.</p>
                </div>
            </div>
        </div>
    </div>

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

    <div class="card eis-card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-cash-register"></i> Onboarding Terminals</h5>
            <span class="badge bg-light text-dark"><?php echo count($terminals); ?> total</span>
        </div>
        <div class="card-body">
            <?php if (empty($terminals)): ?>
                <div class="alert alert-info mb-0">No MRA EIS terminals have been prepared yet.</div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped table-bordered mb-0">
                        <thead>
                            <tr>
                                <th>Terminal</th>
                                <th>Branch</th>
                                <th>Environment</th>
                                <th>POS Product</th>
                                <th>MRA Terminal ID</th>
                                <th>Status</th>
                                <th>Block Status</th>
                                <th>Updated</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($terminals as $terminal): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo htmlspecialchars($terminal['terminal_label']); ?></strong>
                                        <div class="terminal-meta">TAC: <?php echo htmlspecialchars($terminal['terminal_activation_code']); ?></div>
                                    </td>
                                    <td>
                                        <?php echo htmlspecialchars($terminal['branch_name'] ?? 'Unknown branch'); ?>
                                        <div class="terminal-meta">branch_id: <?php echo (int)$terminal['branch_id']; ?></div>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php echo $terminal['environment'] === 'production' ? 'danger' : 'secondary'; ?>">
                                            <?php echo htmlspecialchars(ucfirst($terminal['environment'])); ?>
                                        </span>
                                        <div class="terminal-meta"><?php echo htmlspecialchars($terminal['api_base_url']); ?></div>
                                    </td>
                                    <td>
                                        <?php echo htmlspecialchars($terminal['pos_product_id']); ?>
                                        <div class="terminal-meta">Version <?php echo htmlspecialchars($terminal['pos_product_version']); ?></div>
                                    </td>
                                    <td><?php echo htmlspecialchars($terminal['mra_terminal_id'] ?: 'Not issued'); ?></td>
                                    <td>
                                        <span class="badge bg-<?php echo mra_eis_status_badge($terminal['status']); ?>">
                                            <?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $terminal['status']))); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if (!empty($terminal['is_blocked'])): ?>
                                            <span class="badge bg-danger">Blocked</span>
                                            <div class="terminal-meta"><?php echo htmlspecialchars($terminal['block_reason'] ?: 'No reason given.'); ?></div>
                                        <?php else: ?>
                                            <span class="badge bg-success">Not blocked</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($terminal['updated_at']); ?></td>
                                    <td>
                                        <div class="d-flex flex-wrap" style="gap: 6px;">
                                            <a href="mra_eis_terminal_activation.php?id=<?php echo urlencode($terminal['id']); ?>" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-edit"></i> Prepare
                                            </a>
                                            <a href="mra_eis_terminal_confirmation.php?id=<?php echo urlencode($terminal['id']); ?>" class="btn btn-sm btn-outline-success">
                                                <i class="fas fa-check-circle"></i> Confirm
                                            </a>
                                            <?php if ($terminal['status'] === 'activated'): ?>
                                                <form method="POST" class="d-inline">
                                                    <input type="hidden" name="action" value="refresh_block_status">
                                                    <input type="hidden" name="terminal_id" value="<?php echo (int)$terminal['id']; ?>">
                                                    <button type="submit" class="btn btn-sm btn-outline-warning">
                                                        <i class="fas fa-sync"></i> Check Block Status
                                                    </button>
                                                </form>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

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