<?php

/**
 * Developer Console — Production Dashboard (DX003)
 *
 * Central Developer Experience Dashboard featuring:
 *   - Developer Summary Panel (App, DB, Mirror, Docs, Sync, Overall Health)
 *   - System Metrics (App Version, Env, PHP, MySQL, Supabase, Mirror, Tables, Routes, Modules, Storage, Sync, Health)
 *   - Quick Actions Bar
 *   - Module Navigation Cards
 *
 * Variables:
 *   $mysql_data     — array from MySqlInspectorService::inspect()
 *   $supabase_info  — array from SupabaseService::getProjectInfo()
 *   $sync_status    — array from SynchronizationService::getStatus()
 *   $health         — array from SystemHealthService::inspectHealth()
 *   $db_overview    — array from DeveloperService::getDatabaseOverview()
 *   $app_info       — array from DeveloperService::getApplicationInfo()
 *   $total_routes   — int
 *   $total_modules  — int
 *   $storage_usage  — array
 *   $doc_status     — array
 *
 * @package Inveetaire
 * @ref     DX001, DX002A, DX002B, DX003
 */

/** @var array $mysql_data */
/** @var array $supabase_info */
/** @var array $sync_status */
/** @var array $health */
/** @var array $db_overview */
/** @var array $app_info */
/** @var int $total_routes */
/** @var int $total_modules */
/** @var array $storage_usage */
/** @var array $doc_status */

$mysql_data    = $mysql_data    ?? [];
$supabase_info = $supabase_info ?? [];
$sync_status   = $sync_status   ?? [];
$health        = $health        ?? [];
$db_overview   = $db_overview   ?? [];
$app_info      = $app_info      ?? [];
$total_routes  = $total_routes  ?? 0;
$total_modules = $total_modules ?? 0;
$storage_usage = $storage_usage ?? ['formatted' => '0 MB'];

$overallStatus = $health['overall_status'] ?? 'healthy';
$sbConfigured  = (bool)($supabase_info['configured'] ?? false);
$mysqlConnected = (bool)($mysql_data['connected'] ?? false);
$lastSync      = $sync_status['last_sync'] ?? 'Never';

$testSupabaseUrl = 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;">
        INVEETAIRE / Developer Dashboard
    </div>
    <div style="display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:1rem;">
        <div>
            <h1 style="font-size: 1.5rem; font-weight: 800; color: var(--dev-text); margin-bottom: 0.25rem;">
                Developer Dashboard
            </h1>
            <p style="font-size: 0.8125rem; color: var(--dev-text-muted);">
                Production-grade system monitoring, health diagnostics, database introspection, and cloud mirror management.
            </p>
        </div>
        <div>
            <span class="badge-dev" style="font-size:0.75rem; padding:0.4rem 0.8rem;">
                <i class="fa-solid fa-code"></i> DX003 v1.0.0
            </span>
        </div>
    </div>
</div>

