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

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

$compliance = new MraEisCompliance($conn);
$message = null;
$messageType = 'success';

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? '';

        if ($action === 'submit_outbox') {
            $result = $compliance->submitOutbox($_POST['outbox_id'] ?? 0, $_SESSION['user_id']);
            if (!empty($result['success'])) {
                $message = 'EIS submission completed successfully.';
                $messageType = 'success';
            } elseif (!empty($result['queued'])) {
                $message = $result['message'] ?? ('EIS submission returned HTTP ' . $result['status'] . ' and was kept queued for later.');
                $messageType = 'warning';
            } else {
                $message = 'EIS submission returned HTTP ' . $result['status'] . '.';
                $messageType = 'danger';
            }
        }
    }
} catch (Throwable $e) {
    $message = $e->getMessage();
    $messageType = 'danger';
}

$status = $_GET['status'] ?? '';
$entityType = $_GET['entity_type'] ?? '';
$loadError = null;
try {
    $rows = $compliance->outbox($status, $entityType, 200);
} catch (Throwable $e) {
    // display_errors is off in production (.htaccess), so an uncaught exception
    // here previously produced a silent blank page with no way to diagnose it —
    // surface it on-page instead (this page is superadmin-only).
    $rows = [];
    $loadError = $e->getMessage();
}

$statusCounts = array_count_values(array_column($rows, 'status'));
$entityIcons = [
    'sale' => 'fa-cash-register',
    'transfer' => 'fa-truck',
    'void_receipt' => 'fa-ban',
    'stock_adjustment' => 'fa-sliders-h',
    'initial_inventory' => 'fa-box-open',
    'informal_purchase' => 'fa-file-invoice',
];
$statusMeta = [
    'ready'     => ['label' => 'Ready',     'icon' => 'fa-circle-check',        'tone' => 'ok'],
    'queued'    => ['label' => 'Queued',    'icon' => 'fa-clock-rotate-left',   'tone' => 'warn'],
    'blocked'   => ['label' => 'Blocked',   'icon' => 'fa-hand',                'tone' => 'warn'],
    'submitted' => ['label' => 'Submitted', 'icon' => 'fa-paper-plane',         'tone' => 'info'],
    'failed'    => ['label' => 'Failed',    'icon' => 'fa-triangle-exclamation','tone' => 'bad'],
    'pending'   => ['label' => 'Pending',   'icon' => 'fa-hourglass-half',      'tone' => 'neutral'],
];
$alertMeta = [
    'success' => ['icon' => 'fa-circle-check'],
    'warning' => ['icon' => 'fa-triangle-exclamation'],
    'danger'  => ['icon' => 'fa-circle-xmark'],
];
$httpStatusTone = static function ($httpStatus) {
    $httpStatus = (int)$httpStatus;
    if ($httpStatus >= 200 && $httpStatus < 300) {
        return 'ok';
    }
    if ($httpStatus === 0) {
        return 'neutral';
    }
    return 'bad';
};
?>

