<?php
/**
 * Significant Incident Briefing — Building Fire Deep Dive
 * Google Street View, 3D orbit, ECharts timeline, apparatus, investigation, AI summary
 */
$db = getDB();
$incNum = preg_replace('/[^A-Za-z0-9]/', '', $_GET['inc'] ?? '');
if (!$incNum) { echo '<div class="card"><p>No incident number provided.</p></div>'; return; }

$stmt = $db->prepare("SELECT * FROM eso_fire_briefings WHERE incident_number = ?");
$stmt->execute([$incNum]);
$b = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$b) { echo '<div class="card"><p>Briefing not found for ' . htmlspecialchars($incNum) . '</p></div>'; return; }

$apparatus = json_decode($b['apparatus_json'] ?? '[]', true) ?: [];
$fireMod = json_decode($b['fire_module_json'] ?? '{}', true) ?: [];
$civCas = json_decode($b['civilian_casualties_json'] ?? '[]', true) ?: [];
$ffCas = json_decode($b['ff_casualties_json'] ?? '[]', true) ?: [];

$totalLoss = ($b['property_loss'] ?? 0) + ($b['content_loss'] ?? 0);
$totalApp = ($b['supp_apparatus'] ?? 0) + ($b['ems_apparatus'] ?? 0);
$totalPers = ($b['supp_personnel'] ?? 0) + ($b['ems_personnel'] ?? 0);
$lat = $b['latitude'] ?? 0;
$lng = $b['longitude'] ?? 0;
$mapsKey = getenv('GOOGLE_MAPS_API_KEY') ?: 'AIzaSyBWMuTGk_5XDTkXNNQYotWgsJ--N-wA_dU';

// Sort apparatus by response time
usort($apparatus, fn($a, $b) => ($a['resp'] ?? 9999) - ($b['resp'] ?? 9999));

function fmtTime($sec) { if (!$sec) return '—'; $m = floor($sec/60); $s = $sec%60; return $m > 0 ? "{$m}m {$s}s" : "{$s}s"; }
function fmtMoney($v) { return '$' . number_format((float)$v); }
?>

<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>
<script src="https://maps.googleapis.com/maps/api/js?key=<?= $mapsKey ?>&callback=initMaps" async defer></script>