<!-- ══════════════════════════════════════════════════════════════════════════ -->
<!-- FEATURE 10 — DEVELOPER SUMMARY PANEL                                      -->
<!-- ══════════════════════════════════════════════════════════════════════════ -->
<div class="dev-card" style="margin-bottom: 2rem; border-color: rgba(88,166,255,0.25);">
    <div class="dev-card-header" style="background: rgba(88,166,255,0.04);">
        <span class="dev-card-title">
            <i class="fa-solid fa-gauge-high" style="color:var(--dev-accent); margin-right:0.375rem;"></i>
            Developer Summary
        </span>
        <span class="<?= $overallStatus === 'healthy' ? 'badge-ok' : ($overallStatus === 'warning' ? 'badge-warn' : 'badge-err') ?>">
            ● Overall: <?= strtoupper($overallStatus) ?>
        </span>
    </div>
    <div class="dev-card-body">
        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); gap: 1.25rem;">

            <div>
                <div class="dev-stat-label">App Status</div>
                <div style="margin-top:0.375rem;">
                    <span class="badge-ok"><i class="fa-solid fa-check"></i> Operational</span>
                </div>
                <div class="dev-stat-sub">ENV: <?= strtoupper(config('app.env', 'local')) ?></div>
            </div>

            <div>
                <div class="dev-stat-label">Database Status</div>
                <div style="margin-top:0.375rem;">
                    <?php if ($mysqlConnected): ?>
                        <span class="badge-ok"><i class="fa-solid fa-database"></i> Connected</span>
                    <?php else: ?>
                        <span class="badge-err"><i class="fa-solid fa-xmark"></i> Failed</span>
                    <?php endif; ?>
                </div>
                <div class="dev-stat-sub"><?= (int)($db_overview['total_tables'] ?? 0) ?> tables</div>
            </div>

            <div>
                <div class="dev-stat-label">Mirror Status</div>
                <div style="margin-top:0.375rem;">
                    <?php if (!$sbConfigured): ?>
                        <span class="badge-warn">Not Configured</span>
                    <?php else: ?>
                        <span class="badge-ok">Configured</span>
                    <?php endif; ?>
                </div>
                <div class="dev-stat-sub"><?= $sbConfigured ? 'Supabase PG' : 'No cloud mirror' ?></div>
            </div>

            <div>
                <div class="dev-stat-label">Documentation Status</div>
                <div style="margin-top:0.375rem;">
                    <span class="badge-dev">Complete</span>
                </div>
                <div class="dev-stat-sub">Version <?= escape_html($db_overview['doc_version'] ?? 'v1.0.0') ?></div>
            </div>

            <div>
                <div class="dev-stat-label">Sync Status</div>
                <div style="margin-top:0.375rem;">
                    <span class="badge-busy"><?= escape_html($sync_status['execution_mode'] ?? 'Ready') ?></span>
                </div>
                <div class="dev-stat-sub">Last: <?= escape_html($lastSync) ?></div>
            </div>

            <div>
                <div class="dev-stat-label">System Health</div>
                <div style="margin-top:0.375rem;">
                    <span class="<?= $overallStatus === 'healthy' ? 'badge-ok' : ($overallStatus === 'warning' ? 'badge-warn' : 'badge-err') ?>">
                        <?= strtoupper($overallStatus) ?>
                    </span>
                </div>
                <div class="dev-stat-sub"><a href="<?= url('/app/developer/health') ?>" style="color:var(--dev-accent); text-decoration:none;">Inspect →</a></div>
            </div>

        </div>
    </div>
</div>

<!-- ══════════════════════════════════════════════════════════════════════════ -->
<!-- FEATURE 9 — QUICK ACTIONS                                                  -->
<!-- ══════════════════════════════════════════════════════════════════════════ -->
<div class="dev-section-title" style="margin-bottom: 0.75rem;">Quick Actions</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;">

        <button id="btn-quick-test-sb" onclick="runQuickSupabaseTest()" <?= !$sbConfigured ? 'disabled' : '' ?>
                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.3); border-radius:6px; font-family:var(--mono); font-size:0.75rem; color:#3ecf8e; cursor:pointer;">
            <i class="fa-solid fa-plug"></i> Test Supabase Connection
        </button>

        <a href="<?= url('/app/developer/sync') ?>"
           style="display:inline-flex; align-items:center; gap:0.5rem; padding:0.5rem 1rem; background:rgba(88,166,255,0.1); border:1px solid rgba(88,166,255,0.3); border-radius:6px; font-family:var(--mono); font-size:0.75rem; color:var(--dev-accent); text-decoration:none;">
            <i class="fa-solid fa-code-compare"></i> Compare Schema
        </a>

        <a href="<?= url('/app/developer/sync') ?>"
           style="display:inline-flex; align-items:center; gap:0.5rem; padding:0.5rem 1rem; background:rgba(63,185,80,0.1); border:1px solid rgba(63,185,80,0.3); border-radius:6px; font-family:var(--mono); font-size:0.75rem; color:var(--dev-accent2); text-decoration:none;">
            <i class="fa-solid fa-shield-check"></i> Verify Mirror
        </a>

        <a href="<?= url('/app/developer/sync') ?>"
           style="display:inline-flex; align-items:center; gap:0.5rem; padding:0.5rem 1rem; background:rgba(188,140,255,0.1); border:1px solid rgba(188,140,255,0.3); border-radius:6px; font-family:var(--mono); font-size:0.75rem; color:var(--dev-purple); text-decoration:none;">
            <i class="fa-solid fa-arrows-rotate"></i> Open Sync Center
        </a>

        <a href="<?= url('/app/developer/inspector') ?>"
           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:var(--dev-text); text-decoration:none;">
            <i class="fa-solid fa-table"></i> Open Database Inspector
        </a>

        <a href="<?= url('/app/developer/mapping') ?>"
           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:var(--dev-rose); text-decoration:none;">
            <i class="fa-solid fa-diagram-project"></i> Open Mapping Reference
        </a>

    </div>
    <div id="quick-test-result" style="display:none; padding:0.75rem 1.25rem; border-top:1px solid var(--dev-border2); font-family:var(--mono); font-size:0.75rem;"></div>
