<?php

/**
 * Developer Console — Centralized Log Center (DX003)
 *
 * View, filter, clear, and download application logs:
 *   - Synchronization Logs
 *   - Application Logs
 *   - PHP Error Logs
 *   - Aggregated Activity Feed
 *
 * Variables:
 *   $current_type — string ('all'|'sync'|'app'|'php_error')
 *   $logs         — list<array> from LogManagerService::getLogs()
 *   $log_files    — list<array> from LogManagerService::getLogFilesList()
 *
 * @package Inveetaire
 * @ref     DX003
 */

/** @var string $current_type */
/** @var array $logs */
/** @var array $log_files */
$current_type = $current_type ?? 'all';
$logs         = $logs         ?? [];
$log_files    = $log_files    ?? [];

$clearUrl    = url('/app/developer/logs/clear');
$downloadUrl = url('/app/developer/logs/download');

?>

<!-- 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:var(--dev-accent);">logs</span>
    </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;">
                Log Center
            </h1>
            <p style="font-size: 0.8125rem; color: var(--dev-text-muted);">
                Centralized monitoring for synchronization events, application runtime logs, and PHP system errors.
            </p>
        </div>
        <div style="display:flex; gap:0.5rem; flex-wrap:wrap;">
            <button onclick="window.location.reload()"
                    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); cursor:pointer;">
                <i class="fa-solid fa-rotate-right"></i> Refresh
            </button>
            <?php if ($current_type !== 'all'): ?>
            <a href="<?= $downloadUrl ?>?type=<?= urlencode($current_type) ?>"
               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; text-decoration:none;">
                <i class="fa-solid fa-download"></i> Download Log
            </a>
            <?php endif; ?>
            <button onclick="confirmClearLog('<?= escape_javascript($current_type) ?>')"
                    style="display:inline-flex; align-items:center; gap:0.5rem; padding:0.5rem 1rem; 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.75rem; color:var(--dev-danger); cursor:pointer;">
                <i class="fa-solid fa-trash-can"></i> Clear Log
            </button>
        </div>
    </div>
</div>

<!-- Tab Navigation -->
<div style="display:flex; gap:0.5rem; margin-bottom:1.5rem; border-bottom:1px solid var(--dev-border2); padding-bottom:0.75rem;">
    <?php
    $tabs = [
        'all'       => ['icon' => 'fa-list-ul',          'label' => 'All Activity'],
        'sync'      => ['icon' => 'fa-arrows-rotate',    'label' => 'Sync Logs'],
        'app'       => ['icon' => 'fa-laptop-code',      'label' => 'Application Logs'],
        'php_error' => ['icon' => 'fa-bug',              'label' => 'PHP Errors'],
    ];
    foreach ($tabs as $key => $tab):
        $isActive = ($current_type === $key);
    ?>
        <a href="<?= url('/app/developer/logs') ?>?type=<?= $key ?>"
           style="display:inline-flex; align-items:center; gap:0.5rem; padding:0.5rem 1rem; border-radius:6px; font-family:var(--mono); font-size:0.75rem; text-decoration:none; transition:all 0.15s; <?= $isActive ? 'background:var(--dev-surface2); border:1px solid var(--dev-border); color:var(--dev-text); font-weight:700;' : 'color:var(--dev-text-muted);' ?>">
            <i class="fa-solid <?= $tab['icon'] ?>"></i> <?= escape_html($tab['label']) ?>
        </a>
    <?php endforeach; ?>
</div>

<!-- Log Files Overview -->
<?php if (!empty($log_files)): ?>
<div style="display:grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap:1rem; margin-bottom:1.5rem;">
    <?php foreach ($log_files as $file): ?>
    <div class="dev-card" style="padding:1rem;">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.375rem;">
            <span style="font-family:var(--mono); font-size:0.6875rem; color:var(--dev-text-muted); font-weight:700; text-transform:uppercase;">
                <?= escape_html($file['category']) ?>
            </span>
            <span class="badge-ok" style="font-size:0.5rem;">Available</span>
        </div>
        <div style="font-family:var(--mono); font-size:0.8125rem; font-weight:700; color:var(--dev-text); margin-bottom:0.25rem;">
            <?= escape_html($file['filename']) ?>
        </div>
        <div style="font-size:0.6875rem; color:var(--dev-text-muted);">
            Size: <span style="font-family:var(--mono); color:var(--dev-accent);"><?= escape_html($file['size_kb']) ?></span> · Modified: <?= escape_html($file['modified']) ?>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Log Stream Table -->
