<?php

/**
 * Developer Console — Supabase Inspector (DX002A)
 *
 * Dedicated Supabase page showing:
 *   - Configuration status and masked credentials
 *   - Connection status (live test button via AJAX)
 *   - Project info: URL, region, PG version, schemas
 *   - Mirror status + Sync status (Coming in DX002B)
 *   - Disabled DX002B action buttons
 *
 * Variables:
 *   $project_info  — from SupabaseService::getProjectInfo()
 *   $config_status — from SupabaseService::getConfigStatus()
 *   $schemas       — list<string> from SupabaseService::getAvailableSchemas()
 *
 * @package Inveetaire
 * @ref     DX002A
 */

/** @var array $project_info */
/** @var array $config_status */
/** @var array $schemas */
$project_info  = $project_info  ?? [];
$config_status = $config_status ?? [];
$schemas       = $schemas       ?? [];
$configured    = (bool)($config_status['configured'] ?? false);

$testUrl = url('/app/developer/supabase/test');

?>

<!-- Page Header -->
<div style="margin-bottom: 2rem;">
    <div style="font-family: var(--mono); font-size: 0.6875rem; color: var(--dev-text-muted); margin-bottom: 0.5rem;">
        <a href="<?= url('/app/developer') ?>" style="color:var(--dev-accent); text-decoration:none;">developer</a>
        <span style="color:#444c56;"> / </span>
        <span style="color:#3ecf8e;">supabase</span>
    </div>
    <h1 style="font-size: 1.5rem; font-weight: 800; color: var(--dev-text); margin-bottom: 0.25rem;">
        Supabase Mirror
    </h1>
    <p style="font-size: 0.8125rem; color: var(--dev-text-muted);">
        Cloud mirror infrastructure. MySQL remains the source of truth.
        Synchronization features available in <span style="color:var(--dev-purple);">DX002B</span>.
    </p>
</div>

<!-- Status Banner -->
<div class="dev-card" style="margin-bottom: 2rem; border-color: <?= $configured ? 'rgba(62,207,142,0.3)' : 'rgba(210,153,34,0.3)' ?>;">
    <div class="dev-card-body" style="display:flex; align-items:center; gap:1.5rem; flex-wrap:wrap;">
        <div style="font-size:2rem; color:<?= $configured ? '#3ecf8e' : '#d29922' ?>;">
            <i class="fa-solid fa-<?= $configured ? 'cloud-arrow-up' : 'cloud-slash' ?>"></i>
        </div>
        <div>
            <div style="font-weight:700; font-size:0.9375rem; color:var(--dev-text); margin-bottom:0.125rem;">
                <?= $configured ? 'Supabase Configured' : 'Supabase Not Configured' ?>
            </div>
            <div style="font-size:0.8125rem; color:var(--dev-text-muted);">
                <?= $configured
                    ? 'Credentials are set. Use the Test Connection button to verify connectivity.'
                    : 'Add Supabase credentials to .env to enable cloud mirror features.' ?>
            </div>
        </div>
        <div style="margin-left:auto; display:flex; align-items:center; gap:0.75rem;">
            <?php if ($configured): ?>
                <button id="btn-test-connection"
                        onclick="runConnectionTest()"
                        style="display:inline-flex; align-items:center; gap:0.5rem; padding:0.5rem 1rem; background:rgba(62,207,142,0.1); border:1px solid rgba(62,207,142,0.35); border-radius:6px; font-family:var(--mono); font-size:0.75rem; color:#3ecf8e; cursor:pointer; transition:background 0.15s;"
                        onmouseover="this.style.background='rgba(62,207,142,0.18)'"
                        onmouseout="this.style.background='rgba(62,207,142,0.1)'">
                    <i class="fa-solid fa-plug-circle-check"></i>
                    Test Connection
                </button>
            <?php endif; ?>
            <a href="<?= url('/app/developer/database') ?>" style="font-family:var(--mono); font-size:0.75rem; color:var(--dev-text-muted); text-decoration:none;">
                ← Back to Database
            </a>
        </div>
    </div>
</div>

<!-- Connection Test Result (hidden until test runs) -->
<div id="test-result" style="display:none; margin-bottom:1.5rem;" role="status" aria-live="polite">
    <div class="dev-card" id="test-result-card">
        <div class="dev-card-header">
            <span class="dev-card-title" id="test-result-title">Connection Test Result</span>
            <span id="test-result-badge"></span>
        </div>
        <div class="dev-card-body" id="test-result-body" style="display:grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap:1rem;">
        </div>
    </div>
</div>

<!-- ══════════════════════════════════════════════════════════════════════════ -->
<!-- Configuration Panel                                                        -->
<!-- ══════════════════════════════════════════════════════════════════════════ -->