<style>
.briefing { max-width: 1200px; margin: 0 auto; }
.briefing-header {
    background: linear-gradient(135deg, #1a0a0a 0%, #7A1B1B 30%, #C0392B 60%, #E74C3C 100%);
    color: #fff; padding: 24px 32px; border-radius: var(--ios-radius); margin-bottom: 20px;
    position: relative; overflow: hidden;
}
.briefing-header::before { content: '🔥'; position: absolute; right: 20px; top: 10px; font-size: 80px; opacity: 0.15; }
.briefing-header h1 { font-size: 24px; font-weight: 800; margin-bottom: 4px; }
.briefing-header .addr { font-size: 16px; color: #FFCDD2; }
.briefing-header .meta { font-size: 12px; color: #EF9A9A; margin-top: 8px; }

.brief-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 12px; margin-bottom: 20px; }
.brief-stat {
    background: var(--ios-card); border-radius: var(--ios-radius-sm); padding: 16px 20px;
    box-shadow: var(--ios-shadow); text-align: center; position: relative; overflow: hidden;
}
.brief-stat::before { content:''; position:absolute; top:0; left:0; right:0; height:3px; }
.brief-stat.loss::before { background: #C0392B; }
.brief-stat.app::before { background: #E67E22; }
.brief-stat.pers::before { background: #1B6CB0; }
.brief-stat.water::before { background: #3498DB; }
.brief-stat.ctrl::before { background: #8CC63F; }
.brief-stat.scene::before { background: #8E44AD; }
.brief-stat-value { font-size: 32px; font-weight: 800; line-height: 1; }
.brief-stat-label { font-size: 10px; text-transform: uppercase; letter-spacing: 0.8px; color: var(--ios-tertiary); font-weight: 600; margin-top: 6px; }

.brief-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 20px; }
.brief-panel { background: var(--ios-card); border-radius: var(--ios-radius-sm); padding: 20px; box-shadow: var(--ios-shadow); }
.brief-panel-title { font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 1px; color: var(--ios-tertiary); margin-bottom: 12px; padding-bottom: 8px; border-bottom: 1px solid var(--ios-border); }

.map-container { height: 300px; border-radius: var(--ios-radius-sm); overflow: hidden; }

.app-table { width: 100%; border-collapse: collapse; font-size: 12px; }
.app-table th { text-align: left; font-size: 10px; text-transform: uppercase; letter-spacing: 0.5px; color: var(--ios-tertiary); padding: 6px 8px; border-bottom: 2px solid var(--ios-border); }
.app-table td { padding: 6px 8px; border-bottom: 1px solid var(--ios-border); }
.app-table tr:hover { background: var(--ios-bg); }
.app-unit { font-weight: 700; color: var(--ios-text); }
.app-type { color: var(--ios-secondary); font-size: 11px; }

.inv-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.inv-item { padding: 8px 12px; background: var(--ios-bg); border-radius: 8px; }
.inv-label { font-size: 10px; text-transform: uppercase; letter-spacing: 0.5px; color: var(--ios-tertiary); font-weight: 600; }
.inv-value { font-size: 13px; font-weight: 600; color: var(--ios-text); margin-top: 2px; }

.casualty-card { border-left: 4px solid #E74C3C; padding: 12px 16px; margin-bottom: 10px; border-radius: 0 var(--ios-radius-sm) var(--ios-radius-sm) 0; background: #FDE8E8; }
.casualty-card.minor { border-color: #FF9500; background: #FFF3E0; }

.narrative-box { background: var(--ios-bg); border-radius: var(--ios-radius-sm); padding: 16px 20px; font-size: 13px; line-height: 1.6; color: var(--ios-text); white-space: pre-wrap; }

.ai-summary { background: linear-gradient(135deg, #0B2240 0%, #163158 100%); color: #fff; border-radius: var(--ios-radius); padding: 24px; margin-bottom: 20px; }
.ai-summary h3 { font-size: 14px; color: #8CC63F; margin-bottom: 12px; text-transform: uppercase; letter-spacing: 1px; }
.ai-summary p { font-size: 14px; line-height: 1.7; color: #C8D6E5; margin-bottom: 12px; }

.cc-back { font-size: 13px; color: var(--ios-blue); text-decoration: none; display: inline-flex; align-items: center; gap: 4px; margin-bottom: 12px; }

@media (max-width: 768px) { .brief-grid { grid-template-columns: 1fr; } .brief-stats { grid-template-columns: repeat(2, 1fr); } }
</style>

<div class="briefing">
    <a href="dashboard.php?page=eso-fire" class="cc-back">&larr; Fire Command Center</a>

    <!-- Header -->
    <div class="briefing-header">
        <div style="font-size:10px;text-transform:uppercase;letter-spacing:2px;color:#EF9A9A;margin-bottom:4px;">Significant Incident Briefing</div>
        <h1><?= htmlspecialchars($b['incident_type'] ?? 'Building Fire') ?></h1>
        <div class="addr"><?= htmlspecialchars($b['address'] ?? '') ?></div>
        <div class="meta">
            <?= $b['incident_date'] ? date('l, F j, Y \a\t g:i A', strtotime($b['incident_date'])) : '' ?>
            &nbsp;&bull;&nbsp; <?= htmlspecialchars($incNum) ?>
            &nbsp;&bull;&nbsp; OIC: <?= htmlspecialchars($b['oic_name'] ?? 'Not recorded') ?>
            &nbsp;&bull;&nbsp; <?= htmlspecialchars($b['shift_name'] ?? '') ?>
            <?php if ($b['injury_or_death'] && $b['injury_or_death'] !== 'Not Recorded'): ?>
                &nbsp;&bull;&nbsp; <span style="background:#FF6B6B;padding:2px 8px;border-radius:10px;font-size:10px;font-weight:700;">⚠️ <?= htmlspecialchars($b['injury_or_death']) ?></span>
            <?php endif; ?>
        </div>
    </div>

    <!-- Key Stats -->
    <div class="brief-stats">
        <div class="brief-stat loss">
            <div class="brief-stat-value" style="color:#C0392B;"><?= fmtMoney($totalLoss) ?></div>
            <div class="brief-stat-label">Total Loss</div>
        </div>
        <div class="brief-stat app">
            <div class="brief-stat-value"><?= $totalApp ?></div>
            <div class="brief-stat-label">Apparatus</div>
        </div>
        <div class="brief-stat pers">
            <div class="brief-stat-value"><?= $totalPers ?></div>
            <div class="brief-stat-label">Personnel</div>
        </div>
        <div class="brief-stat water">
            <div class="brief-stat-value" style="color:#3498DB;"><?= fmtTime($b['water_on_fire_sec'] ?? 0) ?></div>
            <div class="brief-stat-label">Water on Fire</div>
        </div>
        <div class="brief-stat ctrl">
            <div class="brief-stat-value" style="color:#8CC63F;"><?= fmtTime($b['arrival_to_controlled_sec'] ?? 0) ?></div>
            <div class="brief-stat-label">Controlled</div>
        </div>
        <div class="brief-stat scene">
            <div class="brief-stat-value"><?= fmtTime($b['total_scene_time_sec'] ?? 0) ?></div>
            <div class="brief-stat-label">Total Scene</div>
        </div>
    </div>

    <!-- Maps: Street View + Satellite Orbit -->
    <?php if ($lat && $lng): ?>
    <div class="brief-grid">
        <div class="brief-panel">
            <div class="brief-panel-title">📍 Street View</div>
            <div id="streetview" class="map-container"></div>
        </div>
        <div class="brief-panel">
            <div class="brief-panel-title">🛰️ Aerial View <span style="font-weight:400;color:var(--ios-secondary);text-transform:none;font-size:10px;">(auto-orbit)</span></div>
            <div id="aerialmap" class="map-container"></div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Incident Timeline -->
    <div class="brief-panel" style="margin-bottom:20px;">
        <div class="brief-panel-title">⏱️ Incident Timeline</div>
        <div id="chart-timeline" style="height:120px;width:100%;"></div>
    </div>

    <!-- Apparatus Deployment -->
    <div class="brief-panel" style="margin-bottom:20px;">
        <div class="brief-panel-title">🚒 Apparatus Response (<?= count($apparatus) ?> units)</div>
        <table class="app-table">
            <thead>
                <tr><th>Unit</th><th>Type</th><th>Response</th><th>Turnout</th><th>Travel</th></tr>
            </thead>
            <tbody>
                <?php foreach ($apparatus as $i => $a):
                    $resp = ($a['resp'] ?? 0);
                    $turn = ($a['turnout'] ?? 0);
                    $travel = $resp > $turn ? $resp - $turn : 0;
                    $respColor = $resp <= 300 ? '#8CC63F' : ($resp <= 480 ? '#FF9500' : '#E74C3C');
                    $isFirst = ($i === 0);
                ?>
                <tr<?= $isFirst ? ' style="background:#FFF8E1;"' : '' ?>>
                    <td><span class="app-unit"><?= htmlspecialchars($a['unit'] ?? '') ?></span><?= $isFirst ? ' <span style="background:#FF9500;color:#fff;font-size:8px;padding:1px 5px;border-radius:6px;font-weight:700;margin-left:4px;">1ST DUE</span>' : '' ?></td>
                    <td><span class="app-type"><?= htmlspecialchars($a['type'] ?? '') ?></span></td>
                    <td style="font-weight:700;color:<?= $respColor ?>;"><?= $resp ? fmtTime($resp) : '—' ?></td>
                    <td><?= $turn ? fmtTime($turn) : '—' ?></td>
                    <td><?= $travel ? fmtTime($travel) : '—' ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Fire Investigation + Financial -->
    <div class="brief-grid">
        <div class="brief-panel">
            <div class="brief-panel-title">🔍 Fire Investigation</div>
            <div class="inv-grid">
                <?php
                $invFields = [
                    'Cause' => $fireMod['cause'] ?? '',
                    'Area of Origin' => $fireMod['area_of_origin'] ?? '',
                    'Heat Source' => $fireMod['heat_source'] ?? '',
                    'Item First Ignited' => $fireMod['item_first_ignited'] ?? '',
                    'Equipment Involved' => $fireMod['equipment'] ?? '',
                    'Material' => $fireMod['material_first_ignited'] ?? '',
                    'Structure' => $fireMod['structure_type'] ?? '',
                    'Stories' => ($fireMod['stories'] ?? '') . ' above / ' . ($fireMod['stories_below'] ?? '0') . ' below',
                    'Square Footage' => ($fireMod['sq_ft'] ?? '') ? number_format((int)$fireMod['sq_ft']) . ' sq ft' : '',
                    'Fire Spread' => $fireMod['fire_spread'] ?? '',
                    'Detector' => $fireMod['detector'] ?? '',
                    'Sprinkler' => $fireMod['sprinkler'] ?? '',
                    'Story of Origin' => $fireMod['story_of_origin'] ?? '',
                    'Buildings Involved' => $fireMod['buildings_involved'] ?? '',
                ];
                foreach ($invFields as $label => $value):
                    if (!$value) continue;
                ?>
                    <div class="inv-item">
                        <div class="inv-label"><?= $label ?></div>
                        <div class="inv-value"><?= htmlspecialchars($value) ?></div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="brief-panel">
            <div class="brief-panel-title">💰 Financial Impact</div>
            <div style="text-align:center;padding:16px 0;">
                <div style="font-size:48px;font-weight:800;color:#C0392B;"><?= fmtMoney($totalLoss) ?></div>
                <div style="font-size:12px;color:var(--ios-tertiary);margin-top:4px;">TOTAL ESTIMATED LOSS</div>
            </div>
            <div id="chart-financial" style="height:160px;"></div>

            <!-- Casualties -->
            <?php if (!empty($civCas) && isset($civCas[0]['name'])): ?>
                <div style="margin-top:16px;">
                    <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:#C0392B;margin-bottom:8px;">⚠️ Civilian Casualties</div>
                    <?php foreach ($civCas as $cas): ?>
                        <div class="casualty-card <?= strtolower($cas['severity'] ?? '') === 'minor' ? 'minor' : '' ?>">
                            <div style="font-weight:700;"><?= htmlspecialchars($cas['name'] ?? '') ?>, <?= $cas['age'] ?? '' ?>yo <?= $cas['gender'] ?? '' ?></div>
                            <div style="font-size:11px;color:var(--ios-secondary);margin-top:4px;">
                                <strong>Severity:</strong> <?= htmlspecialchars($cas['severity'] ?? '') ?> &bull;
                                <strong>Symptom:</strong> <?= htmlspecialchars($cas['symptom'] ?? '') ?> &bull;
                                <strong>Activity:</strong> <?= htmlspecialchars($cas['activity'] ?? '') ?>
                            </div>
                            <div style="font-size:11px;color:var(--ios-secondary);">
                                <strong>Cause:</strong> <?= htmlspecialchars($cas['cause'] ?? '') ?> &bull;
                                <strong>Disposition:</strong> <?= htmlspecialchars($cas['disposition'] ?? '') ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Narrative -->
    <div class="brief-panel" style="margin-bottom:20px;">
        <div class="brief-panel-title">📝 Incident Narrative</div>
        <div class="narrative-box"><?= htmlspecialchars($b['narrative'] ?? 'No narrative available.') ?></div>
    </div>

    <!-- AI Summary (placeholder — Gemini integration) -->
    <?php if ($b['ai_summary']): ?>
    <div class="ai-summary">
        <h3>🤖 AI Executive Briefing Summary</h3>
        <?php foreach (explode("\n\n", $b['ai_summary']) as $para): ?>
            <p><?= htmlspecialchars($para) ?></p>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <div style="text-align:center;padding:12px;font-size:10px;color:var(--ios-tertiary);">
        Significant Incident Briefing &bull; <?= htmlspecialchars($incNum) ?> &bull; Cincinnati Fire Department &bull; Office of the Fire Chief
    </div>
</div>

<script>
// ── Google Maps ──────────────────────────────────────────────
function initMaps() {
    const lat = <?= $lat ?>;
    const lng = <?= $lng ?>;
    const pos = { lat, lng };

    // Street View
    const svDiv = document.getElementById('streetview');
    if (svDiv) {
        new google.maps.StreetViewPanorama(svDiv, {
            position: pos, pov: { heading: 0, pitch: 0 }, zoom: 1,
            addressControl: false, linksControl: false
        });
    }

    // Aerial orbit map
    const mapDiv = document.getElementById('aerialmap');
    if (mapDiv) {
        const map = new google.maps.Map(mapDiv, {
            center: pos, zoom: 18, mapTypeId: 'satellite', tilt: 60, heading: 0,
            disableDefaultUI: true, gestureHandling: 'greedy'
        });
        new google.maps.Marker({ position: pos, map, title: '<?= addslashes($b['address'] ?? '') ?>' });

        // Auto orbit
        let heading = 0;
        setInterval(() => {
            heading = (heading + 0.5) % 360;
            map.setHeading(heading);
        }, 50);
    }
}

// ── ECharts Timeline ─────────────────────────────────────────
const tlChart = echarts.init(document.getElementById('chart-timeline'));
const events = [
    { name: 'Alarm', time: '<?= $b['alarm_dt'] ? date('H:i:s', strtotime($b['alarm_dt'])) : '' ?>' },
    { name: 'On Scene', time: '<?= $b['arrival_dt'] ? date('H:i:s', strtotime($b['arrival_dt'])) : '' ?>', label: 'Response: <?= fmtTime($b['response_time_sec'] ?? 0) ?>' },
    { name: 'Water', time: '<?= $b['arrival_dt'] && $b['water_on_fire_sec'] ? date('H:i:s', strtotime($b['arrival_dt']) + ($b['water_on_fire_sec'] ?? 0)) : '' ?>', label: '<?= fmtTime($b['water_on_fire_sec'] ?? 0) ?> from arrival' },
    { name: 'Controlled', time: '<?= $b['controlled_dt'] ? date('H:i:s', strtotime($b['controlled_dt'])) : '' ?>', label: '<?= fmtTime($b['arrival_to_controlled_sec'] ?? 0) ?> from arrival' },
    { name: 'Cleared', time: '<?= $b['cleared_dt'] ? date('H:i:s', strtotime($b['cleared_dt'])) : '' ?>' },
].filter(e => e.time);

tlChart.setOption({
    tooltip: { trigger: 'item', backgroundColor: '#7A1B1B', textStyle: { color: '#fff' } },
    grid: { top: 30, bottom: 10, left: 60, right: 60 },
    xAxis: { type: 'category', data: events.map(e => e.name), axisLabel: { color: '#5A6A7E', fontSize: 11, fontWeight: 600 }, axisLine: { lineStyle: { color: '#D8DEE6' } } },
    yAxis: { show: false },
    series: [{
        type: 'line', data: events.map((e, i) => i),
        symbol: 'circle', symbolSize: 16,
        lineStyle: { color: '#E74C3C', width: 3 },
        itemStyle: { color: '#E74C3C', borderWidth: 3, borderColor: '#fff' },
        label: { show: true, position: 'top', formatter: (p) => events[p.dataIndex].time, color: '#0B2240', fontWeight: 700, fontSize: 11 },
        animationDuration: 2000
    }]
});
window.addEventListener('resize', () => tlChart.resize());

// ── Financial Chart ──────────────────────────────────────────
const finChart = echarts.init(document.getElementById('chart-financial'));
finChart.setOption({
    tooltip: { trigger: 'item', backgroundColor: '#7A1B1B', textStyle: { color: '#fff' } },
    series: [{
        type: 'pie', radius: ['45%', '70%'], center: ['50%', '50%'],
        data: [
            { value: <?= (float)($b['property_loss'] ?? 0) ?>, name: 'Property Loss', itemStyle: { color: '#C0392B' } },
            { value: <?= (float)($b['content_loss'] ?? 0) ?>, name: 'Content Loss', itemStyle: { color: '#E67E22' } },
        ],
        label: { formatter: '{b}\n{d}%', fontSize: 11, color: '#5A6A7E' },
        emphasis: { scaleSize: 8 },
        animationType: 'scale', animationDuration: 1500
    }]
});
window.addEventListener('resize', () => finChart.resize());
</script>