<div class="dev-card">
    <div class="dev-card-header">
        <span class="dev-card-title">
            <i class="fa-solid fa-stream" style="color:var(--dev-accent); margin-right:0.375rem;"></i>
            Log Stream — <?= count($logs) ?> entries (Newest First)
        </span>
    </div>

    <?php if (empty($logs)): ?>
    <div class="dev-card-body" style="text-align:center; padding:3rem;">
        <div style="font-size:2.5rem; color:#444c56; margin-bottom:0.75rem;"><i class="fa-solid fa-file-circle-check"></i></div>
        <p style="font-size:0.875rem; color:var(--dev-text-muted);">No log entries found for '<?= escape_html($current_type) ?>'.</p>
    </div>
    <?php else: ?>
    <div style="overflow-x:auto;">
        <table class="dev-table">
            <thead>
                <tr>
                    <th style="width:140px;">Timestamp</th>
                    <th style="width:70px;">Type</th>
                    <th style="width:90px;">Level</th>
                    <th>Message / Event</th>
                    <th>Details</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($logs as $log): ?>
                <?php
                $lvl = $log['level'] ?? 'INFO';
                $badgeClass = $lvl === 'ERROR' ? 'badge-err' : ($lvl === 'WARNING' ? 'badge-warn' : 'badge-ok');
                ?>
                <tr>
                    <td class="mono" style="font-size:0.6875rem; white-space:nowrap; color:var(--dev-text-muted);">
                        <?= escape_html($log['timestamp'] ?? '—') ?>
                    </td>
                    <td>
                        <span style="font-family:var(--mono); font-size:0.5625rem; padding:0.15rem 0.4rem; border-radius:3px; background:var(--dev-surface2); border:1px solid var(--dev-border); color:var(--dev-text);">
                            <?= escape_html($log['type'] ?? 'LOG') ?>
                        </span>
                    </td>
                    <td>
                        <span class="<?= $badgeClass ?>" style="font-size:0.5625rem;">
                            <?= escape_html($lvl) ?>
                        </span>
                    </td>
                    <td style="font-weight:600; font-size:0.8125rem;">
                        <?= escape_html($log['message'] ?? '—') ?>
                    </td>
                    <td class="mono muted" style="font-size:0.6875rem; max-width:300px; word-break:break-all;">
                        <?= escape_html($log['details'] ?? '—') ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<!-- Clear Log Confirmation Modal -->
<div id="clear-modal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.7); z-index:1000; align-items:center; justify-content:center;">
    <div style="background:var(--dev-surface); border:1px solid var(--dev-border); border-radius:12px; padding:2rem; max-width:440px; width:90%;">
        <h3 style="font-size:1.125rem; font-weight:800; color:var(--dev-text); margin-bottom:0.5rem;">
            <i class="fa-solid fa-trash-can" style="color:var(--dev-danger); margin-right:0.375rem;"></i>
            Confirm Clear Log
        </h3>
        <p style="font-size:0.8125rem; color:var(--dev-text-muted); margin-bottom:1.5rem; line-height:1.5;">
            Are you sure you want to clear log contents for <strong style="color:var(--dev-text);" id="clear-target-label">all</strong> logs?
            This action cannot be undone.
        </p>
        <div style="display:flex; gap:0.75rem; justify-content:flex-end;">
            <button onclick="closeClearModal()" style="padding:0.5rem 1.25rem; 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-muted); cursor:pointer;">
                Cancel
            </button>
            <button onclick="executeClearLog()" style="padding:0.5rem 1.25rem; background:rgba(248,81,73,0.2); border:1px solid rgba(248,81,73,0.5); border-radius:6px; font-family:var(--mono); font-size:0.75rem; color:var(--dev-danger); cursor:pointer; font-weight:700;">
                Clear Log
            </button>
        </div>
    </div>
</div>

<script>
let targetLogType = 'all';

function confirmClearLog(type) {
    targetLogType = type;
    document.getElementById('clear-target-label').textContent = type.toUpperCase();
    const modal = document.getElementById('clear-modal');
    modal.style.display = 'flex';
}

function closeClearModal() {
    document.getElementById('clear-modal').style.display = 'none';
}

function executeClearLog() {
    closeClearModal();
    fetch('<?= escape_javascript($clearUrl) ?>', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
        body: JSON.stringify({ type: targetLogType })
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            window.location.reload();
        } else {
            alert('Failed to clear log.');
        }
    })
    .catch(() => alert('Network error while clearing log.'));
}

document.getElementById('clear-modal')?.addEventListener('click', function(e) {
    if (e.target === this) closeClearModal();
});
</script>
