<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| FIBRECORE PORTAL - SPAN LOSS ANALYSIS
|--------------------------------------------------------------------------
| Reads existing routes, fiber_cores, core_tests, test_sessions,
| and core_events. No database schema changes are made.
|
| IMPORTANT:
| - fiber_length_km is compared against routes.distance_km.
| - total_loss_db is displayed as the saved OTDR total loss.
| - pm_1310_dbm and pm_1550_dbm are displayed as recorded readings;
|   they are NOT treated as dB loss values.
| - Recommendations are advisory; they do not automatically declare
|   that a cable must be replaced.
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/zone.php';

require_login();

$pdo = db();
$user = current_user() ?? [];
$role = strtoupper(trim((string)($user['role'] ?? '')));
$isSuperAdmin = ($role === 'SUPERADMIN');
$zoneId = current_user_zone_id();

if (!function_exists('span_e')) {
    function span_e($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

function span_num($value, int $decimals = 3): string
{
    if ($value === null || $value === '' || !is_numeric($value)) {
        return '—';
    }
    return number_format((float)$value, $decimals);
}

/** Normalize event labels from different OTDR/PWA save formats. */
function span_event_category($value): string
{
    $raw = strtoupper(trim((string)$value));
    if ($raw === '') return '';
    $compact = preg_replace('/[^A-Z0-9]+/', '', $raw) ?? $raw;
    if (strpos($compact, 'HIGHLOSS') !== false || strpos($compact, 'HIGHATTENUATION') !== false) {
        return 'HIGH_LOSS';
    }
    if (strpos($compact, 'BREAKCUT') !== false || strpos($compact, 'FIBERBREAK') !== false
        || strpos($compact, 'CABLECUT') !== false || $compact === 'CUT' || strpos($compact, 'BROKEN') !== false) {
        return 'BREAK_CUT';
    }
    return $raw;
}

$search = trim((string)($_GET['search'] ?? ''));
$routeFilter = max(0, (int)($_GET['route_id'] ?? 0));
$severityFilter = strtoupper(trim((string)($_GET['alert'] ?? 'ALL')));
$sectorKm = (int)($_GET['sector_km'] ?? 2);
if (!in_array($sectorKm, [2, 5, 10, 20, 30], true)) {
    $sectorKm = 2;
}
$allowedSeverity = ['ALL', 'DISTANCE', 'LOSS', 'REPAIR', 'CABLE'];
if (!in_array($severityFilter, $allowedSeverity, true)) {
    $severityFilter = 'ALL';
}

/* Zone restriction is applied to both the route filter and analysis data. */
$where = [];
$params = [];

if (!$isSuperAdmin) {
    if ($zoneId === null || (int)$zoneId <= 0) {
        $where[] = '1 = 0';
    } else {
        $where[] = 'r.zone_id = ?';
        $params[] = (int)$zoneId;
    }
}

if ($routeFilter > 0) {
    $where[] = 'r.id = ?';
    $params[] = $routeFilter;
}

if ($search !== '') {
    $where[] = '(r.route_name LIKE ? OR CAST(fc.core_no AS CHAR) LIKE ? OR fc.remark LIKE ?)';
    $like = '%' . $search . '%';
    array_push($params, $like, $like, $like);
}

$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

/*
 * Show the username for the latest OTDR session.
 * test_sessions.taken_by stores users.id, so join users to return users.username.
 * This uses the existing schema; no database changes are required.
 */
$lastUpdateSelect = "u.username AS last_update_by";

/*
 * Latest OTDR test per core, and latest event attached to that test.
 * The selected columns match the existing FibreCore code patterns.
 */
$sql = "
    SELECT
        r.id AS route_id,
        r.route_name,
        r.distance_km AS target_distance_km,
        r.zone_id,
        z.zone_name,
        c.name AS cable_name,
        c.core_count,
        fc.id AS core_id,
        fc.core_no,
        fc.status AS core_status,
        fc.fault_type,
        fc.remark AS core_remark,
        cc.continuity_status,
        ct.id AS test_id,
        ct.fiber_length_km,
        ct.total_loss_db,
        ct.pm_1310_dbm,
        ct.pm_1550_dbm,
        ct.remark AS test_remark,
        ts.test_date,
        {$lastUpdateSelect},
        ev.event_type,
        ev.distance_km AS event_distance_km,
        ev.joint_name
    FROM routes r
    LEFT JOIN zones z ON z.id = r.zone_id
    LEFT JOIN cable_types c ON c.id = r.cable_type_id
    INNER JOIN fiber_cores fc ON fc.route_id = r.id
    LEFT JOIN core_continuity cc ON cc.id = (
        SELECT cc2.id
        FROM core_continuity cc2
        WHERE cc2.route_id = r.id AND cc2.core_id = fc.id
        ORDER BY cc2.id DESC
        LIMIT 1
    )
    LEFT JOIN core_tests ct ON ct.id = (
        SELECT ct2.id
        FROM core_tests ct2
        WHERE ct2.core_id = fc.id
        ORDER BY ct2.id DESC
        LIMIT 1
    )
    LEFT JOIN test_sessions ts ON ts.id = ct.session_id
    LEFT JOIN users u ON u.id = ts.taken_by
    LEFT JOIN core_events ev ON ev.id = (
        SELECT ev2.id
        FROM core_events ev2
        WHERE ev2.core_test_id = ct.id
        ORDER BY ev2.event_no DESC, ev2.id DESC
        LIMIT 1
    )
    {$whereSql}
    ORDER BY r.route_name ASC, fc.core_no ASC
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* Route dropdown: only routes this account is permitted to view. */
$routeSql = "
    SELECT r.id, r.route_name
    FROM routes r
";
$routeParams = [];
if (!$isSuperAdmin) {
    if ($zoneId === null || (int)$zoneId <= 0) {
        $routeSql .= " WHERE 1 = 0";
    } else {
        $routeSql .= " WHERE r.zone_id = ?";
        $routeParams[] = (int)$zoneId;
    }
}
$routeSql .= " ORDER BY r.route_name";
$routeStmt = $pdo->prepare($routeSql);
$routeStmt->execute($routeParams);
$routesForFilter = $routeStmt->fetchAll(PDO::FETCH_ASSOC);

/*
 * EVENT SEGMENT ANALYSIS (portal only)
 * Pull ALL events for the latest OTDR test of each core, rather than only
 * the latest single event. Event loss totals are sums of recorded event loss;
 * they are not presented as OTDR span attenuation or cumulative loss.
 */
$eventSql = "
    SELECT
        r.id AS route_id,
        r.route_name,
        r.distance_km AS target_distance_km,
        z.zone_name,
        c.name AS cable_name,
        fc.id AS core_id,
        fc.core_no,
        fc.status AS core_status,
        fc.fault_type AS core_fault_type,
        ct.id AS test_id,
        ct.fiber_length_km,
        ct.total_loss_db,
        ct.pm_1310_dbm,
        ct.pm_1550_dbm,
        ts.test_date,
        ev.id AS event_id,
        ev.event_no,
        ev.distance_km AS event_distance_km,
        ev.loss_db AS event_loss_db,
        ev.event_type,
        ev.status AS event_status,
        ev.joint_name,
        ev.remark AS event_remark
    FROM routes r
    LEFT JOIN zones z ON z.id = r.zone_id
    LEFT JOIN cable_types c ON c.id = r.cable_type_id
    INNER JOIN fiber_cores fc ON fc.route_id = r.id
    LEFT JOIN core_tests ct ON ct.id = (
        SELECT ct2.id FROM core_tests ct2
        WHERE ct2.core_id = fc.id
        ORDER BY ct2.id DESC LIMIT 1
    )
    LEFT JOIN test_sessions ts ON ts.id = ct.session_id
    LEFT JOIN core_events ev ON ev.core_test_id = ct.id
    {$whereSql}
    ORDER BY r.route_name ASC, ev.distance_km ASC, fc.core_no ASC, ev.event_no ASC
";
$eventStmt = $pdo->prepare($eventSql);
$eventStmt->execute($params);
$eventRows = $eventStmt->fetchAll(PDO::FETCH_ASSOC);

$eventSegments = [];
$eventRouteMeta = [];
foreach ($rows as $coreRow) {
    $rid = (int)$coreRow['route_id'];
    $targetKm = is_numeric($coreRow['target_distance_km'] ?? null) ? (float)$coreRow['target_distance_km'] : 0.0;
    if (!isset($eventRouteMeta[$rid])) {
        $eventRouteMeta[$rid] = [
            'route_id' => $rid,
            'route_name' => (string)$coreRow['route_name'],
            'zone_name' => (string)($coreRow['zone_name'] ?? 'Zone not assigned'),
            'cable_name' => (string)($coreRow['cable_name'] ?? '—'),
            'target' => max(0.0, $targetKm),
        ];
    }
}

// Build selectable sector bins for each permitted/filtered route, including bins without events.
foreach ($eventRouteMeta as $rid => $meta) {
    $targetKm = (float)$meta['target'];
    if ($targetKm <= 0) continue;
    $segmentCount = (int)ceil($targetKm / $sectorKm);
    // Safety cap against malformed route distances creating an excessive page.
    $segmentCount = min($segmentCount, 5000);
    for ($segmentIndex = 0; $segmentIndex < $segmentCount; $segmentIndex++) {
        $startKm = $segmentIndex * $sectorKm;
        $endKm = min($startKm + $sectorKm, $targetKm);
        $key = $rid . ':' . $segmentIndex;
        $eventSegments[$key] = $meta + [
            'segment_index' => $segmentIndex,
            'start_km' => $startKm,
            'end_km' => $endKm,
            'event_count' => 0,
            'known_loss_count' => 0,
            'high_loss_count' => 0,
            'high_loss_cores' => [],
            'break_cut_count' => 0,
            'event_items' => [],
            'affected_cores' => [],
            'test_ids' => [],
            'total_loss_values' => [],
            'pm1310_values' => [],
            'pm1550_values' => [],
        ];
    }
}

foreach ($eventRows as $er) {
    $hasSavedEvent = ($er['event_id'] !== null && is_numeric($er['event_distance_km'] ?? null));
    $distanceValue = $hasSavedEvent ? $er['event_distance_km'] : null;
    $eventTypeValue = $er['event_type'] ?? '';
    $eventStatusValue = $er['event_status'] ?? '';
    $eventLossValue = $er['event_loss_db'] ?? null;

    /*
     * Fallback for legacy OTDR records: some fault candidates are saved on the
     * core/test record without a core_events row. Use the recorded OTDR span as
     * a CANDIDATE location only when the core fault type explicitly identifies
     * CUT/BREAK/HIGH LOSS, or the saved total loss reaches the existing 1.00 dB
     * threshold. This does not create or write any database records.
     */
    if (!$hasSavedEvent) {
        $coreFaultType = span_event_category($er['core_fault_type'] ?? '');
        $coreStatus = strtoupper(trim((string)($er['core_status'] ?? '')));
        $totalLoss = is_numeric($er['total_loss_db'] ?? null) ? (float)$er['total_loss_db'] : null;
        $fallbackType = '';
        if (in_array($coreFaultType, ['HIGH_LOSS', 'BREAK_CUT'], true)) {
            $fallbackType = $coreFaultType;
        } elseif ($totalLoss !== null && $totalLoss >= 1.00) {
            $fallbackType = 'HIGH_LOSS';
        }
        if ($fallbackType === '' || !is_numeric($er['fiber_length_km'] ?? null)) {
            continue;
        }
        $distanceValue = $er['fiber_length_km'];
        $eventTypeValue = $fallbackType;
        $eventStatusValue = $fallbackType;
        $eventLossValue = $totalLoss;
    }

    if (!is_numeric($distanceValue)) continue;
    $rid = (int)$er['route_id'];
    $distance = max(0.0, (float)$distanceValue);
    $target = is_numeric($er['target_distance_km'] ?? null) ? (float)$er['target_distance_km'] : null;
    // Keep an event at the exact route endpoint in the final segment.
    if ($target !== null && $target > 0 && $distance >= $target) {
        $segmentIndex = max(0, (int)ceil($target / $sectorKm) - 1);
    } else {
        $segmentIndex = (int)floor($distance / $sectorKm);
    }
    $key = $rid . ':' . $segmentIndex;
    if (!isset($eventSegments[$key])) {
        // Event beyond the route target: retain it in a visible extra segment, never discard it.
        $meta = $eventRouteMeta[$rid] ?? [
            'route_id' => $rid, 'route_name' => (string)$er['route_name'],
            'zone_name' => (string)($er['zone_name'] ?? 'Zone not assigned'),
            'cable_name' => (string)($er['cable_name'] ?? '—'), 'target' => $target,
        ];
        $startKm = $segmentIndex * $sectorKm;
        $eventSegments[$key] = $meta + [
            'segment_index' => $segmentIndex, 'start_km' => $startKm, 'end_km' => $startKm + $sectorKm,
            'event_count' => 0, 'known_loss_count' => 0,
            'high_loss_count' => 0, 'high_loss_cores' => [], 'break_cut_count' => 0, 'event_items' => [],
            'affected_cores' => [], 'test_ids' => [], 'total_loss_values' => [],
            'pm1310_values' => [], 'pm1550_values' => [],
        ];
    }
    $seg =& $eventSegments[$key];
    $seg['event_count']++;
    $eventTypeRaw = strtoupper(trim((string)($eventTypeValue ?: 'UNKNOWN')));
    $eventStatusRaw = strtoupper(trim((string)$eventStatusValue));
    $eventType = span_event_category($eventTypeRaw);
    $eventStatus = span_event_category($eventStatusRaw);
    // Count each event once even when both event_type and status describe the same fault.
    $eventCategories = [$eventType, $eventStatus];
    if (in_array('HIGH_LOSS', $eventCategories, true)) {
        $seg['high_loss_count']++;
        $seg['high_loss_cores'][(string)$er['core_no']] = true;
    }
    if (in_array('BREAK_CUT', $eventCategories, true)) $seg['break_cut_count']++;
    if ($eventType === 'UNKNOWN' && $eventStatus !== '') $eventType = $eventStatus;
    // Event loss is retained per event for View Details, but is not summed into a misleading sector SpanLoss value.
    if (is_numeric($eventLossValue)) {
        $seg['known_loss_count']++;
    }
    $seg['affected_cores'][(string)$er['core_no']] = true;
    if ($er['test_id'] !== null) $seg['test_ids'][(string)$er['test_id']] = true;
    if (is_numeric($er['total_loss_db'] ?? null)) $seg['total_loss_values'][] = (float)$er['total_loss_db'];
    if (is_numeric($er['pm_1310_dbm'] ?? null)) $seg['pm1310_values'][] = (float)$er['pm_1310_dbm'];
    if (is_numeric($er['pm_1550_dbm'] ?? null)) $seg['pm1550_values'][] = (float)$er['pm_1550_dbm'];
    $seg['event_items'][] = [
        'core_no' => $er['core_no'], 'event_no' => $er['event_no'],
        'distance_km' => $distance, 'loss_db' => $eventLossValue,
        'event_type' => $eventType, 'event_status' => $eventStatus,
        'joint_name' => $er['joint_name'], 'remark' => $er['event_remark'],
        'test_date' => $er['test_date'],
    ];
    unset($seg);
}

usort($eventSegments, static function (array $a, array $b): int {
    return strcmp((string)$a['route_name'], (string)$b['route_name'])
        ?: ((float)$a['start_km'] <=> (float)$b['start_km']);
});

// Sector table pagination: show no more than five 2-km sectors per page.
$sectorPerPage = 5;
$sectorTotalRows = count($eventSegments);
$sectorTotalPages = max(1, (int)ceil($sectorTotalRows / $sectorPerPage));
$sectorCurrentPage = max(1, min($sectorTotalPages, (int)($_GET['sector_page'] ?? 1)));
$sectorOffset = ($sectorCurrentPage - 1) * $sectorPerPage;
$sectorPageSegments = array_slice(array_values($eventSegments), $sectorOffset, $sectorPerPage);
$sectorPageUrl = static function (int $page) use ($search, $routeFilter, $severityFilter, $sectorKm): string {
    return 'span_loss_analysis.php?' . http_build_query([
        'search' => $search,
        'route_id' => $routeFilter,
        'alert' => $severityFilter,
        'sector_km' => $sectorKm,
        'sector_page' => $page,
    ]);
};

/* Standalone event detail view opened in a popup window. Route/Zone access
   remains enforced by the same scoped queries above. */
if (isset($_GET['event_details'])) {
    $detailKey = (string)$_GET['event_details'];
    $detailSegment = null;
    foreach ($eventSegments as $candidateSegment) {
        $candidateKey = (int)$candidateSegment['route_id'] . ':' . (int)$candidateSegment['segment_index'];
        if (hash_equals($candidateKey, $detailKey)) {
            $detailSegment = $candidateSegment;
            break;
        }
    }
    if (!$detailSegment) {
        http_response_code(404);
        exit('Event sector not found or access denied.');
    }
    ?><!doctype html>
    <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
    <title>OTDR Event Details — <?= span_e($detailSegment['route_name']) ?></title>
    <style>
      *{box-sizing:border-box}body{font:14px Arial,sans-serif;margin:0;background:#f4f7fb;color:#172b4d}
      .topbar{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:16px 22px;background:#fff;border-bottom:1px solid #dbe4f0;position:sticky;top:0}
      .brand{font-weight:700;color:#1263c7;font-size:16px}.actions{display:flex;gap:8px}.btn{border:1px solid #cbd8e8;background:#fff;border-radius:6px;padding:8px 12px;color:#174a85;cursor:pointer;font-weight:600}.btn.primary{background:#1473e6;color:#fff;border-color:#1473e6}
      main{max-width:1250px;margin:22px auto;padding:0 18px}.panel{background:#fff;border:1px solid #e0e8f2;border-radius:10px;padding:20px;box-shadow:0 2px 8px rgba(20,45,80,.04)}
      h1{font-size:23px;margin:0 0 16px;color:#102a50}.summary{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px;margin-bottom:16px}.summary-card{background:#eef5ff;border:1px solid #dfebfc;border-radius:8px;padding:12px}.label{font-size:11px;text-transform:uppercase;letter-spacing:.04em;color:#526985;margin-bottom:5px}.value{font-size:15px;font-weight:700;overflow-wrap:anywhere}.notice{padding:12px 14px;background:#f0f6ff;border-radius:8px;margin:12px 0 18px;line-height:1.55}.table-wrap{overflow-x:auto}table{width:100%;border-collapse:collapse;min-width:700px}th,td{border:1px solid #dbe4ef;padding:10px 12px;text-align:left;vertical-align:middle}th{background:#f0f4f9;color:#233b5d;font-size:12px;white-space:nowrap}tr:nth-child(even){background:#f8fbff}.position{display:inline-block;padding:5px 9px;border-radius:6px;background:#e2efff;color:#075fc7;font-weight:700;white-space:nowrap}.muted{color:#64748b;margin-top:15px;font-size:12px}
      @media(max-width:760px){main{margin:12px auto;padding:0 10px}.panel{padding:14px}.summary{grid-template-columns:repeat(2,minmax(0,1fr))}.topbar{padding:12px}.brand{font-size:14px}h1{font-size:20px}}
      @media print{body{background:#fff}.topbar{position:static;padding:0 0 12px}.actions{display:none}main{max-width:none;margin:0;padding:0}.panel{border:0;box-shadow:none;padding:0}.summary-card,.notice{background:#fff;border:1px solid #ddd}button{display:none}}
    </style></head><body>
    <header class="topbar"><div class="brand">FibreCore <span style="color:#71839b;font-weight:400">/ OTDR Event Details</span></div><div class="actions"><button class="btn" onclick="window.print()">Print</button><button class="btn primary" onclick="window.close()">Close Window</button></div></header>
    <main><section class="panel">
    <h1>OTDR Event Details</h1>
    <div class="summary">
      <div class="summary-card"><div class="label">Route / Cable</div><div class="value"><?= span_e($detailSegment['route_name']) ?></div></div>
      <div class="summary-card"><div class="label">Zone</div><div class="value"><?= span_e($detailSegment['zone_name'] ?: '—') ?></div></div>
      <div class="summary-card"><div class="label">Actual Distance</div><div class="value"><?= span_num($detailSegment['target'] ?? null, 3) ?> km</div></div>
      <div class="summary-card"><div class="label">Sector</div><div class="value"><?= span_num($detailSegment['start_km'], 3) ?>–<?= span_num($detailSegment['end_km'], 3) ?> km</div></div>
    </div>
    <div class="notice"><strong>Total event records:</strong> <?= (int)$detailSegment['event_count'] ?> &nbsp; | &nbsp; <strong>Affected cores:</strong> <?= count($detailSegment['affected_cores']) ?><br><strong>Core list:</strong> <?= span_e(implode(', ', array_keys($detailSegment['affected_cores']))) ?></div>
    <div class="table-wrap"><table><thead><tr><th>Core</th><th>Position</th><th>Distance (km)</th><th>Loss (dB)</th><th>Test Date</th><th>Remark</th></tr></thead><tbody>
    <?php foreach ($detailSegment['event_items'] as $item): ?>
    <tr><td><?= span_e($item['core_no']) ?></td><td><span class="position">Position <?= max(1, (int)($item['event_no'] ?? 1)) ?></span></td><td><?= span_num($item['distance_km']) ?></td><td><?= span_num($item['loss_db']) ?></td><td><?= span_e($item['test_date'] ?: '—') ?></td><td><?= span_e($item['remark'] ?: '—') ?></td></tr>
    <?php endforeach; ?>
    </tbody></table></div><p class="muted">Verify OTDR trace and field location before confirming repair position.</p>
    </section></main></body></html><?php
    exit;
}


/*
 * Advisory rules:
 * 1) A distance gap is flagged only when both values exist.
 * 2) A loss alert uses the existing high_loss_threshold_db setting
 *    (fallback 1.00 dB, matching existing FibreCore code).
 * 3) Core repair is suggested for high loss / faulty / break / splice /
 *    connector events.
 * 4) Cable inspection/replacement review is suggested when multiple
 *    cores on the same route show fault indicators. This is not an
 *    automatic replacement decision.
 */
$lossThreshold = 1.00;
try {
    $settingStmt = $pdo->prepare("
        SELECT setting_value
        FROM settings
        WHERE setting_key = 'high_loss_threshold_db'
        LIMIT 1
    ");
    $settingStmt->execute();
    $settingValue = $settingStmt->fetchColumn();
    if ($settingValue !== false && is_numeric($settingValue)) {
        $lossThreshold = (float)$settingValue;
    }
} catch (Throwable $ignored) {
    $lossThreshold = 1.00;
}

$routeFaultCounts = [];
$faultyCoreIds = [];
$eventFaultCoreIds = [];
$usedCoreIds = [];
$throughCoreIds = [];
$totalCoreIds = [];

// First collect physical/OTDR fault evidence from the latest test per core.
foreach ($eventRows as $eventRow) {
    $eventType = span_event_category($eventRow['event_type'] ?? '');
    $eventStatus = span_event_category($eventRow['event_status'] ?? '');
    if (in_array($eventType, ['HIGH_LOSS', 'BREAK_CUT'], true)
        || in_array($eventStatus, ['HIGH_LOSS', 'BREAK_CUT'], true)) {
        $eventFaultCoreIds[(int)$eventRow['core_id']] = true;
        $faultyCoreIds[(int)$eventRow['core_id']] = true;
    }
}

foreach ($rows as $row) {
    $rid = (int)$row['route_id'];
    $cid = (int)$row['core_id'];
    $totalCoreIds[$cid] = true;
    $status = strtoupper(trim((string)($row['core_status'] ?? '')));
    $continuityStatus = strtoupper(trim((string)($row['continuity_status'] ?? 'UNVERIFIED')));

    if ($status === 'USED') $usedCoreIds[$cid] = true;
    $faultType = span_event_category($row['fault_type'] ?? '');
    if ($status === 'FAULTY' || in_array($faultType, ['HIGH_LOSS', 'BREAK_CUT'], true)) {
        $faultyCoreIds[$cid] = true;
    }

    // Through Core KPI is the pool of cores eligible to be reserved for transfer:
    // 1) latest continuity verification confirms Node A -> Node B;
    // 2) current core status is FREE (FREE alone is not proof of continuity);
    // 3) no FAULTY status, fault_type, or HIGH_LOSS / BREAK-CUT event is recorded.
    // Event rows cover every event on the latest OTDR test; core fault_type is
    // checked separately so a saved fault flag cannot be overlooked.
    // This is an eligibility count, not a persisted reservation record; the current
    // schema/code reviewed here does not expose a dedicated reservation field.
    if ($continuityStatus === 'CONFIRMED_THROUGH'
        && $status === 'FREE'
        && !isset($faultyCoreIds[$cid])) {
        $throughCoreIds[$cid] = true;
    }
}
foreach ($faultyCoreIds as $coreId => $_) {
    foreach ($rows as $row) {
        if ((int)$row['core_id'] === (int)$coreId) {
            $rid = (int)$row['route_id'];
            $routeFaultCounts[$rid] = ($routeFaultCounts[$rid] ?? 0) + 1;
            break;
        }
    }
}

$analysis = [];
$rawAnalysis = []; // Semua core untuk Raw Data, tanpa ditapis oleh Alert type.
$summary = [
    'cores' => count($totalCoreIds),
    'used' => count($usedCoreIds),
    'faulty' => count($faultyCoreIds),
    'through' => count($throughCoreIds),
    'distance' => 0,
    'loss' => 0,
    'repair' => 0,
    'cable' => 0,
];

foreach ($rows as $row) {
    $target = is_numeric($row['target_distance_km'] ?? null) ? (float)$row['target_distance_km'] : null;
    $measured = is_numeric($row['fiber_length_km'] ?? null) ? (float)$row['fiber_length_km'] : null;
    // Some legacy OTDR records may have been saved in metres although the
    // column is named fiber_length_km. If the reading is implausibly larger
    // than the route target, convert metres to kilometres for analysis.
    if ($measured !== null && $target !== null && $target > 0 && $measured > ($target * 10)) {
        $measured /= 1000;
    }
    $loss = is_numeric($row['total_loss_db'] ?? null) ? (float)$row['total_loss_db'] : null;
    $event = span_event_category($row['event_type'] ?? '');
    $status = strtoupper(trim((string)($row['core_status'] ?? '')));
    $faultType = span_event_category($row['fault_type'] ?? '');

    $distanceGap = ($target !== null && $measured !== null) ? $target - $measured : null;
    $distanceToleranceKm = 0.045; // 45 metres
    $distanceAlert = ($distanceGap !== null && abs($distanceGap) > $distanceToleranceKm);
    $within45m = ($distanceGap !== null && abs($distanceGap) <= $distanceToleranceKm);
    $lossAlert = ($loss !== null && $loss >= $lossThreshold)
        || $faultType === 'HIGH_LOSS'
        || $status === 'FAULTY';

    $eventNeedsRepair = in_array($event, ['HIGH_LOSS', 'BREAK_CUT', 'SPLICE', 'CONNECTOR', 'REFLECTION'], true);
    $repairAlert = $lossAlert || $eventNeedsRepair;

    $faultCount = (int)($routeFaultCounts[(int)$row['route_id']] ?? 0);
    $cableAlert = $faultCount >= 3;

    $recommendations = [];
    if ($distanceAlert) {
        $recommendations[] = ($distanceGap > 0)
            ? 'Perbezaan jarak melebihi 45 m dan bacaan OTDR lebih pendek daripada sasaran. Sahkan titik hujung span, konfigurasi OTDR dan rekod route.'
            : 'Perbezaan jarak melebihi 45 m dan bacaan OTDR melebihi sasaran. Semak unit, tetapan OTDR dan nilai yang direkodkan sebelum tindakan lapangan.';
    } elseif ($within45m) {
        $recommendations[] = 'Jarak OTDR berada dalam toleransi 45 m daripada sasaran. Tandakan untuk INSPECT/VERIFY; buat REPAIR hanya jika bacaan loss, status core atau event OTDR menunjukkan fault.';
    }
    if ($repairAlert) {
        if ($event === 'BREAK_CUT') {
            $recommendations[] = 'Periksa lokasi break/cut yang direkodkan dan rancang pembaikan core/kabel.';
        } elseif ($event === 'SPLICE') {
            $recommendations[] = 'Periksa sambungan splice dan ukur semula loss selepas pembaikan.';
        } elseif ($event === 'CONNECTOR' || $event === 'REFLECTION') {
            $recommendations[] = 'Periksa connector/reflection, kebersihan dan sambungan sebelum mengganti komponen.';
        } else {
            $recommendations[] = 'Jalankan pemeriksaan OTDR pada core ini dan tentukan lokasi loss sebelum pembaikan.';
        }
    }
    if ($cableAlert) {
        $recommendations[] = 'Beberapa core pada route ini mempunyai petunjuk fault. Periksa kabel/joint bersama; pertimbangkan penggantian hanya selepas kerosakan kabel disahkan.';
    }
    if (!$recommendations && $row['test_id'] === null) {
        $recommendations[] = 'Belum ada rekod OTDR. Jalankan ujian 1310 nm dan 1550 nm untuk membolehkan analisis.';
    }
    if (!$recommendations) {
        $recommendations[] = 'Tiada alert berdasarkan bacaan terkini dan ambang semasa.';
    }

    $row['_distance_gap'] = $distanceGap;
    $row['_distance_alert'] = $distanceAlert;
    $row['_within_45m'] = $within45m;
    $row['_loss_alert'] = $lossAlert;
    $row['_repair_alert'] = $repairAlert;
    $row['_cable_alert'] = $cableAlert;
    $row['_recommendations'] = $recommendations;

    // Simpan setiap core untuk export Raw Data, termasuk status USED tanpa OTDR.
    $rawAnalysis[] = $row;

    $matchesSeverity = true;
    if ($severityFilter === 'DISTANCE') $matchesSeverity = $distanceAlert;
    if ($severityFilter === 'LOSS') $matchesSeverity = $lossAlert;
    if ($severityFilter === 'REPAIR') $matchesSeverity = $repairAlert;
    if ($severityFilter === 'CABLE') $matchesSeverity = $cableAlert;

    if ($matchesSeverity) {
        $analysis[] = $row;
        if ($distanceAlert) $summary['distance']++;
        if ($lossAlert) $summary['loss']++;
        if ($repairAlert) $summary['repair']++;
        if ($cableAlert) $summary['cable']++;
    }
}

/*
 * ARRANGE SPAN: create a stable PivotTable grouping per route.
 * Each reading joins a cluster only when it is within 0.045 km (45 m)
 * of that cluster's first/lowest reading. The original OTDR span remains exact.
 */
$arrangeSpanByCore = [];
$spanRowsByRoute = [];
foreach ($rawAnalysis as $idx => $item) {
    $target = is_numeric($item['target_distance_km'] ?? null) ? (float)$item['target_distance_km'] : null;
    $distance = is_numeric($item['fiber_length_km'] ?? null) ? (float)$item['fiber_length_km'] : null;
    if ($distance !== null && $target !== null && $target > 0 && $distance > ($target * 10)) {
        $distance /= 1000;
    }
    if ($distance === null || $distance <= 0) {
        // Make missing-span records visible in PivotTable instead of "(blank)".
        // This is a status label, NOT an estimated OTDR distance.
        $missingStatus = strtoupper(trim((string)($item['core_status'] ?? 'UNKNOWN')));
        $missingStatus = $missingStatus !== '' ? $missingStatus : 'UNKNOWN';
        $arrangeSpanByCore[$idx] = $missingStatus . ' - NO OTDR';
        continue;
    }
    $routeKey = (string)($item['route_id'] ?? '0');
    $spanRowsByRoute[$routeKey][] = ['idx' => $idx, 'distance' => $distance];
}
foreach ($spanRowsByRoute as $routeKey => $spanRows) {
    usort($spanRows, static function (array $a, array $b): int {
        return ($a['distance'] <=> $b['distance']) ?: ($a['idx'] <=> $b['idx']);
    });
    $clusters = [];
    foreach ($spanRows as $spanRow) {
        $placed = false;
        foreach ($clusters as &$cluster) {
            // Compare against the cluster's first reading to avoid chain grouping.
            if (($spanRow['distance'] - $cluster['reference']) <= 0.045 + 1e-9) {
                $cluster['items'][] = $spanRow;
                $cluster['min'] = min($cluster['min'], $spanRow['distance']);
                $cluster['max'] = max($cluster['max'], $spanRow['distance']);
                $placed = true;
                break;
            }
        }
        unset($cluster);
        if (!$placed) {
            $clusters[] = [
                'reference' => $spanRow['distance'],
                'min' => $spanRow['distance'],
                'max' => $spanRow['distance'],
                'items' => [$spanRow],
            ];
        }
    }
    foreach ($clusters as $cluster) {
        $label = number_format($cluster['min'], 3, '.', '') . ' km';
        if (abs($cluster['max'] - $cluster['min']) > 0.0000001) {
            $label = number_format($cluster['min'], 3, '.', '') . '–' . number_format($cluster['max'], 3, '.', '') . ' km';
        }
        foreach ($cluster['items'] as $spanRow) {
            $arrangeSpanByCore[$spanRow['idx']] = $label;
        }
    }
}

/*
 * RAW DATA EXPORT: one row per core, suitable for Excel PivotTable.
 * Keeps the active search and route filters. The exact OTDR span is retained;
 * Arrange Span is an additional 45 m cluster label for PivotTable grouping. Core Record Count is 1 per row so PivotTables can count cores even when OTDR Span is blank.
 */
if (($_GET['export'] ?? '') === 'raw') {
    $filename = 'fibercore_span_loss_raw_' . date('Ymd_His') . '.csv';
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Pragma: no-cache');
    header('Expires: 0');

    $out = fopen('php://output', 'w');
    if ($out === false) {
        http_response_code(500);
        exit('Unable to create CSV export.');
    }

    // UTF-8 BOM helps Microsoft Excel display text correctly.
    fwrite($out, "\xEF\xBB\xBF");
    fputcsv($out, [
        'Route ID', 'Route Name', 'Zone', 'Cable Type', 'Core ID', 'Core Number',
        'Core Record Count', 'Core Status', 'Fault Type', 'Target Distance (km)', 'OTDR Span (km)', 'Arrange Span (KM)',
        'Gap (km)', 'Absolute Gap (m)', 'Total Loss (dB)', 'Span Loss Rate (dB/km)',
        '1310 nm Reading (dBm)', '1550 nm Reading (dBm)', 'Latest Event',
        'Event Distance (km)', 'Joint Name',
        'Latest Test Date', 'Last Update By', 'Distance Alert', 'High Loss / Fault Alert',
        'Repair Core Alert', 'Cable Inspection Alert', 'Core Remark', 'Test Remark'
    ], ',');

    foreach ($rawAnalysis as $idx => $r) {
        $targetRaw = is_numeric($r['target_distance_km'] ?? null) ? (float)$r['target_distance_km'] : null;
        $measuredRaw = is_numeric($r['fiber_length_km'] ?? null) ? (float)$r['fiber_length_km'] : null;
        if ($measuredRaw !== null && $targetRaw !== null && $targetRaw > 0 && $measuredRaw > ($targetRaw * 10)) {
            $measuredRaw /= 1000;
        }
        $gapRaw = ($targetRaw !== null && $measuredRaw !== null) ? ($targetRaw - $measuredRaw) : null;
        fputcsv($out, [
            $r['route_id'] ?? '', $r['route_name'] ?? '', $r['zone_name'] ?? '',
            $r['cable_name'] ?? '', $r['core_id'] ?? '', $r['core_no'] ?? '',
            1,
            strtoupper(trim((string)($r['core_status'] ?? ''))),
            (function () use ($r): string {
                $statusForExport = strtoupper(trim((string)($r['core_status'] ?? '')));
                $faultForExport = strtoupper(trim((string)($r['fault_type'] ?? '')));
                if ($statusForExport === 'USED') return 'USED';
                if ($statusForExport === 'FAULTY') return $faultForExport !== '' ? $faultForExport : 'UNKNOWN';
                return $faultForExport;
            })(),
            $targetRaw,
            $measuredRaw, $arrangeSpanByCore[$idx] ?? '', $gapRaw, $gapRaw === null ? null : abs($gapRaw) * 1000,
            $r['total_loss_db'] ?? '',
            ($measuredRaw !== null && $measuredRaw > 0 && is_numeric($r['total_loss_db'] ?? null))
                ? ((float)$r['total_loss_db'] / $measuredRaw) : '',
            $r['pm_1310_dbm'] ?? '', $r['pm_1550_dbm'] ?? '',
            $r['event_type'] ?? '', $r['event_distance_km'] ?? '', $r['joint_name'] ?? '',
            $r['test_date'] ?? '', $r['last_update_by'] ?? '', !empty($r['_distance_alert']) ? 'YES' : 'NO',
            !empty($r['_loss_alert']) ? 'YES' : 'NO', !empty($r['_repair_alert']) ? 'YES' : 'NO',
            !empty($r['_cable_alert']) ? 'YES' : 'NO', $r['core_remark'] ?? '', $r['test_remark'] ?? ''
        ], ',');
    }
    fclose($out);
    exit;
}

/*
 * GROUP REPORTS: one report per route + measured OTDR distance cluster.
 * Use event distance when available; otherwise use the saved fiber length.
 * Readings are grouped when they are within 0.045 km (45 m) of the
 * cluster's first reading. This prevents the same fault span being listed
 * repeatedly for every core.
 */
$distanceToleranceKm = 0.045;
$rowsByRoute = [];
foreach ($analysis as $item) {
    $rid = (int)$item['route_id'];
    // Group by the overall OTDR span length, not the event's position.
    // Event distance is a fault location along the fibre and must not be used
    // as a substitute for the measured span distance.
    $targetForGroup = is_numeric($item['target_distance_km'] ?? null)
        ? (float)$item['target_distance_km'] : null;
    $groupDistance = is_numeric($item['fiber_length_km'] ?? null)
        ? (float)$item['fiber_length_km'] : null;
    // Normalise legacy records stored in metres to kilometres.
    if ($groupDistance !== null && $targetForGroup !== null && $targetForGroup > 0
        && $groupDistance > ($targetForGroup * 10)) {
        $groupDistance /= 1000;
    }
    $item['_group_distance'] = $groupDistance;
    $rowsByRoute[$rid][] = $item;
}

$groupReports = [];
foreach ($rowsByRoute as $rid => $routeItems) {
    $withDistance = [];
    $withoutDistance = [];
    foreach ($routeItems as $item) {
        if ($item['_group_distance'] === null) {
            $withoutDistance[] = $item;
        } else {
            $withDistance[] = $item;
        }
    }
    usort($withDistance, static function (array $a, array $b): int {
        return ($a['_group_distance'] <=> $b['_group_distance'])
            ?: ((int)$a['core_no'] <=> (int)$b['core_no']);
    });

    $clusters = [];
    foreach ($withDistance as $item) {
        $distance = (float)$item['_group_distance'];
        $lastIndex = count($clusters) - 1;
        if ($lastIndex < 0 || ($distance - $clusters[$lastIndex]['anchor']) > $distanceToleranceKm) {
            $clusters[] = [
                'anchor' => $distance,
                'min' => $distance,
                'max' => $distance,
                'items' => [$item],
            ];
        } else {
            $clusters[$lastIndex]['items'][] = $item;
            $clusters[$lastIndex]['max'] = $distance;
        }
    }

    foreach ($clusters as $cluster) {
        $items = $cluster['items'];
        $first = $items[0];
        $coreNumbers = [];
        $repair = $loss = $distanceAlert = $cable = false;
        $lossValues = [];
        $spanLossRates = [];
        $events = [];
        foreach ($items as $it) {
            $coreNumbers[] = (string)$it['core_no'];
            $repair = $repair || !empty($it['_repair_alert']);
            $loss = $loss || !empty($it['_loss_alert']);
            $distanceAlert = $distanceAlert || !empty($it['_distance_alert']);
            $cable = $cable || !empty($it['_cable_alert']);
            if (is_numeric($it['total_loss_db'] ?? null)) {
                $lossValue = (float)$it['total_loss_db'];
                $lossValues[] = $lossValue;
                $itemDistance = is_numeric($it['_group_distance'] ?? null) ? (float)$it['_group_distance'] : null;
                if ($itemDistance !== null && $itemDistance > 0) {
                    $spanLossRates[] = $lossValue / $itemDistance;
                }
            }
            $ev = trim((string)($it['event_type'] ?? ''));
            if ($ev !== '' && $ev !== '—') $events[$ev] = true;
        }
        $groupReports[] = [
            'route_id' => (int)$rid,
            'route_name' => $first['route_name'],
            'zone_name' => $first['zone_name'] ?? 'Zone not assigned',
            'cable_name' => $first['cable_name'] ?? '—',
            'target' => is_numeric($first['target_distance_km'] ?? null) ? (float)$first['target_distance_km'] : null,
            'distance' => (float)$cluster['anchor'],
            'min_distance' => (float)$cluster['min'],
            'max_distance' => (float)$cluster['max'],
            'gap' => is_numeric($first['target_distance_km'] ?? null) ? ((float)$first['target_distance_km'] - (float)$cluster['anchor']) : null,
            'cores' => $coreNumbers,
            'core_count' => count($items),
            'loss_values' => $lossValues,
            'span_loss_rates' => $spanLossRates,
            'events' => array_keys($events),
            'distance_alert' => $distanceAlert,
            'loss_alert' => $loss,
            'repair_alert' => $repair,
            'cable_alert' => $cable,
            'items' => $items,
        ];
    }

    if ($withoutDistance) {
        $first = $withoutDistance[0];
        $coreNumbers = [];
        $repair = $loss = $distanceAlert = $cable = false;
        foreach ($withoutDistance as $it) {
            $coreNumbers[] = (string)$it['core_no'];
            $repair = $repair || !empty($it['_repair_alert']);
            $loss = $loss || !empty($it['_loss_alert']);
            $distanceAlert = $distanceAlert || !empty($it['_distance_alert']);
            $cable = $cable || !empty($it['_cable_alert']);
        }
        $groupReports[] = [
            'route_id' => (int)$rid,
            'route_name' => $first['route_name'],
            'zone_name' => $first['zone_name'] ?? 'Zone not assigned',
            'cable_name' => $first['cable_name'] ?? '—',
            'target' => is_numeric($first['target_distance_km'] ?? null) ? (float)$first['target_distance_km'] : null,
            'distance' => null, 'min_distance' => null, 'max_distance' => null, 'gap' => null,
            'cores' => $coreNumbers, 'core_count' => count($withoutDistance),
            'loss_values' => [], 'events' => [],
            'distance_alert' => $distanceAlert, 'loss_alert' => $loss,
            'repair_alert' => $repair, 'cable_alert' => $cable,
            'items' => $withoutDistance,
        ];
    }
}

usort($groupReports, static function (array $a, array $b): int {
    return strcmp((string)$a['route_name'], (string)$b['route_name'])
        ?: (($a['distance'] ?? PHP_FLOAT_MAX) <=> ($b['distance'] ?? PHP_FLOAT_MAX));
});

/* Pagination is by grouped report, 10 reports per page, retaining filters. */
$perPage = 10;
$totalRecords = count($groupReports);
$spanTotalPages = max(1, (int)ceil($totalRecords / $perPage));
$spanCurrentPage = max(1, (int)($_GET['page'] ?? 1));
if ($spanCurrentPage > $spanTotalPages) {
    $spanCurrentPage = $spanTotalPages;
}
$spanOffset = ($spanCurrentPage - 1) * $perPage;
$analysisPage = array_slice($groupReports, $spanOffset, $perPage);

function span_page_url(int $page, string $search, int $routeId, string $alert, int $sectorKm = 2): string
{
    $query = [
        'page' => $page,
        'search' => $search,
        'route_id' => $routeId,
        'alert' => $alert,
        'sector_km' => $sectorKm,
    ];
    return 'span_loss_analysis.php?' . http_build_query($query);
}

require_once __DIR__ . '/_header.php';
?>

<style>
/* Span Loss Analysis: professional table and fixed portal navigation */
html, body { min-height: 100%; }
.main-sidebar { position: fixed !important; top: 0 !important; bottom: 0 !important; height: 100vh !important; overflow-y: auto !important; overflow-x: hidden !important; }
.main-sidebar .sidebar { height: auto !important; overflow: visible !important; }
.content-wrapper, .main-header, .main-footer { margin-left: 250px; }
.content-wrapper { min-height: 100vh; }
.span-analysis-intro { gap: 12px; }
.span-summary .small-box { min-height: 105px; border-radius: 8px; box-shadow: 0 2px 8px rgba(20,35,55,.08); }
.span-summary .small-box .inner h3 { font-size: 30px; margin-bottom: 5px; }
.span-analysis-card { border: 0; border-radius: 8px; box-shadow: 0 2px 10px rgba(20,35,55,.08); overflow: hidden; }
.span-analysis-table { min-width: 1100px; font-size: 12px; }
.span-analysis-table thead th { position: sticky; top: 0; z-index: 2; background: #f1f5f9; color: #25364a; font-weight: 700; white-space: nowrap; vertical-align: middle; border-bottom: 2px solid #d8e0e8; padding: 10px 8px; }
.span-analysis-table td { padding: 9px 8px; vertical-align: top; border-color: #e3e8ef; line-height: 1.4; }
.span-analysis-table tbody tr:nth-child(even) { background: #fafbfd; }
.span-analysis-table tbody tr:hover { background: #eef6ff; }
.span-analysis-table .route-cell { min-width: 145px; }
.span-analysis-table .recommendation-cell { min-width: 300px; max-width: 440px; white-space: normal; }
.span-analysis-table .recommendation-cell ul { padding-left: 17px; }
.span-analysis-table .recommendation-cell li { margin: 4px 0; }
.span-analysis-table .numeric-cell { white-space: nowrap; font-variant-numeric: tabular-nums; }
.span-alert-badges { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 5px; }
.span-alert-badges .badge { font-size: 10px; padding: 5px 6px; }
.span-analysis-note { border-radius: 7px; }
.span-pagination-top { background: #f8fafc; }
.span-analysis-card .pagination { display: flex; flex-wrap: wrap; gap: 2px; }
.span-analysis-card .pagination .page-link { cursor: pointer; min-width: 34px; text-align: center; }
.span-analysis-card .pagination .page-item.disabled .page-link { cursor: not-allowed; }
@media (max-width: 767.98px) { .content-wrapper, .main-header, .main-footer { margin-left: 0 !important; } .main-sidebar { transform: translateX(-250px); z-index: 1038; } body.sidebar-open .main-sidebar { transform: translateX(0); } .span-analysis-table { min-width: 1100px; } }
</style>

<div class="d-flex justify-content-between align-items-center flex-wrap mb-3 span-analysis-intro">
    <div>
        <h2 class="mb-1"><i class="fas fa-wave-square text-primary"></i> Span Loss Analysis</h2>
        <div class="text-muted">Bandingkan jarak sasaran route dengan bacaan OTDR dan semak alert pembaikan core/kabel.</div>
    </div>
    <span class="badge badge-info p-2">Loss threshold: <?= span_e(number_format($lossThreshold, 2)) ?> dB</span>
</div>



<div class="row span-summary">
    <div class="col-md-3 col-sm-6"><div class="small-box bg-info"><div class="inner"><h3><?= (int)$summary['cores'] ?></h3><p>Total Core</p></div><div class="icon"><i class="fas fa-project-diagram"></i></div></div></div>
    <div class="col-md-3 col-sm-6"><div class="small-box bg-primary"><div class="inner"><h3><?= (int)$summary['used'] ?></h3><p>Used Core</p></div><div class="icon"><i class="fas fa-plug"></i></div></div></div>
    <div class="col-md-3 col-sm-6"><div class="small-box bg-danger"><div class="inner"><h3><?= (int)$summary['faulty'] ?></h3><p>Faulty Core</p></div><div class="icon"><i class="fas fa-exclamation-triangle"></i></div></div></div>
    <div class="col-md-3 col-sm-6"><div class="small-box bg-success"><div class="inner"><h3><?= (int)$summary['through'] ?></h3><p>Through Core</p></div><div class="icon"><i class="fas fa-check-circle"></i></div></div></div>
</div>


<div class="card span-analysis-card">
    <div class="card-header">
        <h3 class="card-title"><i class="fas fa-filter"></i> Filters</h3>
    </div>
    <div class="card-body">
        <form method="get" class="row">
            <div class="col-md-5 form-group">
                <label for="search">Search route / core / remark</label>
                <input class="form-control" type="search" id="search" name="search" value="<?= span_e($search) ?>" placeholder="Search...">
            </div>
            <div class="col-md-4 form-group">
                <label for="route_id">Route</label>
                <select class="form-control" id="route_id" name="route_id">
                    <option value="0">All permitted routes</option>
                    <?php foreach ($routesForFilter as $route): ?>
                        <option value="<?= (int)$route['id'] ?>" <?= $routeFilter === (int)$route['id'] ? 'selected' : '' ?>>
                            <?= span_e($route['route_name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3 form-group">
                <label for="sector_km">Sector interval</label>
                <select class="form-control" id="sector_km" name="sector_km">
                    <?php foreach ([2, 5, 10, 20, 30] as $sectorOption): ?>
                    <option value="<?= $sectorOption ?>" <?= $sectorKm === $sectorOption ? 'selected' : '' ?>><?= $sectorOption ?> km</option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3 form-group">
                <label for="alert">Alert type</label>
                <select class="form-control" id="alert" name="alert">
                    <option value="ALL" <?= $severityFilter === 'ALL' ? 'selected' : '' ?>>All</option>
                    <option value="DISTANCE" <?= $severityFilter === 'DISTANCE' ? 'selected' : '' ?>>Distance gap</option>
                    <option value="LOSS" <?= $severityFilter === 'LOSS' ? 'selected' : '' ?>>High loss / faulty</option>
                    <option value="REPAIR" <?= $severityFilter === 'REPAIR' ? 'selected' : '' ?>>Repair core</option>
                    <option value="CABLE" <?= $severityFilter === 'CABLE' ? 'selected' : '' ?>>Cable inspection</option>
                </select>
            </div>
            <div class="col-12">
                <button class="btn btn-primary" type="submit"><i class="fas fa-search"></i> Analyse</button>
                <a class="btn btn-success" href="<?= span_e('span_loss_analysis.php?' . http_build_query(['search' => $search, 'route_id' => $routeFilter, 'alert' => $severityFilter, 'sector_km' => $sectorKm, 'export' => 'raw'])) ?>">
                    <i class="fas fa-file-csv"></i> Export Raw Data (Excel Pivot)
                </a>
                <a class="btn btn-secondary" href="span_loss_analysis.php">Reset</a>
            </div>
        </form>
    </div>
</div>

<div class="card span-analysis-card mb-4">
    <div class="card-header">
        <h3 class="card-title"><i class="fas fa-ruler-combined"></i> OTDR Event Analysis by <?= (int)$sectorKm ?> km Sector — Test Using 1550 nm</h3>
    </div>
    <div class="card-body">
     
        <div class="table-responsive">
            <table class="table table-bordered table-hover table-sm span-analysis-table">
                <thead><tr>
                    <th>Route / Zone</th><th>Actual Distance (km)</th><th>Sector (km)</th>
                    <th>T. Core High Loss</th><th>BREAK/CUT</th>
                    <th>Core(s)</th><th>Core Range Loss (dB)</th>
                    <th>Cable Assessment</th><th aria-label="Event actions"></th>
                </tr></thead>
                <tbody>
                <?php if (!$eventSegments): ?>
                    <tr><td colspan="10" class="text-center text-muted p-4">Tiada route dengan jarak sasaran yang sah untuk dibahagikan kepada sektor.</td></tr>
                <?php else: ?>
                    <?php foreach ($sectorPageSegments as $segment): ?>
                        <?php
                        $coreNames = array_keys($segment['affected_cores']);
                        sort($coreNames, SORT_NUMERIC);
                        $fmtRange = static function (array $values): string {
                            if (!$values) return '—';
                            $lo = min($values); $hi = max($values);
                            return number_format($lo, 3) . (abs($hi - $lo) > 0.000001 ? ' – ' . number_format($hi, 3) : '');
                        };
                        $hasConcern = $segment['high_loss_count'] > 0 || $segment['break_cut_count'] > 0;
                        $multipleCores = count($coreNames) >= 2;
                        ?>
                        <tr>
                            <td><strong><?= span_e($segment['route_name']) ?></strong><br><small class="text-muted"><?= span_e($segment['zone_name']) ?></small><br><small><?= span_e($segment['cable_name']) ?></small></td>
                            <td class="numeric-cell"><?= span_num($segment['target'], 3) ?></td>
                            <td class="numeric-cell"><strong><?= span_num($segment['start_km'], 0) ?>–<?= span_num($segment['end_km'], 0) ?></strong></td>
                            <td class="numeric-cell"><?= count($segment['high_loss_cores']) ?></td>
                            <td class="numeric-cell"><?= (int)$segment['break_cut_count'] ?></td>
                            <td><?= $coreNames ? span_e(implode(', ', $coreNames)) : '—' ?></td>
                            <td class="numeric-cell"><?= span_e($fmtRange($segment['total_loss_values'])) ?></td>
                            <td>
                                <?php if ($segment['break_cut_count'] > 0): ?>
                                    <span class="badge badge-danger">Investigate break/cut</span><br><small>Verify event location and cable continuity.</small>
                                <?php elseif ($segment['high_loss_count'] > 0 && $multipleCores): ?>
                                    <span class="badge badge-warning">Inspect shared cable/joint</span><br><small>Multiple cores show high-loss events; assess cable replacement only after field verification.</small>
                                <?php elseif ($segment['high_loss_count'] > 0): ?>
                                    <span class="badge badge-warning">Inspect affected core</span><br><small>Confirm OTDR trace and joint/connector before deciding repair.</small>
                                <?php elseif ($segment['event_count'] > 0): ?>
                                    <span class="badge badge-info">Review events</span><br><small>Check event type and recorded loss.</small>
                                <?php else: ?>
                                    <span class="badge badge-light">No recorded events</span><br><small>This does not mean measured loss is zero.</small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if (!$segment['event_items']): ?>
                                    <span class="text-muted">No events recorded for this segment in the latest tests.</span>
                                <?php else: ?>
                                    <a class="btn btn-sm btn-outline-primary" onclick="var w=Math.min(1280,Math.max(900,screen.availWidth-120)),h=Math.min(900,Math.max(650,screen.availHeight-120)),l=Math.max(0,Math.round((screen.availWidth-w)/2)),t=Math.max(0,Math.round((screen.availHeight-h)/2));var p=window.open(this.href,'FibreCoreOtdrEventDetails','popup=yes,width='+w+',height='+h+',left='+l+',top='+t+',resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,status=no');if(p){p.focus();return false;}return true;"
                                       href="<?= span_e('span_loss_analysis.php?' . http_build_query(['search'=>$search,'route_id'=>$routeFilter,'alert'=>$severityFilter,'sector_km'=>$sectorKm,'event_details'=>$segment['route_id'].':'.$segment['segment_index']])) ?>">
                                        View Details (<?= count($segment['event_items']) ?>)
                                    </a>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php if ($sectorTotalRows > 0): ?>
        <div class="d-flex justify-content-between align-items-center flex-wrap mt-3">
            <div class="text-muted small mb-2 mb-md-0">
                Showing <?= $sectorOffset + 1 ?>–<?= min($sectorOffset + $sectorPerPage, $sectorTotalRows) ?> of <?= $sectorTotalRows ?> sectors · Maximum 5 per page
            </div>
            <?php if ($sectorTotalPages > 1): ?>
            <nav aria-label="OTDR sector pages">
                <ul class="pagination pagination-sm mb-0">
                    <li class="page-item <?= $sectorCurrentPage <= 1 ? 'disabled' : '' ?>">
                        <?php if ($sectorCurrentPage > 1): ?><a class="page-link" href="<?= span_e($sectorPageUrl($sectorCurrentPage - 1)) ?>">Previous</a><?php else: ?><span class="page-link">Previous</span><?php endif; ?>
                    </li>
                    <?php
                    $sectorPageStart = max(1, $sectorCurrentPage - 2);
                    $sectorPageEnd = min($sectorTotalPages, $sectorCurrentPage + 2);
                    for ($sectorP = $sectorPageStart; $sectorP <= $sectorPageEnd; $sectorP++):
                    ?>
                    <li class="page-item <?= $sectorP === $sectorCurrentPage ? 'active' : '' ?>">
                        <a class="page-link" href="<?= span_e($sectorPageUrl($sectorP)) ?>" <?= $sectorP === $sectorCurrentPage ? 'aria-current="page"' : '' ?>><?= $sectorP ?></a>
                    </li>
                    <?php endfor; ?>
                    <li class="page-item <?= $sectorCurrentPage >= $sectorTotalPages ? 'disabled' : '' ?>">
                        <?php if ($sectorCurrentPage < $sectorTotalPages): ?><a class="page-link" href="<?= span_e($sectorPageUrl($sectorCurrentPage + 1)) ?>">Next &raquo;</a><?php else: ?><span class="page-link">Next &raquo;</span><?php endif; ?>
                    </li>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<div class="card span-analysis-card">
    <div class="card-header">
        <h3 class="card-title"><i class="fas fa-list"></i> Analysis Results</h3>
        <div class="card-tools">
            <span class="badge badge-light">
                <?= $totalRecords ? ($spanOffset + 1) : 0 ?>–<?= min($spanOffset + $perPage, $totalRecords) ?> of <?= $totalRecords ?> records
            </span>
        </div>
    </div>

    <?php if ($spanTotalPages > 1): ?>
        <div class="card-body border-bottom py-2 span-pagination-top">
            <div class="d-flex justify-content-between align-items-center flex-wrap">
                <div class="text-muted small mb-2 mb-md-0">
                    Page <strong><?= $spanCurrentPage ?></strong> of <strong><?= $spanTotalPages ?></strong>
                    &nbsp;·&nbsp; Showing <?= $spanOffset + 1 ?>–<?= min($spanOffset + $perPage, $totalRecords) ?> of <?= $totalRecords ?> grouped reports
                </div>
                <nav aria-label="Analysis results pages top">
                    <ul class="pagination pagination-sm mb-0">
                        <li class="page-item <?= $spanCurrentPage <= 1 ? 'disabled' : '' ?>">
                            <?php if ($spanCurrentPage > 1): ?>
                                <a class="page-link" href="<?= span_e(span_page_url($spanCurrentPage - 1, $search, $routeFilter, $severityFilter, $sectorKm)) ?>">Previous</a>
                            <?php else: ?>
                                <span class="page-link">Previous</span>
                            <?php endif; ?>
                        </li>
                        <?php
                        $pageStartTop = max(1, $spanCurrentPage - 2);
                        $pageEndTop = min($spanTotalPages, $spanCurrentPage + 2);
                        for ($pTop = $pageStartTop; $pTop <= $pageEndTop; $pTop++):
                        ?>
                            <li class="page-item <?= $pTop === $spanCurrentPage ? 'active' : '' ?>">
                                <a class="page-link" href="<?= span_e(span_page_url($pTop, $search, $routeFilter, $severityFilter, $sectorKm)) ?>" <?= $pTop === $spanCurrentPage ? 'aria-current="page"' : '' ?>><?= $pTop ?></a>
                            </li>
                        <?php endfor; ?>
                        <li class="page-item <?= $spanCurrentPage >= $spanTotalPages ? 'disabled' : '' ?>">
                            <?php if ($spanCurrentPage < $spanTotalPages): ?>
                                <a class="page-link" href="<?= span_e(span_page_url($spanCurrentPage + 1, $search, $routeFilter, $severityFilter, $sectorKm)) ?>">Next &raquo;</a>
                            <?php else: ?>
                                <span class="page-link">Next &raquo;</span>
                            <?php endif; ?>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>
    <?php endif; ?>

    <div class="card-body table-responsive p-0">
        <table class="table table-bordered table-hover table-sm mb-0 span-analysis-table">
            <thead class="thead-light">
                <tr>
                    <th>Route / Zone</th>
                    <th>Core Group</th>
                    <th>Core Count</th>
                    <th>Target (km)</th>
                    <th>OTDR Span (km)</th>
                    <th>Total Loss Range (dB)</th>
                    <th>Span Loss Rate (dB/km)</th>
                    <th>Latest Event</th>
                    <th>Report / Recommended Action</th>
                </tr>
            </thead>
            <tbody>
            <?php if (!$analysisPage): ?>
                <tr><td colspan="9" class="text-center text-muted p-4">Tiada laporan kumpulan sepadan dengan penapis ini.</td></tr>
            <?php else: ?>
                <?php foreach ($analysisPage as $group): ?>
                    <?php
                    $badges = [];
                    if ($group['distance_alert']) $badges[] = '<span class="badge badge-warning">DISTANCE GAP &gt; 45 M</span>';
                    elseif ($group['distance'] !== null && $group['gap'] !== null && abs($group['gap']) <= 0.045) $badges[] = '<span class="badge badge-info">WITHIN 45 M</span>';
                    if ($group['loss_alert']) $badges[] = '<span class="badge badge-danger">HIGH LOSS / FAULT</span>';
                    if ($group['repair_alert']) $badges[] = '<span class="badge badge-danger">REPAIR CORE</span>';
                    if ($group['cable_alert']) $badges[] = '<span class="badge badge-dark">INSPECT CABLE</span>';
                    if (!$badges) $badges[] = '<span class="badge badge-success">INSPECT / VERIFY</span>';
                    $lossMin = $group['loss_values'] ? min($group['loss_values']) : null;
                    $lossMax = $group['loss_values'] ? max($group['loss_values']) : null;
                    $spanLossMin = !empty($group['span_loss_rates']) ? min($group['span_loss_rates']) : null;
                    $spanLossMax = !empty($group['span_loss_rates']) ? max($group['span_loss_rates']) : null;
                    $eventLabel = $group['events'] ? implode(', ', $group['events']) : '—';
                    $coreList = implode(', ', $group['cores']);
                    ?>
                    <tr>
                        <td class="route-cell">
                            <strong><?= span_e($group['route_name']) ?></strong><br>
                            <small class="text-muted"><?= span_e($group['zone_name']) ?></small><br>
                            <small><?= span_e($group['cable_name']) ?></small>
                        </td>
                        <td>
                            <strong><?= span_e($coreList) ?></strong><br>
                            <small class="text-muted">Core(s)</small>
                        </td>
                        <td class="numeric-cell"><?= (int)$group['core_count'] ?></td>
                        <td class="numeric-cell"><?= span_num($group['target']) ?></td>
                        <td class="numeric-cell">
                            <?php if ($group['distance'] !== null): ?>
                                <?= span_num($group['distance']) ?>
                                <?php if ($group['min_distance'] !== $group['max_distance']): ?>
                                    <br><small class="text-muted">Range <?= span_num($group['min_distance']) ?>–<?= span_num($group['max_distance']) ?></small>
                                <?php endif; ?>
                            <?php else: ?>—<?php endif; ?>
                        </td>
                        <td class="numeric-cell">
                            <?php if ($lossMin !== null): ?>
                                <?= span_num($lossMin, 2) ?><?= $lossMax !== null && $lossMax !== $lossMin ? '–' . span_num($lossMax, 2) : '' ?>
                            <?php else: ?>—<?php endif; ?>
                        </td>
                        <td class="numeric-cell">
                            <?php if ($spanLossMin !== null): ?>
                                <?= span_num($spanLossMin, 3) ?><?= $spanLossMax !== null && abs($spanLossMax - $spanLossMin) > 0.000001 ? '–' . span_num($spanLossMax, 3) : '' ?>
                            <?php else: ?>—<?php endif; ?>
                            <br><small class="text-muted">Total Loss ÷ OTDR Span</small>
                        </td>
                        <td>
                            <?= span_e($eventLabel) ?>
                            <br><small class="text-muted">Latest test: <?= span_e($group['items'][0]['test_date'] ?? '—') ?></small>
                        </td>
                        <td class="recommendation-cell">
                            <div class="span-alert-badges">
                                <?php foreach ($badges as $badge): ?><?= $badge ?><?php endforeach; ?>
                            </div>
                            <p class="mb-1"><strong>Grouped span report:</strong> <?= (int)$group['core_count'] ?> core(s) have OTDR distance readings within 45 m of the group reference.</p>
                            <?php if ($group['distance'] === null): ?>
                                <p class="mb-1">No saved OTDR distance for these cores. Run OTDR tests before grouping by span.</p>
                            <?php elseif ($group['gap'] !== null && abs($group['gap']) > 0.045): ?>
                                <p class="mb-1">Target differs from the group reference by <?= span_num(abs($group['gap']) * 1000, 0) ?> m. Verify the saved unit and OTDR reading before dispatching repair.</p>
                            <?php else: ?>
                                <p class="mb-1">Group distance is within 45 m of the target. Inspect the listed cores together; repair only cores with confirmed loss/fault evidence.</p>
                            <?php endif; ?>
                            <?php if ($group['repair_alert']): ?><p class="mb-1">Recommended: inspect and repair the affected core(s) after confirming fault location.</p><?php endif; ?>
                            <?php if ($group['cable_alert']): ?><p class="mb-0">Several fault indicators exist on this route: inspect shared cable/joints before considering cable replacement.</p><?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card-footer">
        <div class="text-muted small mb-3">
            Laporan menggabungkan core pada route yang sama apabila panjang span OTDR keseluruhan berada dalam julat 0.045 km (45 m) daripada bacaan rujukan kumpulan. Kedudukan event/fault tidak digunakan sebagai panjang span. Pagination ialah 10 laporan kumpulan setiap halaman, bukan 10 core individu. Sahkan unit dan bacaan OTDR sebelum tindakan lapangan.
        </div>

        <?php if ($spanTotalPages > 1): ?>
            <div class="d-flex justify-content-between align-items-center flex-wrap">
                <div class="text-muted small mb-2 mb-md-0">
                    Page <strong><?= $spanCurrentPage ?></strong> of <strong><?= $spanTotalPages ?></strong>
                    &nbsp;·&nbsp; Showing <?= $spanOffset + 1 ?>–<?= min($spanOffset + $perPage, $totalRecords) ?> of <?= $totalRecords ?> records
                </div>
                <nav aria-label="Analysis results pages">
                    <ul class="pagination pagination-sm mb-0">
                        <li class="page-item <?= $spanCurrentPage <= 1 ? 'disabled' : '' ?>">
                            <?php if ($spanCurrentPage > 1): ?>
                                <a class="page-link" href="<?= span_e(span_page_url($spanCurrentPage - 1, $search, $routeFilter, $severityFilter, $sectorKm)) ?>">Previous</a>
                            <?php else: ?>
                                <span class="page-link">Previous</span>
                            <?php endif; ?>
                        </li>

                        <?php
                        $pageStart = max(1, $spanCurrentPage - 2);
                        $pageEnd = min($spanTotalPages, $spanCurrentPage + 2);
                        for ($p = $pageStart; $p <= $pageEnd; $p++):
                        ?>
                            <li class="page-item <?= $p === $spanCurrentPage ? 'active' : '' ?>">
                                <a class="page-link" href="<?= span_e(span_page_url($p, $search, $routeFilter, $severityFilter, $sectorKm)) ?>"><?= $p ?></a>
                            </li>
                        <?php endfor; ?>

                        <li class="page-item <?= $spanCurrentPage >= $spanTotalPages ? 'disabled' : '' ?>">
                            <?php if ($spanCurrentPage < $spanTotalPages): ?>
                                <a class="page-link" href="<?= span_e(span_page_url($spanCurrentPage + 1, $search, $routeFilter, $severityFilter, $sectorKm)) ?>">Next</a>
                            <?php else: ?>
                                <span class="page-link">Next</span>
                            <?php endif; ?>
                        </li>
                    </ul>
                </nav>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php require_once __DIR__ . '/_footer.php'; ?>