<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; margin-bottom: 2rem;">

    <!-- Credentials (Masked) -->
    <div class="dev-card">
        <div class="dev-card-header">
            <span class="dev-card-title">
                <i class="fa-solid fa-key" style="color:var(--dev-warn); margin-right:0.375rem;"></i>
                Configuration
            </span>
            <?php if ($configured): ?>
                <span class="badge-ok">● Set</span>
            <?php else: ?>
                <span class="badge-warn">Not Set</span>
            <?php endif; ?>
        </div>
        <div class="dev-card-body">
            <div class="dev-info-row">
                <span class="label">SUPABASE_URL</span>
                <span class="value" style="font-size:0.6875rem;"><?= escape_html($config_status['url_masked'] ?? 'Not configured') ?></span>
            </div>
            <div class="dev-info-row">
                <span class="label">PROJECT_REF</span>
                <span class="value"><?= escape_html($config_status['project_ref_masked'] ?? 'Not configured') ?></span>
            </div>
            <div class="dev-info-row">
                <span class="label">REGION</span>
                <span class="value"><?= escape_html($config_status['region'] ?? '—') ?></span>
            </div>
            <div class="dev-info-row">
                <span class="label">ANON_KEY</span>
                <span class="value" style="font-size:0.6875rem; letter-spacing:0.05em;"><?= escape_html($config_status['anon_key_masked'] ?? 'Not configured') ?></span>
            </div>
            <div class="dev-info-row">
                <span class="label">SERVICE_ROLE_KEY</span>
                <span class="value" style="letter-spacing:0.1em; color:var(--dev-text-muted);">
                    <?= ($config_status['has_service_role'] ?? false) ? '••••••••••••••••' : 'Not set' ?>
                </span>
            </div>
            <div style="margin-top:0.75rem; font-size:0.6875rem; color:var(--dev-text-muted); font-style:italic;">
                Credentials are masked. Service Role Key is never rendered.
            </div>
        </div>
    </div>

    <!-- Project Info -->
    <div class="dev-card">
        <div class="dev-card-header">
            <span class="dev-card-title">
                <i class="fa-solid fa-circle-info" style="color:#3ecf8e; margin-right:0.375rem;"></i>
                Project Info
            </span>
        </div>
        <div class="dev-card-body">
            <div class="dev-info-row">
                <span class="label">Project Name</span>
                <span class="value"><?= escape_html($config_status['project_ref_masked'] ?? '—') ?></span>
            </div>
            <div class="dev-info-row">
                <span class="label">Region</span>
                <span class="value"><?= escape_html($config_status['region'] ?? '—') ?></span>
            </div>
            <div class="dev-info-row">
                <span class="label">PostgreSQL Version</span>
                <span class="value" id="pg-version-cell">—</span>
            </div>
            <div class="dev-info-row">
                <span class="label">Available Schemas</span>
                <span class="value">
                    <?= $configured && !empty($schemas)
                        ? implode(', ', array_map('escape_html', $schemas))
                        : '—' ?>
                </span>
            </div>
            <div class="dev-info-row">
                <span class="label">Connection Status</span>
                <span class="value" id="connection-status-cell">
                    <?= $configured ? 'Not Tested' : '—' ?>
                </span>
            </div>
        </div>
    </div>

</div>

<!-- Mirror & Sync Status -->
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; margin-bottom: 2rem;">

    <div class="dev-card">
        <div class="dev-card-header">
            <span class="dev-card-title">
                <i class="fa-solid fa-server" style="color:var(--dev-warn); margin-right:0.375rem;"></i>
                Mirror Status
            </span>
            <span class="badge-warn">Not Synced</span>
        </div>
        <div class="dev-card-body">
            <div class="dev-info-row">
                <span class="label">Mirror Status</span>
                <span class="value" style="color:var(--dev-warn);"><?= escape_html($project_info['mirror_status'] ?? 'Not Synced') ?></span>
            </div>
            <div class="dev-info-row">
                <span class="label">Last Push</span>
                <span class="value" style="color:#444c56;">Never</span>
            </div>
            <div class="dev-info-row">
                <span class="label">Last Pull</span>
                <span class="value" style="color:#444c56;">Never</span>
            </div>
        </div>
    </div>

    <div class="dev-card">
        <div class="dev-card-header">
            <span class="dev-card-title">
                <i class="fa-solid fa-arrows-rotate" style="color:#444c56; margin-right:0.375rem;"></i>
                Synchronization Status
            </span>
            <span class="badge-soon">DX002B</span>
        </div>
        <div class="dev-card-body">
            <div class="dev-info-row">
                <span class="label">Sync Status</span>
                <span class="value" style="color:var(--dev-purple);"><?= escape_html($project_info['sync_status'] ?? 'Coming in DX002B') ?></span>
            </div>
            <div class="dev-info-row">
                <span class="label">Schema Drift</span>
                <span class="value" style="color:#444c56;">—</span>
            </div>
            <div style="margin-top:0.75rem; padding:0.625rem; background:rgba(188,140,255,0.06); border:1px solid rgba(188,140,255,0.15); border-radius:6px; font-size:0.6875rem; color:var(--dev-text-muted);">
                Full synchronization tooling is planned for <span style="color:var(--dev-purple);">DX002B</span>.
            </div>
        </div>
    </div>

