<?php
/**
 * ESO Module Hub — Links to EMS and Fire dashboards
 */
$esoUrl = getSetting('eso_url', 'https://app.esosuite.net');
$db = getDB();

// Quick stats from latest daily summary
$emsSummary = $db->query("SELECT * FROM eso_ems_daily ORDER BY report_date DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
$emsDate = $emsSummary ? date('M j, Y', strtotime($emsSummary['report_date'])) : 'No data';
?>

<div class="page-header">
    <h1>ESO</h1>
</div>

<!-- ESO Suite Quick Link -->
<div class="card" style="margin-bottom:20px;">
    <div style="display:flex; align-items:center; justify-content:space-between;">
        <div>
            <h2 style="font-size:18px; font-weight:700; margin-bottom:4px;">ESO Suite</h2>
            <p style="color:var(--ios-secondary); font-size:14px;">Access the ESO electronic patient care and incident reporting system.</p>
        </div>
        <a href="<?= htmlspecialchars($esoUrl) ?>" target="_blank" class="btn btn-primary btn-lg">
            Open ESO Suite
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
        </a>
    </div>
</div>

<!-- Data Dashboards -->
<div class="grid grid-2" style="margin-bottom:20px;">
    <!-- EMS Container -->
    <a href="dashboard.php?page=eso-ems" class="card" style="text-decoration:none;color:inherit;cursor:pointer;transition:transform 0.15s ease,box-shadow 0.15s ease;">
        <div style="display:flex;align-items:center;gap:16px;">
            <div style="width:56px;height:56px;border-radius:14px;background:linear-gradient(135deg,#1B6CB0,#0B2240);display:flex;align-items:center;justify-content:center;">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>
            </div>
            <div>
                <h2 style="font-size:18px;font-weight:700;margin-bottom:2px;">EMS Data</h2>
                <p style="color:var(--ios-secondary);font-size:13px;">Incident command center &bull; Response times &bull; High-acuity calls</p>
                <?php if ($emsSummary): ?>
                    <div style="margin-top:6px;display:flex;gap:12px;font-size:12px;">
                        <span><strong><?= $emsSummary['unique_incidents'] ?></strong> incidents</span>
                        <span><strong><?= $emsSummary['total_transports'] ?></strong> transports</span>
                        <span style="color:var(--ios-tertiary);"><?= $emsDate ?></span>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <div style="text-align:right;color:var(--ios-blue);font-size:20px;margin-top:-20px;">&rarr;</div>
    </a>

    <!-- Fire Container -->
    <?php
    $fireSummary = $db->query("SELECT * FROM eso_fire_daily ORDER BY report_date DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    $fireDate = $fireSummary ? date('M j, Y', strtotime($fireSummary['report_date'])) : 'No data';
    ?>
    <a href="dashboard.php?page=eso-fire" class="card" style="text-decoration:none;color:inherit;cursor:pointer;transition:transform 0.15s ease,box-shadow 0.15s ease;">
        <div style="display:flex;align-items:center;gap:16px;">
            <div style="width:56px;height:56px;border-radius:14px;background:linear-gradient(135deg,#E74C3C,#C0392B);display:flex;align-items:center;justify-content:center;">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2"><path d="M12 12c-2-2.67-4-4-4-6a4 4 0 0 1 8 0c0 2-2 3.33-4 6z"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M8.46 8.46a5 5 0 0 0 0 7.07"/></svg>
            </div>
            <div>
                <h2 style="font-size:18px;font-weight:700;margin-bottom:2px;">Fire Data</h2>
                <p style="color:var(--ios-secondary);font-size:13px;">Structure fires &bull; Apparatus response &bull; Property loss</p>
                <?php if ($fireSummary): ?>
                    <div style="margin-top:6px;display:flex;gap:12px;font-size:12px;">
                        <span><strong><?= $fireSummary['total_incidents'] ?></strong> incidents</span>
                        <span><strong><?= $fireSummary['structure_fires'] + $fireSummary['vehicle_fires'] ?></strong> fires</span>
                        <span style="color:var(--ios-tertiary);"><?= $fireDate ?></span>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <div style="text-align:right;color:var(--ios-blue);font-size:20px;margin-top:-20px;">&rarr;</div>
    </a>
</div>

<!-- Personnel Container -->
<div class="grid grid-2" style="margin-bottom:20px;">
    <a href="dashboard.php?page=eso-personnel" class="card" style="text-decoration:none;color:inherit;cursor:pointer;transition:transform 0.15s ease,box-shadow 0.15s ease;">
        <div style="display:flex;align-items:center;gap:16px;">
            <div style="width:56px;height:56px;border-radius:14px;background:linear-gradient(135deg,#8E44AD,#6C3483);display:flex;align-items:center;justify-content:center;">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
            </div>
            <div>
                <h2 style="font-size:18px;font-weight:700;margin-bottom:2px;">Personnel</h2>
                <p style="color:var(--ios-secondary);font-size:13px;">Crew analytics &bull; Run counts &bull; Certifications &bull; Training</p>
                <div style="margin-top:6px;display:flex;gap:12px;font-size:12px;">
                    <span><strong>933</strong> active employees</span>
                    <span><strong>569</strong> EMTs</span>
                    <span><strong>531</strong> Paramedics</span>
                </div>
            </div>
        </div>
        <div style="text-align:right;color:var(--ios-blue);font-size:20px;margin-top:-20px;">&rarr;</div>
    </a>
    <div></div>
</div>

<!-- Snowflake Sync Control -->
<?php $lastSync = getSetting('eso_last_sync', ''); $lastSyncDate = getSetting('eso_last_sync_date', ''); ?>
<div class="card" style="border:1px solid var(--ios-border);">
    <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;">
        <div style="display:flex;align-items:center;gap:12px;">
            <div id="syncStatusDot" style="width:10px;height:10px;border-radius:50%;background:#8CC63F;flex-shrink:0;"></div>
            <div>
                <span style="font-weight:600;">Snowflake Connected</span>
                <span style="color:var(--ios-secondary);font-size:13px;margin-left:8px;">
                    Daily sync at 5:30 AM &bull; EMS.EMS (230+ tables) + Fire_Incidents (32 tables)
                </span>
            </div>
        </div>
        <button class="btn btn-primary" id="syncBtn" onclick="triggerSync()" style="display:flex;align-items:center;gap:8px;">
            <svg id="syncIcon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 4v6h-6"/><path d="M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
            <span id="syncBtnText">Sync Last 24 Hours</span>
        </button>
    </div>
    <div id="syncStatus" style="margin-top:10px;font-size:11px;color:var(--ios-tertiary);">
        <?php if ($lastSync): ?>
            Last synced: <?= date('M j, Y g:i A', strtotime($lastSync)) ?><?= $lastSyncDate ? " (data for {$lastSyncDate})" : '' ?>
        <?php else: ?>
            Last synced: <?= $emsDate ?> (auto-sync at 5:30 AM)
        <?php endif; ?>
    </div>
</div>

<style>
@keyframes syncSpin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}
.sync-spinning #syncIcon {
    animation: syncSpin 1s linear infinite;
}
.sync-spinning {
    background: var(--ios-secondary) !important;
    pointer-events: none;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    window.triggerSync = async function() {
        const btn = document.getElementById('syncBtn');
        const btnText = document.getElementById('syncBtnText');
        const statusEl = document.getElementById('syncStatus');
        const dot = document.getElementById('syncStatusDot');

        btn.classList.add('sync-spinning');
        btnText.textContent = 'Syncing...';
        dot.style.background = '#FF9500';
        statusEl.textContent = 'Sync in progress — pulling from Snowflake...';

        try {
            const formData = new FormData();
            formData.append('csrf_token', window.CFD_PORTAL.csrfToken);
            formData.append('date', new Date(Date.now() - 86400000).toISOString().split('T')[0]);

            const resp = await fetch(window.CFD_PORTAL.apiPath + '/trigger-sync.php', {
                method: 'POST',
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
                body: formData
            });
            const data = await resp.json();

            if (data.success) {
                btnText.textContent = 'Sync Started';
                dot.style.background = '#8CC63F';
                statusEl.innerHTML = 'Sync started at ' + new Date().toLocaleTimeString('en-US', {hour:'numeric',minute:'2-digit'}) +
                    ' &mdash; data will update in ~60 seconds. <a href="javascript:location.reload()" style="color:var(--accent);">Refresh page</a>';

                // Poll for completion
                setTimeout(() => {
                    btn.classList.remove('sync-spinning');
                    btnText.textContent = 'Sync Last 24 Hours';
                }, 5000);

                // Auto-refresh after 90 seconds
                setTimeout(() => location.reload(), 90000);
            } else {
                throw new Error(data.error || 'Sync failed');
            }
        } catch (err) {
            btn.classList.remove('sync-spinning');
            btnText.textContent = 'Sync Failed — Retry';
            dot.style.background = '#E74C3C';
            statusEl.textContent = 'Error: ' + err.message;
            setTimeout(() => { btnText.textContent = 'Sync Last 24 Hours'; }, 3000);
        }
    };
});
</script>