</div>

<!-- ══════════════════════════════════════════════════════════════════════════ -->
<!-- FEATURE 1 — SYSTEM METRICS CARDS (12 CARDS)                                -->
<!-- ══════════════════════════════════════════════════════════════════════════ -->
<div class="dev-section-title" style="margin-bottom: 0.75rem;">System Metrics</div>
<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 1rem; margin-bottom: 2rem;">

    <!-- 1. App Version -->
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">App Version</div>
        <div class="dev-stat-value" style="font-size:1.125rem; color:var(--dev-text);"><?= escape_html($app_info['app_version'] ?? '1.0.0') ?></div>
        <div class="dev-stat-sub">INVEETAIRE Core</div>
    </div>

    <!-- 2. Environment -->
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">Environment</div>
        <div class="dev-stat-value" style="font-size:1.125rem; color:var(--dev-purple);"><?= strtoupper((string)config('app.env', 'local')) ?></div>
        <div class="dev-stat-sub">APP_ENV setting</div>
    </div>

    <!-- 3. PHP Version -->
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">PHP Version</div>
        <div class="dev-stat-value" style="font-size:1.125rem; color:var(--dev-accent);"><?= PHP_VERSION ?></div>
        <div class="dev-stat-sub"><?= PHP_SAPI ?></div>
    </div>

    <!-- 4. MySQL Version -->
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">MySQL Version</div>
        <div class="dev-stat-value" style="font-size:1.125rem;"><?= escape_html($mysql_data['db_version_short'] ?? '—') ?></div>
        <div class="dev-stat-sub"><?= escape_html($mysql_data['db_name'] ?? 'inveetaire') ?></div>
    </div>

    <!-- 5. Supabase Status -->
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">Supabase Status</div>
        <div style="margin-top:0.25rem;">
            <?php if ($sbConfigured): ?>
                <span class="badge-ok">Configured</span>
            <?php else: ?>
                <span class="badge-warn">Not Configured</span>
            <?php endif; ?>
        </div>
        <div class="dev-stat-sub"><?= escape_html($supabase_info['region'] ?? '—') ?></div>
    </div>

    <!-- 6. Mirror Status -->
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">Mirror Status</div>
        <div class="dev-stat-value" style="font-size:1rem; color:var(--dev-warn);"><?= escape_html($supabase_info['mirror_status'] ?? 'Not Synced') ?></div>
        <div class="dev-stat-sub">Read-only mirror</div>
    </div>

    <!-- 7. Database Tables -->
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">Database Tables</div>
        <div class="dev-stat-value" style="color:var(--dev-accent);"><?= (int)($db_overview['total_tables'] ?? 0) ?></div>
        <div class="dev-stat-sub"><?= number_format((int)($db_overview['total_columns'] ?? 0)) ?> columns</div>
    </div>

    <!-- 8. Total Routes -->
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">Total Routes</div>
        <div class="dev-stat-value" style="color:var(--dev-accent2);"><?= $total_routes ?></div>
        <div class="dev-stat-sub">registered endpoints</div>
    </div>

    <!-- 9. Total Modules -->
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">Total Modules</div>
        <div class="dev-stat-value" style="color:var(--dev-rose);"><?= $total_modules ?></div>
        <div class="dev-stat-sub">app/modules/</div>
    </div>

    <!-- 10. Storage Usage -->
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">Storage Usage</div>
        <div class="dev-stat-value" style="font-size:1.125rem;"><?= escape_html($storage_usage['formatted'] ?? '0 MB') ?></div>
        <div class="dev-stat-sub"><?= (int)($storage_usage['file_count'] ?? 0) ?> files in storage/</div>
    </div>

    <!-- 11. Last Sync -->
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">Last Sync</div>
        <div class="dev-stat-value" style="font-size:0.875rem; font-family:var(--mono); margin-top:0.25rem;"><?= escape_html($lastSync) ?></div>
        <div class="dev-stat-sub"><?= (int)($sync_status['total_syncs'] ?? 0) ?> total syncs</div>
    </div>

    <!-- 12. System Health -->
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">System Health</div>
        <div style="margin-top:0.25rem;">
            <span class="<?= $overallStatus === 'healthy' ? 'badge-ok' : ($overallStatus === 'warning' ? 'badge-warn' : 'badge-err') ?>">
                ● <?= strtoupper($overallStatus) ?>
            </span>
        </div>
        <div class="dev-stat-sub"><a href="<?= url('/app/developer/health') ?>" style="color:var(--dev-text-muted); text-decoration:none;">View Report →</a></div>
    </div>