<style>
    :root {
        --eisc-ink: #1B2430;
        --eisc-ink-muted: #5B6472;
        --eisc-ink-faint: #8B93A1;
        --eisc-canvas: #F4F6FA;
        --eisc-surface: #FFFFFF;
        --eisc-border: #E3E7EE;
        --eisc-header: #202B3D;
        --eisc-accent: #2A5DB0;
        --eisc-accent-soft: #E8F0FC;
        --eisc-code-bg: #161B22;
        --eisc-code-fg: #D7DEE8;
        --eisc-ok: #1F8A5F;      --eisc-ok-soft: #E4F6EC;
        --eisc-warn: #B4780A;    --eisc-warn-soft: #FBF0DC;
        --eisc-bad: #C23934;     --eisc-bad-soft: #FBE7E5;
        --eisc-info: #2A5DB0;    --eisc-info-soft: #E8F0FC;
        --eisc-neutral: #5B6472; --eisc-neutral-soft: #EEF0F3;
    }

    body { background: var(--eisc-canvas); }

    .eis-shell { max-width: 1360px; margin: 32px auto 56px; padding: 0 16px; color: var(--eisc-ink); }

    /* ---------- Header ---------- */
    .eis-topbar {
        display: flex; flex-wrap: wrap; justify-content: space-between; gap: 18px;
        align-items: flex-end; margin-bottom: 22px; padding-bottom: 18px;
        border-bottom: 1px solid var(--eisc-border);
    }
    .eis-title {
        font-weight: 700; color: var(--eisc-ink); font-size: 1.5rem;
        display: flex; align-items: center; gap: 10px; letter-spacing: -0.01em;
    }
    .eis-title i { color: var(--eisc-accent); font-size: 1.15rem; }
    .eis-subtitle { color: var(--eisc-ink-muted); font-size: 0.925rem; }

    /* ---------- Alert ---------- */
    .eis-alert {
        border: 1px solid transparent; border-radius: 9px; padding: 13px 16px;
        display: flex; align-items: flex-start; gap: 11px; font-size: 0.9rem; margin-bottom: 20px;
    }
    .eis-alert i { margin-top: 2px; }
    .eis-alert.alert-success { background: var(--eisc-ok-soft); color: var(--eisc-ok); border-color: #CBEAD9; }
    .eis-alert.alert-warning { background: var(--eisc-warn-soft); color: var(--eisc-warn); border-color: #F3E1B6; }
    .eis-alert.alert-danger  { background: var(--eisc-bad-soft);  color: var(--eisc-bad);  border-color: #F2CFCB; }
    .eis-alert .btn-close { margin-left: auto; }

    /* ---------- Card shell ---------- */
    .eis-card {
        border: 1px solid var(--eisc-border); border-radius: 12px; background: var(--eisc-surface);
        box-shadow: 0 1px 2px rgba(27,36,48,0.04), 0 8px 24px -14px rgba(27,36,48,0.18);
        overflow: hidden;
    }
    .eis-card-head {
        display: flex; flex-wrap: wrap; gap: 14px; align-items: center; justify-content: space-between;
        padding: 18px 22px; background: var(--eisc-header); color: #fff;
    }
    .eis-card-head h5 { margin: 0; font-weight: 650; font-size: 1.02rem; display: flex; align-items: center; gap: 9px; }
    .eis-card-head .eis-count { font-size: 0.8rem; color: #C7D2E6; font-variant-numeric: tabular-nums; }
    .eis-card-body { padding: 20px 22px 22px; }

    /* ---------- Status summary strip ---------- */
    .eis-stat-row { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px; }
    .eis-stat {
        flex: 1 1 130px; display: flex; align-items: center; gap: 10px;
        padding: 11px 14px; border-radius: 9px; border: 1px solid var(--eisc-border);
        background: var(--eisc-canvas); text-decoration: none; color: inherit;
        transition: border-color .12s ease, transform .12s ease;
    }
    .eis-stat:hover { border-color: var(--eisc-accent); transform: translateY(-1px); }
    .eis-stat.is-active { border-color: var(--eisc-accent); background: var(--eisc-accent-soft); }
    .eis-stat .dot { width: 9px; height: 9px; border-radius: 50%; flex: 0 0 auto; }
    .eis-stat .num { font-size: 1.15rem; font-weight: 700; font-variant-numeric: tabular-nums; line-height: 1; color: var(--eisc-ink); }
    .eis-stat .lbl { font-size: 0.72rem; text-transform: uppercase; letter-spacing: .05em; color: var(--eisc-ink-muted); }
    .tone-ok .dot, .tone-ok .num { color: var(--eisc-ok); } .tone-ok .dot { background: var(--eisc-ok); }
    .tone-warn .dot { background: var(--eisc-warn); } .tone-warn .num { color: var(--eisc-warn); }
    .tone-bad .dot { background: var(--eisc-bad); } .tone-bad .num { color: var(--eisc-bad); }
    .tone-info .dot { background: var(--eisc-info); } .tone-info .num { color: var(--eisc-info); }
    .tone-neutral .dot { background: var(--eisc-neutral); } .tone-neutral .num { color: var(--eisc-neutral); }

    /* ---------- Filter toolbar ---------- */
    .eis-filter { display: flex; flex-wrap: wrap; align-items: end; gap: 12px; margin-bottom: 22px; }
    .eis-filter .fld { display: flex; flex-direction: column; gap: 5px; min-width: 190px; }
    .eis-filter label { font-size: 0.72rem; text-transform: uppercase; letter-spacing: .05em; color: var(--eisc-ink-faint); font-weight: 600; }
    .eis-filter .form-select { border-color: var(--eisc-border); }
    .eis-filter .btn-filter {
        background: var(--eisc-accent); border-color: var(--eisc-accent); color: #fff;
        font-weight: 600; padding: 8px 18px;
    }
    .eis-filter .btn-filter:hover { background: #244C90; border-color: #244C90; color: #fff; }
    .eis-filter .btn-reset { color: var(--eisc-ink-muted); text-decoration: none; font-size: 0.85rem; padding-bottom: 9px; }
    .eis-filter .btn-reset:hover { color: var(--eisc-accent); }

    /* ---------- Table ---------- */
    .eis-table-wrap { border: 1px solid var(--eisc-border); border-radius: 10px; overflow: hidden; }
    table.eis-table { width: 100%; margin: 0; border-collapse: collapse; font-size: 0.865rem; }
    table.eis-table thead th {
        background: var(--eisc-header); color: #C7D2E6; font-size: 0.72rem;
        text-transform: uppercase; letter-spacing: .06em; font-weight: 650;
        padding: 11px 14px; text-align: left; white-space: nowrap; border: 0;
    }
    table.eis-table tbody td { padding: 13px 14px; vertical-align: top; border-top: 1px solid var(--eisc-border); }
    table.eis-table tbody tr:nth-child(even) { background: var(--eisc-canvas); }
    table.eis-table tbody tr:hover { background: var(--eisc-accent-soft); }

    .item-title { font-weight: 650; display: flex; align-items: center; gap: 7px; color: var(--eisc-ink); }
    .item-title i { color: var(--eisc-ink-faint); font-size: 0.85rem; }
    .mono-chip {
        display: inline-block; margin-top: 4px; font-family: ui-monospace, SFMono-Regular, "Cascadia Code", Consolas, monospace;
        font-size: 0.76rem; color: var(--eisc-ink-muted); background: var(--eisc-canvas);
        border: 1px solid var(--eisc-border); border-radius: 5px; padding: 1px 7px; word-break: break-all;
    }
    .queue-meta { color: var(--eisc-ink-muted); font-size: 0.78rem; line-height: 1.5; margin-top: 4px; }
    .queue-meta i { width: 12px; text-align: center; margin-right: 2px; color: var(--eisc-ink-faint); }
    .attempt-pill {
        display: inline-flex; align-items: center; gap: 4px; font-size: 0.72rem; color: var(--eisc-ink-faint);
        margin-top: 4px;
    }

    .status-pill {
        display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px 4px 8px;
        border-radius: 100px; font-size: 0.76rem; font-weight: 650; white-space: nowrap;
    }
    .status-pill i { font-size: 0.72rem; }
    .tone-ok.status-pill { background: var(--eisc-ok-soft); color: var(--eisc-ok); }
    .tone-warn.status-pill { background: var(--eisc-warn-soft); color: var(--eisc-warn); }
    .tone-bad.status-pill { background: var(--eisc-bad-soft); color: var(--eisc-bad); }
    .tone-info.status-pill { background: var(--eisc-info-soft); color: var(--eisc-info); }
    .tone-neutral.status-pill { background: var(--eisc-neutral-soft); color: var(--eisc-neutral); }
    .error-note {
        margin-top: 7px; font-size: 0.76rem; color: var(--eisc-bad); background: var(--eisc-bad-soft);
        border-radius: 6px; padding: 6px 9px; line-height: 1.4;
    }
    .validation-link { margin-top: 6px; font-size: 0.78rem; }
    .validation-link a { color: var(--eisc-accent); text-decoration: none; font-weight: 600; }
    .validation-link a:hover { text-decoration: underline; }

    .endpoint-text {
        font-family: ui-monospace, SFMono-Regular, "Cascadia Code", Consolas, monospace;
        font-size: 0.78rem; color: var(--eisc-ink-muted); max-width: 220px; display: inline-block;
        overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: bottom;
    }

    details.eis-detail { margin-top: 6px; }
    details.eis-detail:first-child { margin-top: 0; }
    details.eis-detail summary {
        cursor: pointer; list-style: none; display: inline-flex; align-items: center; gap: 6px;
        font-size: 0.76rem; font-weight: 600; color: var(--eisc-accent);
        padding: 4px 9px; border-radius: 6px; background: var(--eisc-accent-soft);
    }
    details.eis-detail summary::-webkit-details-marker { display: none; }
    details.eis-detail summary::before { content: "\f105"; font-family: "Font Awesome 6 Free"; font-weight: 900; transition: transform .12s ease; }
    details.eis-detail[open] summary::before { transform: rotate(90deg); }
    .payload-preview {
        max-height: 260px; overflow: auto; white-space: pre-wrap; word-break: break-word;
        font-family: ui-monospace, SFMono-Regular, "Cascadia Code", Consolas, monospace;
        font-size: 11.5px; line-height: 1.55; background: var(--eisc-code-bg); color: var(--eisc-code-fg);
        border-radius: 7px; padding: 12px 13px; margin: 6px 0 0;
    }

    .btn-submit-outbox {
        background: var(--eisc-accent); border-color: var(--eisc-accent); color: #fff;
        font-size: 0.8rem; font-weight: 600; padding: 6px 13px;
    }
    .btn-submit-outbox:hover { background: #244C90; border-color: #244C90; color: #fff; }
    .not-ready { color: var(--eisc-ink-faint); font-size: 0.78rem; display: inline-flex; align-items: center; gap: 6px; }

    .eis-empty { text-align: center; padding: 56px 20px; color: var(--eisc-ink-muted); }
    .eis-empty i { font-size: 2rem; color: var(--eisc-border); margin-bottom: 14px; display: block; }
    .eis-empty strong { color: var(--eisc-ink); display: block; margin-bottom: 4px; font-size: 0.95rem; }
</style>

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

    <div class="eis-topbar">
        <div>
            <div class="eis-title"><i class="fas fa-shield-alt"></i> MRA EIS Compliance</div>
            <p class="eis-subtitle mb-0">Review and submit queued MRA EIS outbox items.</p>
        </div>
    </div>

    <?php if ($loadError): ?>
        <div class="alert fade show eis-alert alert-danger" role="alert">
            <i class="fas fa-circle-xmark"></i>
            <div>Could not load the outbox: <?php echo htmlspecialchars($loadError); ?></div>
        </div>
    <?php endif; ?>

    <?php if ($message): ?>
        <div class="alert fade show eis-alert alert-<?php echo htmlspecialchars($messageType); ?>" role="alert">
            <i class="fas <?php echo $alertMeta[$messageType]['icon'] ?? 'fa-circle-info'; ?>"></i>
            <div><?php echo htmlspecialchars($message); ?></div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="eis-card">
        <div class="eis-card-head">
            <h5><i class="fas fa-list"></i> EIS Compliance Outbox</h5>
            <span class="eis-count"><?php echo count($rows); ?> item(s) in this view</span>
        </div>
        <div class="eis-card-body">

            <div class="eis-stat-row">
                <?php foreach ($statusMeta as $key => $meta):
                    // 'queued' is a synthesized per-row display label (ready + prior
                    // attempts + an error), never a real outbox.status value, so it
                    // never has a meaningful count or a matching filter option here.
                    if ($key === 'queued') { continue; }
                    $n = $statusCounts[$key] ?? 0;
                    if ($n === 0 && $status !== $key) { continue; }
                    $isActive = $status === $key;
                    $href = '?status=' . urlencode($isActive ? '' : $key) . '&entity_type=' . urlencode($entityType);
                ?>
                    <a class="eis-stat tone-<?php echo $meta['tone']; ?><?php echo $isActive ? ' is-active' : ''; ?>" href="<?php echo htmlspecialchars($href); ?>">
                        <span class="dot"></span>
                        <div>
                            <div class="num"><?php echo (int)$n; ?></div>
                            <div class="lbl"><?php echo htmlspecialchars($meta['label']); ?></div>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>

            <form method="GET" class="eis-filter">
                <div class="fld">
                    <label for="statusFilter">Status</label>
                    <select name="status" id="statusFilter" class="form-select">
                        <option value="">All statuses</option>
                        <?php foreach (['ready','blocked','failed','submitted','pending'] as $option): ?>
                            <option value="<?php echo $option; ?>" <?php echo $status === $option ? 'selected' : ''; ?>><?php echo ucfirst($option); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="fld">
                    <label for="entityFilter">Module</label>
                    <select name="entity_type" id="entityFilter" class="form-select">
                        <option value="">All modules</option>
                        <?php foreach (['sale','transfer','void_receipt','stock_adjustment','initial_inventory','informal_purchase'] as $option): ?>
                            <option value="<?php echo $option; ?>" <?php echo $entityType === $option ? 'selected' : ''; ?>><?php echo ucwords(str_replace('_', ' ', $option)); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="btn btn-filter"><i class="fas fa-filter"></i> Filter</button>
                <?php if ($status !== '' || $entityType !== ''): ?>
                    <a href="?" class="btn-reset">Clear filters</a>
                <?php endif; ?>
            </form>

            <?php if (empty($rows)): ?>
                <div class="eis-empty">
                    <i class="fas fa-inbox"></i>
                    <strong>No EIS compliance items found</strong>
                    Nothing matches this filter right now.
                </div>
            <?php else: ?>
                <div class="table-responsive eis-table-wrap">
                    <table class="eis-table">
                        <thead>
                            <tr>
                                <th>Item</th>
                                <th>Branch / Terminal</th>
                                <th>Status</th>
                                <th>Endpoint</th>
                                <th>Payload</th>
                                <th>MRA Response</th>
                                <th>Submit</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($rows as $row): ?>
                                <tr>
                                    <td>
                                        <div class="item-title">
                                            <i class="fas <?php echo $entityIcons[$row['entity_type']] ?? 'fa-file'; ?>"></i>
                                            <?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $row['entity_type']))); ?>
                                        </div>
                                        <div class="mono-chip"><?php echo htmlspecialchars($row['source_key']); ?></div>
                                        <?php if (!empty($row['created_at'])): ?>
                                            <div class="queue-meta"><i class="fas fa-clock"></i> Queued <?php echo htmlspecialchars(date('d M Y H:i', strtotime($row['created_at']))); ?></div>
                                        <?php endif; ?>
                                        <?php if (!empty($row['updated_at']) && $row['updated_at'] !== $row['created_at']): ?>
                                            <div class="queue-meta"><i class="fas fa-pen"></i> Updated <?php echo htmlspecialchars(date('d M Y H:i', strtotime($row['updated_at']))); ?></div>
                                        <?php endif; ?>
                                        <?php if ((int)$row['attempts'] > 0): ?>
                                            <div class="attempt-pill"><i class="fas fa-arrows-rotate"></i> <?php echo (int)$row['attempts']; ?> attempt(s)</div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php echo htmlspecialchars($row['branch_name'] ?: 'Default'); ?>
                                        <div class="queue-meta"><?php echo htmlspecialchars($row['terminal_label'] ?: 'No terminal'); ?></div>
                                    </td>
                                    <td>
                                        <?php
                                        $isQueuedRetry = $row['status'] === 'ready' && (int)($row['attempts'] ?? 0) > 0 && !empty($row['last_error']);
                                        $statusKey = $isQueuedRetry ? 'queued' : $row['status'];
                                        $meta = $statusMeta[$statusKey] ?? ['label' => ucfirst($statusKey), 'icon' => 'fa-circle', 'tone' => 'neutral'];
                                        ?>
                                        <span class="status-pill tone-<?php echo $meta['tone']; ?>"><i class="fas <?php echo $meta['icon']; ?>"></i> <?php echo htmlspecialchars($meta['label']); ?></span>
                                        <?php if (!empty($row['last_error'])): ?>
                                            <div class="error-note"><?php echo htmlspecialchars($row['last_error']); ?></div>
                                        <?php endif; ?>
                                        <?php if (!empty($row['validation_url'])): ?>
                                            <div class="validation-link"><a href="<?php echo htmlspecialchars($row['validation_url']); ?>" target="_blank"><i class="fas fa-arrow-up-right-from-square"></i> Validation URL</a></div>
                                        <?php endif; ?>
                                    </td>
                                    <td><span class="endpoint-text" title="<?php echo htmlspecialchars($row['endpoint']); ?>"><?php echo htmlspecialchars($row['endpoint']); ?></span></td>
                                    <td>
                                        <details class="eis-detail">
                                            <summary>View JSON</summary>
                                            <pre class="payload-preview"><?php echo htmlspecialchars(json_encode(json_decode($row['payload_json'], true), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); ?></pre>
                                        </details>
                                        <?php if (!empty($row['local_audit_json'])): ?>
                                            <details class="eis-detail">
                                                <summary>IMS unique_code audit</summary>
                                                <pre class="payload-preview"><?php echo htmlspecialchars(json_encode(json_decode($row['local_audit_json'], true), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); ?></pre>
                                            </details>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if (empty($row['http_status']) && empty($row['response_body'])): ?>
                                            <span class="not-ready"><i class="fas fa-minus"></i> Not yet sent</span>
                                        <?php else: ?>
                                            <?php $httpTone = $httpStatusTone($row['http_status']); ?>
                                            <span class="status-pill tone-<?php echo $httpTone; ?>">
                                                <i class="fas <?php echo $httpTone === 'ok' ? 'fa-circle-check' : (($httpTone === 'neutral') ? 'fa-hourglass-half' : 'fa-triangle-exclamation'); ?>"></i>
                                                HTTP <?php echo (int)$row['http_status']; ?>
                                            </span>
                                            <?php if (!empty($row['submitted_at'])): ?>
                                                <div class="queue-meta"><i class="fas fa-paper-plane"></i> Submitted <?php echo htmlspecialchars(date('d M Y H:i', strtotime($row['submitted_at']))); ?></div>
                                            <?php endif; ?>
                                            <?php if (!empty($row['mra_reference'])): ?>
                                                <div class="mono-chip"><?php echo htmlspecialchars($row['mra_reference']); ?></div>
                                            <?php endif; ?>
                                            <?php if (!empty($row['response_body'])): ?>
                                                <details class="eis-detail">
                                                    <summary>Response body</summary>
                                                    <pre class="payload-preview"><?php echo htmlspecialchars($row['response_body']); ?></pre>
                                                </details>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($row['status'] === 'ready' || $row['status'] === 'failed'): ?>
                                            <form method="POST" onsubmit="return confirm('Submit this item to MRA EIS now?');">
                                                <input type="hidden" name="action" value="submit_outbox">
                                                <input type="hidden" name="outbox_id" value="<?php echo (int)$row['id']; ?>">
                                                <button type="submit" class="btn btn-sm btn-submit-outbox"><i class="fas fa-paper-plane"></i> Submit</button>
                                            </form>
                                        <?php else: ?>
                                            <span class="not-ready"><i class="fas fa-lock"></i> Not submit-ready</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

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