<?php
/**
 * ESO Fire Command Center Dashboard — Apache ECharts
 */
$db = getDB();

$today = $db->query("SELECT * FROM eso_fire_daily ORDER BY report_date DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
$trend = $db->query("SELECT * FROM eso_fire_daily ORDER BY report_date DESC LIMIT 7")->fetchAll(PDO::FETCH_ASSOC);
$trend = array_reverse($trend);

$latestDate = $today['report_date'] ?? date('Y-m-d', strtotime('-1 day'));

// Structure fires for detail
$stmt = $db->prepare("SELECT * FROM eso_fire_incidents WHERE report_date = ? AND incident_type_group LIKE '100%' ORDER BY estimated_property_loss DESC");
$stmt->execute([$latestDate]);
$fireDetail = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Decode JSON
$incidentTypes = json_decode($today['incident_types'] ?? '{}', true) ?: [];
$districts = json_decode($today['district_counts'] ?? '{}', true) ?: [];

// Build station counts from apparatus_counts or fall back to district
$apparatusCounts = json_decode($today['apparatus_counts'] ?? '{}', true) ?: [];
$stationCounts = [];
if (!empty($apparatusCounts)) {
    // Apparatus names like E9, L5, M19 — extract station number
    foreach ($apparatusCounts as $unit => $ct) {
        if (preg_match('/[A-Z]+(\d+)/', strtoupper($unit), $m)) {
            $stn = 'Station ' . ltrim($m[1], '0');
            $stationCounts[$stn] = ($stationCounts[$stn] ?? 0) + $ct;
        }
    }
    arsort($stationCounts);
} elseif (!empty($districts)) {
    // Map districts to primary stations
    $districtStations = [
        'District One' => ['Station 1', 'Station 2', 'Station 3', 'Station 4', 'Station 5'],
        'District Two' => ['Station 6', 'Station 7', 'Station 8', 'Station 9', 'Station 10'],
        'District Three' => ['Station 11', 'Station 12', 'Station 13', 'Station 14', 'Station 15'],
        'District Four' => ['Station 16', 'Station 17', 'Station 18', 'Station 19', 'Station 20'],
        'District Five' => ['Station 21', 'Station 22', 'Station 23', 'Station 24', 'Station 25'],
    ];
    foreach ($districts as $dist => $ct) {
        $stationCounts[$dist] = $ct;
    }
}
// If still empty, query incidents table directly for station-like data
if (empty($stationCounts)) {
    try {
        $stationRows = $db->prepare("
            SELECT district, COUNT(*) as ct FROM eso_fire_incidents
            WHERE report_date = ? AND district IS NOT NULL AND district != ''
            GROUP BY district ORDER BY ct DESC LIMIT 10
        ");
        $stationRows->execute([$latestDate]);
        foreach ($stationRows->fetchAll(PDO::FETCH_ASSOC) as $r) {
            $stationCounts[$r['district']] = (int)$r['ct'];
        }
    } catch (Exception $e) {}
}
$hourlyVol = json_decode($today['hourly_volume'] ?? '{}', true) ?: [];

$reportDate = $today ? date('l, F j, Y', strtotime($today['report_date'])) : 'No data';

// JS data
$trendDates = array_map(fn($d) => date('D M j', strtotime($d['report_date'])), $trend);
$trendInc = array_map(fn($d) => (int)$d['total_incidents'], $trend);
$trendFires = array_map(fn($d) => (int)$d['structure_fires'] + (int)$d['vehicle_fires'], $trend);

$typeData = [];
foreach (array_slice($incidentTypes, 0, 12) as $name => $ct) {
    $typeData[] = ['name' => $name, 'value' => $ct];
}

$distNames = array_keys(array_slice($stationCounts, 0, 10));
$distValues = array_values(array_slice($stationCounts, 0, 10));

$hourlyData = [];
for ($h = 0; $h < 24; $h++) $hourlyData[] = (int)($hourlyVol[(string)$h] ?? 0);

$propLoss = $today['total_property_loss'] ?? 0;
$contLoss = $today['total_content_loss'] ?? 0;
?>

<script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts-liquidfill@3/dist/echarts-liquidfill.min.js"></script>

<style>
.fire-cc { padding: 0; }
.fire-cc .cc-header {
    background: linear-gradient(135deg, #7A1B1B 0%, #C0392B 50%, #E74C3C 100%);
    color: #fff; padding: 16px 24px; border-radius: var(--ios-radius); margin-bottom: 16px;
    display: flex; align-items: center; justify-content: space-between;
}
.fire-cc .cc-header h1 { font-size: 20px; font-weight: 800; }
.fire-cc .cc-header .cc-date { font-size: 13px; color: #FFCDD2; }
.fire-cc .cc-header .cc-badge { background: #FFEB3B; color: #7A1B1B; font-size: 10px; font-weight: 700; padding: 3px 10px; border-radius: 12px; text-transform: uppercase; }
.cc-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 10px; margin-bottom: 16px; }
.cc-stat { background: var(--ios-card); border-radius: var(--ios-radius-sm); padding: 14px 16px; box-shadow: var(--ios-shadow); text-align: center; position: relative; overflow: hidden; }
.cc-stat::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px; }
.cc-stat.stat-total::before { background: #E74C3C; }
.cc-stat.stat-structure::before { background: #C0392B; }
.cc-stat.stat-vehicle::before { background: #E67E22; }
.cc-stat.stat-false::before { background: #8E99A8; }
.cc-stat.stat-hazmat::before { background: #F39C12; }
.cc-stat.stat-service::before { background: #3498DB; }
.cc-stat.stat-ems::before { background: #1B6CB0; }
.cc-stat.stat-loss::before { background: #C0392B; }
.cc-stat-value { font-size: 28px; font-weight: 800; color: var(--ios-text); line-height: 1; }
.cc-stat-label { font-size: 10px; text-transform: uppercase; letter-spacing: 0.8px; color: var(--ios-tertiary); font-weight: 600; margin-top: 4px; }
.cc-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 16px; }
.cc-grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px; margin-bottom: 16px; }
.cc-panel { background: var(--ios-card); border-radius: var(--ios-radius-sm); padding: 16px; box-shadow: var(--ios-shadow); }
.cc-panel-title { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 1px; color: var(--ios-tertiary); margin-bottom: 8px; padding-bottom: 6px; border-bottom: 1px solid var(--ios-border); }
.cc-chart { width: 100%; }
.cc-back { font-size: 13px; color: var(--ios-blue); text-decoration: none; display: inline-flex; align-items: center; gap: 4px; margin-bottom: 12px; }
.cc-collapsed { display: none; }
.cc-chevron { transform: rotate(-90deg); transition: transform 0.2s ease; }
.cc-chevron-open { transform: rotate(0deg); }
.fire-detail { border-left: 4px solid #E74C3C; padding: 10px 14px; margin-bottom: 8px; border-radius: 0 var(--ios-radius-sm) var(--ios-radius-sm) 0; background: #FDE8E8; font-size: 12px; }
@media (max-width: 768px) { .cc-stats { grid-template-columns: repeat(2, 1fr); } .cc-grid, .cc-grid-3 { grid-template-columns: 1fr; } }
</style>

<div class="fire-cc">
    <a href="dashboard.php?page=eso" class="cc-back">&larr; ESO Overview</a>

    <div class="cc-header">
        <div>
            <h1>🔥 Fire Command Center</h1>
            <div class="cc-date"><?= $reportDate ?></div>
        </div>
        <span class="cc-badge">Live Data</span>
    </div>

    <div class="cc-stats">
        <div class="cc-stat stat-total">
            <div class="cc-stat-value" data-countup="<?= $today['total_incidents'] ?? 0 ?>">0</div>
            <div class="cc-stat-label">Total Incidents</div>
        </div>
        <div class="cc-stat stat-structure">
            <div class="cc-stat-value" data-countup="<?= $today['structure_fires'] ?? 0 ?>">0</div>
            <div class="cc-stat-label">Structure Fires</div>
        </div>
        <div class="cc-stat stat-vehicle">
            <div class="cc-stat-value" data-countup="<?= $today['vehicle_fires'] ?? 0 ?>">0</div>
            <div class="cc-stat-label">Vehicle Fires</div>
        </div>
        <div class="cc-stat stat-false">
            <div class="cc-stat-value" data-countup="<?= $today['false_alarms'] ?? 0 ?>">0</div>
            <div class="cc-stat-label">False Alarms</div>
        </div>
        <div class="cc-stat stat-hazmat">
            <div class="cc-stat-value" data-countup="<?= $today['hazmat'] ?? 0 ?>">0</div>
            <div class="cc-stat-label">HazMat</div>
        </div>
        <div class="cc-stat stat-service">
            <div class="cc-stat-value" data-countup="<?= $today['service_calls'] ?? 0 ?>">0</div>
            <div class="cc-stat-label">Service Calls</div>
        </div>
        <div class="cc-stat stat-ems">
            <div class="cc-stat-value" data-countup="<?= $today['rescue_ems'] ?? 0 ?>">0</div>
            <div class="cc-stat-label">Rescue/EMS</div>
        </div>
        <div class="cc-stat stat-loss">
            <div class="cc-stat-value" style="font-size:20px;color:#C0392B;">$<?= number_format($propLoss + $contLoss) ?></div>
            <div class="cc-stat-label">Property Loss</div>
        </div>
    </div>

    <!-- Row 1: Trend + Treemap -->
    <div class="cc-grid">
        <div class="cc-panel">
            <div class="cc-panel-title">7-Day Incident Trend</div>
            <div id="fire-trend" class="cc-chart" style="height:250px;"></div>
        </div>
        <div class="cc-panel">
            <div class="cc-panel-title">Incident Type Breakdown</div>
            <div id="fire-treemap" class="cc-chart" style="height:250px;"></div>
        </div>
    </div>

    <!-- Row 2: Hourly + Districts -->
    <div class="cc-grid">
        <div class="cc-panel">
            <div class="cc-panel-title">Call Volume by Hour</div>
            <div id="fire-hourly" class="cc-chart" style="height:180px;"></div>
        </div>
        <div class="cc-panel">
            <div class="cc-panel-title">Incidents by Station</div>
            <div id="fire-districts" class="cc-chart" style="height:180px;"></div>
        </div>
    </div>

    <!-- Row 3: Fire Detail (collapsible) -->
    <?php if (!empty($fireDetail)): ?>
    <div class="cc-panel" style="margin-bottom:16px;">
        <div class="cc-panel-title" style="cursor:pointer;display:flex;justify-content:space-between;align-items:center;" onclick="document.getElementById('fireDetailBody').classList.toggle('cc-collapsed');this.querySelector('.cc-chevron').classList.toggle('cc-chevron-open');">
            <span>Fire Incidents &mdash; <?= date('M j', strtotime($latestDate)) ?> <span style="font-weight:400;color:var(--ios-secondary);font-size:10px;text-transform:none;">(<?= count($fireDetail) ?>)</span></span>
            <span class="cc-chevron" style="font-size:14px;color:var(--ios-tertiary);">&#9660;</span>
        </div>
        <div id="fireDetailBody" class="cc-collapsed">
        <?php foreach ($fireDetail as $f): ?>
            <div class="fire-detail">
                <div style="display:flex;justify-content:space-between;">
                    <strong><?= htmlspecialchars($f['incident_number']) ?></strong>
                    <?php if ($f['estimated_property_loss'] > 0): ?>
                        <span style="color:#C0392B;font-weight:700;">$<?= number_format($f['estimated_property_loss']) ?> loss</span>
                    <?php endif; ?>
                </div>
                <div style="color:var(--ios-secondary);margin-top:2px;">
                    <?= htmlspecialchars($f['incident_type']) ?>
                    &bull; <?= htmlspecialchars($f['location_address'] ?: 'No address') ?>
                    <?php if ($f['district']): ?>&bull; D<?= htmlspecialchars($f['district']) ?><?php endif; ?>
                    <?php if ($f['response_time_sec']): ?>&bull; <?= round($f['response_time_sec'] / 60, 1) ?>min response<?php endif; ?>
                </div>
                <?php if ($f['narrative']): ?>
                    <div style="margin-top:4px;font-size:11px;color:var(--ios-secondary);"><?= htmlspecialchars(mb_substr($f['narrative'], 0, 200)) ?><?= mb_strlen($f['narrative']) > 200 ? '...' : '' ?></div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <div style="text-align:center;padding:12px;font-size:10px;color:var(--ios-tertiary);">
        Data Source: ESO Fire Records / Snowflake &bull; Updated daily at 5:30 AM &bull; Powered by Apache ECharts &bull; Cincinnati Fire Department
    </div>
</div>

<script>
// Count-up animation
document.querySelectorAll('[data-countup]').forEach(el => {
    const target = parseFloat(el.dataset.countup);
    const decimal = parseInt(el.dataset.decimal || '0');
    const duration = 1200;
    const start = performance.now();
    const tick = (now) => {
        const progress = Math.min((now - start) / duration, 1);
        const eased = 1 - Math.pow(1 - progress, 3);
        el.textContent = (target * eased).toFixed(decimal);
        if (progress < 1) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
});

function initChart(id) {
    const dom = document.getElementById(id);
    if (!dom) return null;
    const chart = echarts.init(dom);
    window.addEventListener('resize', () => chart.resize());
    return chart;
}

// Trend chart
const trendChart = initChart('fire-trend');
if (trendChart) trendChart.setOption({
    tooltip: { trigger: 'axis', backgroundColor: '#7A1B1B', textStyle: { color: '#fff' } },
    legend: { data: ['All Incidents', 'Fires'], textStyle: { color: '#8E99A8', fontSize: 10 }, top: 0 },
    grid: { top: 30, right: 10, bottom: 24, left: 40 },
    xAxis: { type: 'category', data: <?= json_encode($trendDates) ?>, axisLabel: { color: '#8E99A8', fontSize: 10 } },
    yAxis: { type: 'value', splitLine: { lineStyle: { color: '#E8EDF3' } }, axisLabel: { color: '#8E99A8', fontSize: 10 } },
    series: [
        {
            name: 'All Incidents', data: <?= json_encode($trendInc) ?>, type: 'line', smooth: true,
            lineStyle: { width: 3, color: '#E74C3C' }, itemStyle: { color: '#E74C3C' },
            areaStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(231,76,60,0.3)' }, { offset: 1, color: 'rgba(231,76,60,0.02)' }
            ])},
            animationDuration: 1500
        },
        {
            name: 'Fires', data: <?= json_encode($trendFires) ?>, type: 'bar',
            barWidth: '40%',
            itemStyle: { borderRadius: [4,4,0,0], color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#C0392B' }, { offset: 1, color: '#7A1B1B' }
            ])},
            animationDelay: idx => idx * 100
        }
    ]
});

// Treemap
const treemapChart = initChart('fire-treemap');
if (treemapChart) treemapChart.setOption({
    tooltip: { formatter: p => '<strong>' + p.name + '</strong><br>' + p.value + ' incidents', backgroundColor: '#7A1B1B', textStyle: { color: '#fff' } },
    series: [{
        type: 'treemap', data: <?= json_encode($typeData) ?>, roam: false,
        breadcrumb: { show: false },
        itemStyle: { borderRadius: 6, borderWidth: 3, borderColor: '#fff', gapWidth: 2 },
        label: { show: true, formatter: '{b}\n{c}', fontSize: 10, fontWeight: 600, color: '#fff', lineHeight: 14 },
        color: ['#E74C3C', '#C0392B', '#E67E22', '#F39C12', '#8E44AD', '#3498DB', '#1B6CB0', '#8CC63F', '#00BCD4', '#E91E63', '#7A1B1B', '#5A6A7E'],
        animationDuration: 1500
    }]
});

// Hourly volume
const hourlyChart = initChart('fire-hourly');
const hourLabels = Array.from({length: 24}, (_, i) => { if (i===0) return '12a'; if (i===12) return '12p'; return (i%12)+(i<12?'a':'p'); });
const hourValues = <?= json_encode($hourlyData) ?>;
const maxH = Math.max(...hourValues, 1);
if (hourlyChart) hourlyChart.setOption({
    tooltip: { trigger: 'axis', backgroundColor: '#7A1B1B', textStyle: { color: '#fff' },
        formatter: p => { const h = p[0].dataIndex; const ampm = h<12?'AM':'PM'; const h12 = h===0?12:(h>12?h-12:h); return '<b>'+h12+':00 '+ampm+'</b><br>'+p[0].value+' incidents'; }
    },
    grid: { top: 8, right: 8, bottom: 20, left: 30 },
    xAxis: { type: 'category', data: hourLabels, axisLabel: { color: '#8E99A8', fontSize: 9 } },
    yAxis: { type: 'value', axisLabel: { color: '#8E99A8', fontSize: 9 }, splitLine: { lineStyle: { color: '#F0F2F5' } } },
    series: [{ type: 'bar', data: hourValues.map(v => ({
        value: v,
        itemStyle: { borderRadius: [4,4,0,0], color: new echarts.graphic.LinearGradient(0,1,0,0,[
            {offset:0, color:'rgba(231,76,60,0.2)'}, {offset:1, color:'rgba(231,76,60,'+(0.3+0.7*(v/maxH))+')'}
        ])}
    })), barWidth: '70%', animationDelay: idx => idx * 40 }]
});

// Districts
const distChart = initChart('fire-districts');
if (distChart) distChart.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, backgroundColor: '#7A1B1B', textStyle: { color: '#fff' } },
    grid: { top: 4, right: 40, bottom: 4, left: 10, containLabel: true },
    xAxis: { type: 'value', show: false },
    yAxis: { type: 'category', data: <?= json_encode(array_reverse($distNames)) ?>, axisLabel: { color: '#5A6A7E', fontSize: 10 }, axisLine: { show: false }, axisTick: { show: false } },
    series: [{
        type: 'bar', data: <?= json_encode(array_reverse($distValues)) ?>, barWidth: 16,
        itemStyle: { borderRadius: [0,8,8,0], color: new echarts.graphic.LinearGradient(0,0,1,0,[
            {offset:0, color:'#C0392B'}, {offset:1, color:'#E74C3C'}
        ])},
        label: { show: true, position: 'right', color: '#0B2240', fontWeight: 700, fontSize: 11 },
        animationDelay: idx => idx * 80
    }]
});
</script>