</div>

<!-- DX002B Action Buttons (disabled placeholders) -->
<div class="dev-section-title" style="margin-bottom: 1rem;">
    DX002B Actions — Coming Soon
</div>
<div class="dev-card" style="margin-bottom: 2rem;">
    <div class="dev-card-body" style="display:flex; flex-wrap:wrap; gap:0.75rem; align-items:center;">

        <?php
        $dx002bActions = [
            ['icon' => 'fa-cloud-arrow-up',     'label' => 'Push to Supabase'],
            ['icon' => 'fa-cloud-arrow-down',    'label' => 'Pull from Supabase'],
            ['icon' => 'fa-shield-check',        'label' => 'Verify Mirror'],
            ['icon' => 'fa-file-code',           'label' => 'Generate Schema'],
            ['icon' => 'fa-code-compare',        'label' => 'Compare Schema'],
        ];
        foreach ($dx002bActions as $action):
        ?>
            <div style="display:flex; flex-direction:column; align-items:center; gap:0.375rem;">
                <button disabled
                        style="display:inline-flex; align-items:center; gap:0.5rem; padding:0.5rem 1rem; background:var(--dev-surface2); border:1px solid var(--dev-border); border-radius:6px; font-family:var(--mono); font-size:0.75rem; color:#444c56; cursor:not-allowed;">
                    <i class="fa-solid <?= $action['icon'] ?>"></i>
                    <?= escape_html($action['label']) ?>
                </button>
                <span style="font-family:var(--mono); font-size:0.5rem; color:var(--dev-purple); letter-spacing:0.05em;">Available in DX002B</span>
            </div>
        <?php endforeach; ?>

        <div style="margin-left:auto; font-size:0.6875rem; color:var(--dev-text-muted); font-family:var(--mono); display:flex; align-items:center;">
            Synchronization features arrive in sprint DX002B.
        </div>
    </div>
</div>

<?php if ($configured): ?>
<script>
function runConnectionTest() {
    const btn = document.getElementById('btn-test-connection');
    const resultBox = document.getElementById('test-result');
    const body = document.getElementById('test-result-body');
    const badge = document.getElementById('test-result-badge');
    const title = document.getElementById('test-result-title');

    btn.disabled = true;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Testing...';
    resultBox.style.display = 'none';

    fetch('<?= escape_javascript($testUrl) ?>', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({})
    })
    .then(r => r.json())
    .then(data => {
        resultBox.style.display = 'block';
        const ok = data.connected;

        badge.innerHTML = ok
            ? '<span class="badge-ok">● Connected</span>'
            : '<span class="badge-err">✕ Failed</span>';

        const pgCell = document.getElementById('pg-version-cell');
        if (pgCell && data.pg_version && data.pg_version !== '—') {
            pgCell.textContent = data.pg_version;
        }

        const csCell = document.getElementById('connection-status-cell');
        if (csCell) {
            csCell.textContent = ok ? 'Connected' : 'Failed';
            csCell.style.color = ok ? 'var(--dev-accent2)' : 'var(--dev-danger)';
        }

        const fields = [
            { label: 'Connected',       value: ok ? 'Yes' : 'No',              color: ok ? 'var(--dev-accent2)' : 'var(--dev-danger)' },
            { label: 'HTTP Status',     value: data.http_status || '—',         color: '' },
            { label: 'Response Time',   value: (data.response_time_ms || 0) + ' ms', color: '' },
            { label: 'PG Version',      value: data.pg_version || '—',          color: '' },
            { label: 'Region',          value: data.region || '—',              color: '' },
            { label: 'Tested At',       value: data.tested_at || '—',           color: '' },
        ];

        body.innerHTML = fields.map(f =>
            `<div>
                <div class="dev-stat-label">${f.label}</div>
                <div class="dev-stat-value" style="font-size:0.875rem; ${f.color ? 'color:'+f.color : ''}">${f.value}</div>
            </div>`
        ).join('');

        if (data.error) {
            body.innerHTML += `<div style="grid-column:1/-1; margin-top:0.5rem; padding:0.75rem; background:rgba(248,81,73,0.08); border:1px solid rgba(248,81,73,0.2); border-radius:6px; font-family:var(--mono); font-size:0.6875rem; color:var(--dev-danger);">${data.error}</div>`;
        }
    })
    .catch(err => {
        resultBox.style.display = 'block';
        badge.innerHTML = '<span class="badge-err">✕ Error</span>';
        body.innerHTML = `<div style="grid-column:1/-1; padding:0.75rem; background:rgba(248,81,73,0.08); border:1px solid rgba(248,81,73,0.2); border-radius:6px; font-family:var(--mono); font-size:0.6875rem; color:var(--dev-danger);">JavaScript error: ${err.message}</div>`;
    })
    .finally(() => {
        btn.disabled = false;
        btn.innerHTML = '<i class="fa-solid fa-plug-circle-check"></i> Test Connection';
    });
}
</script>
<?php endif; ?>