</div>

<!-- ══════════════════════════════════════════════════════════════════════════ -->
<!-- MODULE CARDS GRID                                                          -->
<!-- ══════════════════════════════════════════════════════════════════════════ -->
<div class="dev-section-title" style="margin-bottom: 0.75rem;">Developer Console Modules</div>
<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 1rem; margin-bottom: 2rem;">

    <!-- Database -->
    <a href="<?= url('/app/developer/database') ?>" class="dev-feature-card" id="dev-card-database">
        <div class="dev-feature-icon"><i class="fa-solid fa-database"></i></div>
        <div class="dev-feature-title">Database</div>
        <div class="dev-feature-desc">MySQL Inspector — tables, columns, constraints, engine, charset, collation, and size.</div>
        <div style="margin-top: 1rem;"><span class="badge-ok">● Available</span></div>
    </a>

    <!-- Schema Documentation -->
    <a href="<?= url('/app/developer/schema') ?>" class="dev-feature-card" id="dev-card-schema">
        <div class="dev-feature-icon" style="color: var(--dev-purple);"><i class="fa-solid fa-file-code"></i></div>
        <div class="dev-feature-title">Schema Documentation</div>
        <div class="dev-feature-desc">Documentation files: README, AI Context, Relationships, Changelog, per-table docs.</div>
        <div style="margin-top: 1rem;"><span class="badge-ok">● Available</span></div>
    </a>

    <!-- Supabase Inspector -->
    <a href="<?= url('/app/developer/supabase') ?>" class="dev-feature-card" id="dev-card-supabase">
        <div class="dev-feature-icon" style="color: #3ecf8e;"><i class="fa-solid fa-cloud"></i></div>
        <div class="dev-feature-title">Supabase Inspector</div>
        <div class="dev-feature-desc">Supabase mirror configuration, connection test, project info, and mirror status.</div>
        <div style="margin-top: 1rem;"><span class="badge-ok">● Available</span></div>
    </a>

    <!-- DB Inspector -->
    <a href="<?= url('/app/developer/inspector') ?>" class="dev-feature-card" id="dev-card-inspector">
        <div class="dev-feature-icon" style="color: var(--dev-accent);"><i class="fa-solid fa-table"></i></div>
        <div class="dev-feature-title">DB Inspector</div>
        <div class="dev-feature-desc">Side-by-side MySQL and Supabase schema comparison and table inventory.</div>
        <div style="margin-top: 1rem;"><span class="badge-ok">● Available</span></div>
    </a>

    <!-- Type Mapping -->
    <a href="<?= url('/app/developer/mapping') ?>" class="dev-feature-card" id="dev-card-mapping">
        <div class="dev-feature-icon" style="color: var(--dev-rose);"><i class="fa-solid fa-diagram-project"></i></div>
        <div class="dev-feature-title">Type Mapping</div>
        <div class="dev-feature-desc">MySQL → PostgreSQL data type mapping reference for DDL generation.</div>
        <div style="margin-top: 1rem;"><span class="badge-ok">● Available</span></div>
    </a>

    <!-- Synchronization -->
    <a href="<?= url('/app/developer/sync') ?>" class="dev-feature-card" id="dev-card-sync">
        <div class="dev-feature-icon" style="color: #3ecf8e;"><i class="fa-solid fa-arrows-rotate"></i></div>
        <div class="dev-feature-title">Synchronization</div>
        <div class="dev-feature-desc">Compare, dry run, generate DDL, push MySQL → Supabase, verify mirror.</div>
        <div style="margin-top: 1rem;"><span class="badge-ok">● Available</span></div>
    </a>

    <!-- Sync Log -->
    <a href="<?= url('/app/developer/sync/log') ?>" class="dev-feature-card" id="dev-card-sync-log">
        <div class="dev-feature-icon" style="color: var(--dev-text-muted);"><i class="fa-solid fa-clock-rotate-left"></i></div>
        <div class="dev-feature-title">Sync Log</div>
        <div class="dev-feature-desc">Synchronization history: timestamps, affected tables, results, duration, errors.</div>
        <div style="margin-top: 1rem;"><span class="badge-ok">● Available</span></div>
    </a>

    <!-- System Health -->
    <a href="<?= url('/app/developer/health') ?>" class="dev-feature-card" id="dev-card-health">
        <div class="dev-feature-icon" style="color: var(--dev-accent2);"><i class="fa-solid fa-heartbeat"></i></div>
        <div class="dev-feature-title">System Health</div>
        <div class="dev-feature-desc">Diagnostics suite: DB, Supabase, Storage, Logs, Cache, Extensions, Limits.</div>
        <div style="margin-top: 1rem;"><span class="badge-ok">● Available</span></div>
    </a>

    <!-- Log Center -->
    <a href="<?= url('/app/developer/logs') ?>" class="dev-feature-card" id="dev-card-logs">
        <div class="dev-feature-icon" style="color: var(--dev-accent);"><i class="fa-solid fa-scroll"></i></div>
        <div class="dev-feature-title">Log Center</div>
        <div class="dev-feature-desc">Centralized logs: Sync Logs, Application Logs, PHP Error Logs, Activity Feed.</div>
        <div style="margin-top: 1rem;"><span class="badge-ok">● Available</span></div>
    </a>

    <!-- Application Info -->
    <a href="<?= url('/app/developer/info') ?>" class="dev-feature-card" id="dev-card-info">
        <div class="dev-feature-icon" style="color: var(--dev-purple);"><i class="fa-solid fa-circle-info"></i></div>
        <div class="dev-feature-title">Application Info</div>
        <div class="dev-feature-desc">System specification, framework metadata, build info, and environment settings.</div>
        <div style="margin-top: 1rem;"><span class="badge-ok">● Available</span></div>
    </a>

</div>

<script>
function runQuickSupabaseTest() {
    const btn = document.getElementById('btn-quick-test-sb');
    const res = document.getElementById('quick-test-result');
    if (!btn || !res) return;

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

    fetch('<?= escape_javascript($testSupabaseUrl) ?>', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(r => r.json())
    .then(data => {
        res.style.display = 'block';
        if (data.connected) {
            res.style.color = 'var(--dev-accent2)';
            res.innerHTML = `✓ Connected to Supabase! Response time: ${data.response_time_ms} ms (${data.tested_at})`;
        } else {
            res.style.color = 'var(--dev-danger)';
            res.innerHTML = `✕ Supabase test failed: ${data.error || 'Unknown error'}`;
        }
    })
    .catch(err => {
        res.style.display = 'block';
        res.style.color = 'var(--dev-danger)';
        res.innerHTML = `✕ Error: ${err.message}`;
    })
    .finally(() => {
        btn.disabled = false;
        btn.innerHTML = '<i class="fa-solid fa-plug"></i> Test Supabase Connection';
    });
}
</script>
