<?php
declare(strict_types=1);
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/zone.php';
require_login();

$pdo = db();
$user = current_user() ?? [];
$isSuperAdmin = zone_is_superadmin();
$zoneId = (int)($user['zone_id'] ?? 0);
$routeId = max(0, (int)($_GET['route_id'] ?? 0));
$toleranceKm = 0.100; // Initial default 100 m; configurable in UI below.
$thresholdDb = 1.0;
$pageError = '';
$routes = [];
$selected = null;
$reverseRoute = null;
$forwardTests = [];
$reverseTests = [];
$analysis = [];
$sectorGroups = [];
$hasReverseData = false;

try {
    $q = $pdo->query("SELECT setting_value FROM settings WHERE setting_key='high_loss_threshold_db' LIMIT 1");
    $v = $q->fetchColumn();
    if ($v !== false && is_numeric($v)) $thresholdDb = (float)$v;
} catch (Throwable $ignored) {}

try {
    $sql = "SELECT r.id,r.route_name,r.from_node,r.to_node,r.distance_km,r.status,r.zone_id,
                   z.zone_name,c.name AS cable_name,c.core_count
            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
            WHERE (r.status='ACTIVE' OR r.status IS NULL)";
    $args = [];
    if (!$isSuperAdmin) {
        $sql .= " AND r.zone_id=?";
        $args[] = $zoneId;
    }
    $sql .= " ORDER BY r.route_name";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($args);
    $routes = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($routes as $r) if ((int)$r['id'] === $routeId) $selected = $r;
    if ($selected === null && $routes) {
        $selected = $routes[0];
        $routeId = (int)$selected['id'];
    }

    if ($selected) {
        $from = trim((string)($selected['from_node'] ?? ''));
        $to = trim((string)($selected['to_node'] ?? ''));
        // A reverse route is only paired when its endpoints are explicitly reversed.
        if ($from !== '' && $to !== '') {
            foreach ($routes as $r) {
                if ((int)$r['id'] !== $routeId
                    && strcasecmp(trim((string)($r['from_node'] ?? '')), $to) === 0
                    && strcasecmp(trim((string)($r['to_node'] ?? '')), $from) === 0) {
                    $reverseRoute = $r;
                    break;
                }
            }
        }

        // Load the newest test per core AFTER applying the direction filter.
        // This prevents a newer forward test from hiding an older reverse test.
        $loadTests = function(int $rid, ?string $directionNeedle = null, ?string $fallbackNeedle = null) use ($pdo): array {
            $sql = "SELECT ct.id AS test_id,ct.core_id,fc.core_no,fc.status AS core_status,fc.fault_type AS core_fault_type,ct.fiber_length_km,ct.total_loss_db,
                           ct.pm_1310_dbm,ct.pm_1550_dbm,ct.remark AS test_remark,
                           ts.id AS session_id,ts.test_date,ts.direction,ts.equipment,ts.session_remark
                    FROM core_tests ct
                    JOIN fiber_cores fc ON fc.id=ct.core_id
                    JOIN test_sessions ts ON ts.id=ct.session_id
                    WHERE ts.route_id=? ORDER BY ts.test_date DESC, ts.id DESC, ct.id DESC";
            $st = $pdo->prepare($sql);
            $st->execute([$rid]);
            $rows = $st->fetchAll(PDO::FETCH_ASSOC);
            $selectLatest = static function(array $source, ?string $needle): array {
                $filtered = [];
                // Direction must be explicit. Never treat an unlabelled or opposite-direction
                // session as a valid forward/reverse test.
                if ($needle !== null && trim($needle) !== '') {
                    $expected = preg_split('/\s*(?:→|->|[-–—]|\bto\b)\s*/iu', trim($needle));
                    $normaliseNode = static function(string $value): string {
                        return strtolower(trim((string)preg_replace('/\s+/u', ' ', $value)));
                    };
                    $expectedFrom = $normaliseNode((string)($expected[0] ?? ''));
                    $expectedTo = $normaliseNode((string)($expected[1] ?? ''));
                    if ($expectedFrom !== '' && $expectedTo !== '') {
                        $filtered = array_values(array_filter($source, static function($row) use ($expectedFrom, $expectedTo, $normaliseNode): bool {
                            $direction = trim((string)($row['direction'] ?? ''));
                            if ($direction === '') return false;
                            $parts = preg_split('/\s*(?:→|->|[-–—]|\bto\b)\s*/iu', $direction);
                            if (count($parts) < 2) return false;
                            return $normaliseNode((string)$parts[0]) === $expectedFrom
                                && $normaliseNode((string)$parts[1]) === $expectedTo;
                        }));
                    }
                }
                $byCore = [];
                foreach ($filtered as $row) {
                    $no = (int)$row['core_no'];
                    if (isset($byCore[$no])) continue;
                    $byCore[$no] = $row;
                }
                return $byCore;
            };
            $picked = $directionNeedle !== null ? $selectLatest($rows, $directionNeedle) : [];
            if (!$picked && $fallbackNeedle !== null) $picked = $selectLatest($rows, $fallbackNeedle);
            foreach ($picked as &$row) {
                $ev = $pdo->prepare("SELECT id,event_no,distance_km,loss_db,event_type,status,joint_name,remark
                                     FROM core_events WHERE core_test_id=? ORDER BY event_no,id");
                $ev->execute([(int)$row['test_id']]);
                $row['events'] = $ev->fetchAll(PDO::FETCH_ASSOC);
            }
            unset($row);
            return $picked;
        };

        $forwardNeedle = $from !== '' && $to !== '' ? $from . ' → ' . $to : null;
        $reverseNeedle = $from !== '' && $to !== '' ? $to . ' → ' . $from : null;
        if ($reverseRoute) {
            $forwardTests = $loadTests($routeId, $forwardNeedle);
            // Never fall back to unfiltered tests: that can put the same direction on both SLDs.
            // A paired route is not enough by itself to prove reverse OTDR data exists.
            // Require the saved test session direction to match the reverse route's direction.
            $reverseFrom = trim((string)($reverseRoute['from_node'] ?? ''));
            $reverseTo = trim((string)($reverseRoute['to_node'] ?? ''));
            $reverseRouteNeedle = $reverseFrom !== '' && $reverseTo !== '' ? $reverseFrom . ' → ' . $reverseTo : $reverseNeedle;
            $reverseTests = $loadTests((int)$reverseRoute['id'], $reverseRouteNeedle);
            // Some deployments store both directions under the selected route ID.
            // If the paired route has no reverse-direction session, try only the explicit
            // reverse direction on the selected route; never load arbitrary latest tests.
            if (!$reverseTests && $reverseNeedle !== null) {
                $reverseTests = $loadTests($routeId, $reverseNeedle);
            }
            $hasReverseData = !empty($reverseTests);
        } else {
            $forwardTests = $loadTests($routeId, $forwardNeedle);
            $reverseTests = $loadTests($routeId, $reverseNeedle);
            $hasReverseData = !empty($reverseTests);
        }

        $actualDistance = (float)($selected['distance_km'] ?? 0);
        $hasExplicitReverseEventPoints = false;
        $coreStmt = $pdo->prepare('SELECT core_no FROM fiber_cores WHERE route_id=? ORDER BY core_no');
        $coreStmt->execute([$routeId]);
        $allCoreNos = array_map('intval', $coreStmt->fetchAll(PDO::FETCH_COLUMN));
        $coreNos = array_unique(array_merge($allCoreNos, array_keys($forwardTests), array_keys($reverseTests)));
        sort($coreNos, SORT_NUMERIC);
        foreach ($coreNos as $coreNo) {
            $f = $forwardTests[$coreNo] ?? null;
            $r = $reverseTests[$coreNo] ?? null;
            $fEvents = [];
            $rEvents = [];
            foreach (($f['events'] ?? []) as $e) {
                $type = strtoupper((string)($e['event_type'] ?? ''));
                $status = strtoupper((string)($e['status'] ?? ''));
                $loss = is_numeric($e['loss_db'] ?? null) ? (float)$e['loss_db'] : null;
                $bad = in_array($type, ['BREAK_CUT','CUT','BREAK','HIGH_LOSS'], true) || $status === 'HIGH_LOSS' || ($loss !== null && $loss >= $thresholdDb);
                if ($bad && is_numeric($e['distance_km'] ?? null)) $fEvents[] = $e;
            }
            foreach (($r['events'] ?? []) as $e) {
                $type = strtoupper((string)($e['event_type'] ?? ''));
                $status = strtoupper((string)($e['status'] ?? ''));
                $loss = is_numeric($e['loss_db'] ?? null) ? (float)$e['loss_db'] : null;
                $bad = in_array($type, ['BREAK_CUT','CUT','BREAK','HIGH_LOSS'], true) || $status === 'HIGH_LOSS' || ($loss !== null && $loss >= $thresholdDb);
                if ($bad && is_numeric($e['distance_km'] ?? null)) {
                    $rEvents[] = $e;
                    if (eventMatchClass($e) !== 'UNKNOWN') $hasExplicitReverseEventPoints = true;
                }
            }
            // Fallback for the user's current data-entry pattern:
            // when a core is marked FAULTY/CUT but no CUT event point was saved,
            // use the measured fiber length as a *candidate* fault distance.
            // This is explicitly marked inferred; it is not treated as a confirmed event.
            $makeLengthCandidate = static function(?array $test, float $routeKm): ?array {
                if (!$test || !is_numeric($test['fiber_length_km'] ?? null)) return null;
                $coreStatus = strtoupper(trim((string)($test['core_status'] ?? '')));
                $faultType = strtoupper(trim((string)($test['core_fault_type'] ?? '')));
                $remark = strtoupper((string)($test['test_remark'] ?? ''));
                $sessionRemark = strtoupper((string)($test['session_remark'] ?? ''));
                $explicitFault = in_array($coreStatus, ['FAULTY'], true)
                    || in_array($faultType, ['CUT','HIGH_LOSS','DAMAGED','BEND'], true)
                    || preg_match('/\\b(CUT|BREAK|PUTUS|HIGH.?LOSS)\\b/', $remark . ' ' . $sessionRemark);
                $distance = (float)$test['fiber_length_km'];
                if (!$explicitFault || $routeKm <= 0 || $distance <= 0 || $distance >= $routeKm) return null;
                return [
                    'id'=>null,'event_no'=>0,'distance_km'=>$distance,'loss_db'=>null,
                    'event_type'=>'INFERRED_FAULT_FROM_TEST_LENGTH','status'=>'UNKNOWN',
                    'joint_name'=>null,
                    'remark'=>'Inferred candidate from FAULTY core / fault type and fiber length; confirm explicit event point in OTDR form.'
                ];
            };
            if (!$fEvents) {
                $candidate = $makeLengthCandidate($f, $actualDistance);
                if ($candidate) $fEvents[] = $candidate;
            }
            if (!$rEvents) {
                $candidate = $makeLengthCandidate($r, $actualDistance);
                if ($candidate) $rEvents[] = $candidate;
            }

            $matches = [];
            foreach ($fEvents as $fe) foreach ($rEvents as $re) {
                // Only explicit saved event points of the same fault class can match.
                // Inferred F.Length candidates are not proof of a reverse/forward match.
                $fClass = eventMatchClass($fe);
                $rClass = eventMatchClass($re);
                if ($fClass === 'UNKNOWN' || $rClass === 'UNKNOWN' || $fClass !== $rClass) continue;
                if (!is_numeric($fe['distance_km'] ?? null) || !is_numeric($re['distance_km'] ?? null)) continue;
                $fd = (float)$fe['distance_km'];
                $rd = (float)$re['distance_km'];
                // Reverse reading is measured from Node B, so convert it to Node A reference.
                $normalizedReverse = $actualDistance - $rd;
                $delta = abs($fd - $normalizedReverse);
                if ($actualDistance > 0 && $fd >= 0 && $rd >= 0 && $fd <= $actualDistance && $rd <= $actualDistance && $delta <= $toleranceKm) {
                    $matches[] = ['f'=>$fe,'r'=>$re,'fd'=>$fd,'rd'=>$rd,'norm'=>$normalizedReverse,'delta'=>$delta,'class'=>$fClass];
                }
            }
            // Keep nearest candidate matches first. Match is per core and same event class.
            usort($matches, static fn($a,$b) => $a['delta'] <=> $b['delta']);
            $analysis[] = ['core_no'=>(int)$coreNo,'forward'=>$f,'reverse'=>$r,'forward_events'=>$fEvents,'reverse_events'=>$rEvents,'matches'=>$matches];
        }

        // Build repair-location groups from all candidates for review.
        // Only matched points are rendered on the SLD; unmatched points remain in the review table.
        // Reverse distances are normalized to the selected route's Node A reference.
        $sectorGroups = [];
        foreach ($analysis as $coreAnalysis) {
            $coreNo = (int)$coreAnalysis['core_no'];
            $candidatePoints = [];
            foreach ($coreAnalysis['forward_events'] as $event) {
                $candidatePoints[] = ['location_a'=>(float)$event['distance_km'],'distance_original'=>(float)$event['distance_km'],'direction'=>'FORWARD','event'=>$event,'matched'=>false,'delta'=>null];
            }
            foreach ($coreAnalysis['reverse_events'] as $event) {
                $reverseDistance = (float)$event['distance_km'];
                $candidatePoints[] = ['location_a'=>$actualDistance-$reverseDistance,'distance_original'=>$reverseDistance,'direction'=>'REVERSE','event'=>$event,'matched'=>false,'delta'=>null];
            }
            foreach ($candidatePoints as &$point) {
                // Mark only the exact saved event point that participated in a valid match.
                foreach ($coreAnalysis['matches'] as $match) {
                    $matchedEvent = $point['direction'] === 'FORWARD' ? $match['f'] : $match['r'];
                    $pointEvent = $point['event'];
                    $matchedId = $matchedEvent['id'] ?? null;
                    $pointId = $pointEvent['id'] ?? null;
                    $sameEvent = ($matchedId !== null && $pointId !== null && (string)$matchedId === (string)$pointId)
                        || ($matchedId === null && $pointId === null
                            && eventMatchClass($matchedEvent) !== 'UNKNOWN'
                            && eventMatchClass($pointEvent) === eventMatchClass($matchedEvent)
                            && abs((float)$matchedEvent['distance_km'] - (float)$pointEvent['distance_km']) < 0.0005);
                    if ($sameEvent) {
                        $point['matched'] = true;
                        $point['delta'] = (float)$match['delta'];
                        break;
                    }
                }
            }
            unset($point);
            foreach ($candidatePoints as $point) {
                $location = (float)$point['location_a'];
                if ($location < 0 || $location > $actualDistance) continue;
                $groupIndex = null;
                foreach ($sectorGroups as $idx => $group) {
                    if (abs((float)$group['location_a'] - $location) <= $toleranceKm) { $groupIndex = $idx; break; }
                }
                if ($groupIndex === null) {
                    $sectorGroups[] = ['location_a'=>$location,'events'=>[],'cores'=>[],'matched_cores'=>[],'directions'=>[],'event_types'=>[],'max_delta'=>null,'review'=>true];
                    $groupIndex = array_key_last($sectorGroups);
                }
                $sectorGroups[$groupIndex]['events'][] = ['core_no'=>$coreNo,'event'=>$point['event'],'direction'=>$point['direction'],'distance_original'=>$point['distance_original'],'matched'=>$point['matched'],'delta'=>$point['delta']];
                $sectorGroups[$groupIndex]['cores'][$coreNo] = true;
                $sectorGroups[$groupIndex]['directions'][$point['direction']] = true;
                $sectorGroups[$groupIndex]['event_types'][eventLabel($point['event'])] = true;
                if ($point['matched']) {
                    $sectorGroups[$groupIndex]['matched_cores'][$coreNo] = true;
                    $sectorGroups[$groupIndex]['review'] = false;
                    if ($point['delta'] !== null) $sectorGroups[$groupIndex]['max_delta'] = max((float)($sectorGroups[$groupIndex]['max_delta'] ?? 0), (float)$point['delta']);
                }
            }
        }
        // Deduplicate event rows and sort locations by exact distance (3 decimal precision retained).
        foreach ($sectorGroups as &$group) {
            $unique = [];
            foreach ($group['events'] as $ev) {
                $key = $ev['core_no'].'|'.$ev['direction'].'|'.number_format((float)$ev['distance_original'],3,'.','').'|'.eventLabel($ev['event']);
                $unique[$key] = $ev;
            }
            $group['events'] = array_values($unique);
        }
        unset($group);
        usort($sectorGroups, static fn($a,$b) => $a['location_a'] <=> $b['location_a']);
        // A reverse SLD requires actual saved reverse event points; route pairing or F.Length inference alone is insufficient.
        $hasReverseData = $hasReverseData && $hasExplicitReverseEventPoints;
    }
} catch (Throwable $e) {
    $pageError = 'Unable to load analysis data. Please check the existing database structure and PHP error log.';
}

function h($value): string { return e((string)($value ?? '')); }
function km($value): string { return is_numeric($value) ? number_format((float)$value, 3) . ' km' : '—'; }
function eventMatchClass(array $e): string {
    $type = strtoupper(trim((string)($e['event_type'] ?? '')));
    $status = strtoupper(trim((string)($e['status'] ?? '')));
    if (in_array($type, ['BREAK_CUT','CUT','BREAK'], true)) return 'CUT';
    if ($type === 'HIGH_LOSS' || $status === 'HIGH_LOSS') return 'HIGH_LOSS';
    // Inferred candidates are for review only; they cannot establish a two-way match.
    return 'UNKNOWN';
}
function eventLabel(array $e): string {
    $type = strtoupper((string)($e['event_type'] ?? 'UNKNOWN'));
    if ($type === 'BREAK_CUT') return 'CUT / BREAK';
    if ($type === 'INFERRED_FAULT_FROM_TEST_LENGTH') return 'INFERRED FAULT (TEST LENGTH)';
    if ($type === 'HIGH_LOSS' || strtoupper((string)($e['status'] ?? '')) === 'HIGH_LOSS') return 'HIGH LOSS';
    return $type;
}
// Paginate only the per-core OTDR comparison table; calculations above still use every core.
$comparisonPerPage = 5;
$comparisonTotal = count($analysis);
$comparisonPages = max(1, (int)ceil($comparisonTotal / $comparisonPerPage));
$comparisonPage = max(1, min($comparisonPages, (int)($_GET['page'] ?? 1)));
$comparisonOffset = ($comparisonPage - 1) * $comparisonPerPage;
$comparisonRows = array_slice($analysis, $comparisonOffset, $comparisonPerPage);
$eventCoreCount = 0; $matchedCoreSet = []; $unmatchedEventCount = 0;
foreach ($analysis as $row) { if (!empty($row['forward_events']) || !empty($row['reverse_events'])) $eventCoreCount++; if (!empty($row['matches'])) $matchedCoreSet[(int)$row['core_no']] = true; if ((empty($row['matches'])) && (!empty($row['forward_events']) || !empty($row['reverse_events']))) $unmatchedEventCount++; }
$matchedCoreCount = count($matchedCoreSet);
$selectedRepairIndex = max(0, (int)($_GET['repair-location'] ?? 0));
if ($selectedRepairIndex > count($sectorGroups)) $selectedRepairIndex = 0;
$pageTitle = 'Bi-Directional OTDR Analysis';
$currentPage = 'bi_directional_otdr.php';

require_once __DIR__ . '/_header.php';

if (($_GET['view'] ?? '') === 'detail') {
    $detailIndex = max(1, (int)($_GET['repair-location'] ?? 1));
    $actualDetail = (float)($selected['distance_km'] ?? 0);
    $detailGroup = $sectorGroups[$detailIndex - 1] ?? null;
    ?>
    <style>
      .repair-detail-wrap{max-width:1500px;margin:0 auto;padding:18px}
      .rd-hero{background:linear-gradient(120deg,#123b63,#1768a5);color:#fff;border-radius:14px;padding:22px;margin-bottom:18px}
      .rd-card{background:#fff;border:1px solid #dbe3ec;border-radius:12px;padding:18px;margin-bottom:16px;box-shadow:0 3px 12px rgba(15,23,42,.05)}
      .rd-kpi{background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;padding:14px;height:100%}
      .rd-kpi strong{display:block;font-size:27px;line-height:1.2;color:#123b63}
      .rd-table th{background:#eff5fb;white-space:nowrap}
      .rd-table td,.rd-table th{vertical-align:middle!important}
      .rd-chip{display:inline-block;background:#fee2e2;color:#991b1b;border-radius:7px;padding:6px 9px;margin:3px;font-weight:700}
      .rd-status{display:inline-block;padding:4px 8px;border-radius:20px;font-size:11px;font-weight:700}
      .rd-match{background:#dcfce7;color:#166534}.rd-review{background:#fef3c7;color:#92400e}
      .rd-muted{color:#64748b;font-size:12px}
    </style>
    <div class="repair-detail-wrap">
      <div class="rd-hero">
        <div class="d-flex flex-wrap justify-content-between align-items-center">
          <div><h2 class="mb-1"><i class="fas fa-tools mr-2"></i>Repair Location Details</h2>
          <div>Bi-Directional OTDR · <?=h($selected['route_name'] ?? 'Selected route')?></div></div>
          <a class="btn btn-light mt-2" href="bi_directional_otdr.php?route_id=<?=$routeId?>"><i class="fas fa-arrow-left mr-1"></i> Back to Analysis</a>
        </div>
      </div>
      <?php if (!$selected || !$detailGroup): ?>
        <div class="alert alert-warning">Repair location tidak ditemui. Kembali ke analysis dan pilih lokasi yang sah.</div>
      <?php else:
        $detailCores = array_keys($detailGroup['cores']); sort($detailCores, SORT_NUMERIC);
        $detailLoc = (float)$detailGroup['location_a']; $detailLocB = max(0, $actualDetail - $detailLoc);
        $detailTypes = implode(' / ', array_keys($detailGroup['event_types']));
        $detailRows = array_values(array_filter($detailGroup['events'], static fn($ev) => in_array((int)$ev['core_no'], array_map('intval',$detailCores), true)));
      ?>
      <div class="rd-card">
        <div class="d-flex flex-wrap justify-content-between align-items-start">
          <div><div class="rd-muted">ROUTE</div><h3 class="mb-1"><?=h($selected['route_name'])?></h3>
          <div><?=h($selected['from_node'])?> <i class="fas fa-long-arrow-alt-right mx-1"></i> <?=h($selected['to_node'])?> · <?=h($selected['cable_name'] ?? 'Cable type unknown')?></div></div>
          <span class="rd-status <?=$detailGroup['review']?'rd-review':'rd-match'?>"><?=$detailGroup['review']?'NEEDS REVIEW':'MATCHED EVIDENCE'?></span>
        </div>
        <hr>
        <div class="row">
          <div class="col-md-3 mb-2"><div class="rd-kpi"><span class="rd-muted">Actual Distance</span><strong><?=number_format($actualDetail,3)?> km</strong></div></div>
          <div class="col-md-3 mb-2"><div class="rd-kpi"><span class="rd-muted">Affected Cores</span><strong><?=count($detailCores)?></strong></div></div>
          <div class="col-md-3 mb-2"><div class="rd-kpi"><span class="rd-muted">Matched Cores</span><strong><?=count($detailGroup['matched_cores'])?></strong></div></div>
          <div class="col-md-3 mb-2"><div class="rd-kpi"><span class="rd-muted">Candidate Events</span><strong><?=count($detailRows)?></strong></div></div>
        </div>
      </div>
      <div class="rd-card">
        <h4><i class="fas fa-map-marker-alt text-danger mr-2"></i>Candidate Fault Location</h4>
        <div class="row align-items-center">
          <div class="col-md-5"><div class="rd-kpi"><span class="rd-muted">Distance from Node A · <?=h($selected['from_node'])?></span><strong><?=number_format($detailLoc,3)?> km</strong></div></div>
          <div class="col-md-2 text-center py-3"><i class="fas fa-exchange-alt fa-2x text-primary"></i></div>
          <div class="col-md-5"><div class="rd-kpi"><span class="rd-muted">Distance from Node B · <?=h($selected['to_node'])?></span><strong><?=number_format($detailLocB,3)?> km</strong></div></div>
        </div>
        <p class="mt-3 mb-1"><strong>Event type:</strong> <?=h($detailTypes ?: 'Unknown')?></p>
        <div class="rd-muted">Location ini ialah calon berdasarkan rekod OTDR yang tersedia. Sahkan lokasi fizikal sebelum kerja repair/splicing.</div>
      </div>
      <div class="rd-card">
        <div class="d-flex justify-content-between flex-wrap align-items-center">
          <h4><i class="fas fa-layer-group text-primary mr-2"></i>Core Terlibat</h4>
          <span class="rd-status rd-review"><?=count($detailCores)?> CORE</span>
        </div>
        <div class="mb-3"><?php foreach($detailCores as $cn): ?><span class="rd-chip">Core <?= (int)$cn ?></span><?php endforeach; ?></div>
        <div class="table-responsive"><table class="table table-bordered table-hover rd-table">
          <thead><tr><th>Core</th><th>Direction</th><th>Event Distance</th><th>Event Type</th><th>Match Status</th><th>Distance Difference</th></tr></thead><tbody>
          <?php if (!$detailRows): ?><tr><td colspan="6" class="text-muted">Tiada event detail untuk lokasi ini.</td></tr>
          <?php else: foreach($detailRows as $ev): ?>
            <tr><td><strong>Core <?= (int)$ev['core_no'] ?></strong></td><td><?=$ev['direction']==='FORWARD'?'Node A → Node B':'Node B → Node A'?></td><td><?=number_format((float)$ev['distance_original'],3)?> km</td><td><?=h(eventLabel($ev['event']))?></td><td><span class="rd-status <?=$ev['matched']?'rd-match':'rd-review'?>"><?=$ev['matched']?'MATCH':'REVIEW'?></span></td><td><?=$ev['delta']===null?'—':number_format((float)$ev['delta']*1000,0).' m'?></td></tr>
          <?php endforeach; endif; ?>
          </tbody></table></div>
        <div class="alert alert-info mb-0"><strong>Technician next step:</strong> sahkan joint/closure/kabel di lokasi ini, lakukan repair atau replace selepas punca disahkan, kemudian uji OTDR dan continuity semula. Status THROUGH hanya selepas continuity disahkan.</div>
      </div>
      <?php endif; ?>
    </div>
    <?php require_once __DIR__ . '/_footer.php'; exit;
}

?>
<style>
.bidir-wrap{color:#172b4d}.bidir-hero{background:linear-gradient(120deg,#102b46,#1769aa);color:#fff;border-radius:12px;padding:18px 20px;margin-bottom:14px}.bidir-panel{background:#fff;border:1px solid #dce5ef;border-radius:10px;padding:14px;margin-bottom:14px;box-shadow:0 2px 8px rgba(23,43,77,.04)}.bidir-muted{color:#64748b}.bidir-stat{border:1px solid #dce5ef;border-radius:9px;padding:12px;height:100%;background:#fff}.bidir-stat strong{display:block;font-size:25px;line-height:1.15}.bidir-stat small{color:#64748b}.bidir-stat.red{background:#fff1f2;border-color:#fecdd3}.bidir-stat.amber{background:#fffbeb;border-color:#fde68a}.bidir-stat.green{background:#ecfdf5;border-color:#a7f3d0}.bidir-sld{padding:20px 20px 12px;overflow:hidden}.bidir-line{height:5px;background:#64748b;border-radius:5px;position:relative;margin:44px 22px 35px}.bidir-node{position:absolute;top:-27px;background:#1769aa;color:#fff;border-radius:8px;padding:6px 9px;font-weight:700;white-space:nowrap;font-size:12px}.bidir-node.left{left:0;transform:translateX(-12%)}.bidir-node.right{right:0;transform:translateX(12%)}.bidir-point{position:absolute;top:-8px;width:19px;height:19px;border-radius:50%;background:#dc2626;border:3px solid #fff;box-shadow:0 0 0 2px #dc2626;transform:translateX(-50%);cursor:pointer}.bidir-point.high{background:#f59e0b;box-shadow:0 0 0 2px #f59e0b}.bidir-point-label{position:absolute;top:-32px;transform:translateX(-50%);font-size:11px;font-weight:700;color:#b91c1c;white-space:nowrap;background:#fff1f2;border:1px solid #fecdd3;border-radius:5px;padding:2px 4px;z-index:3}.bidir-tick{position:absolute;top:8px;height:12px;border-left:1px solid #94a3b8}.bidir-tick-label{position:absolute;top:22px;transform:translateX(-50%);font-size:10px;color:#475569;white-space:nowrap}.bidir-point-link{display:block;position:absolute;top:-8px;width:19px;height:19px;transform:translateX(-50%);z-index:4}.bidir-table th{background:#f1f5f9}.bidir-table td,.bidir-table th{vertical-align:middle!important}.bidir-pill{display:inline-block;padding:3px 8px;border-radius:20px;font-size:11px;font-weight:700}.bidir-red{background:#fee2e2;color:#b91c1c}.bidir-green{background:#dcfce7;color:#166534}.bidir-amber{background:#fef3c7;color:#92400e}.bidir-empty{padding:16px;background:#fff7ed;border:1px solid #fed7aa;border-radius:8px;color:#9a3412}.bidir-core-chip{display:inline-block;padding:5px 9px;border-radius:6px;background:#fee2e2;color:#b91c1c;font-weight:700;font-size:12px;margin:2px}.bidir-group-row{cursor:pointer}.bidir-group-row:hover{background:#f8fbff}.bidir-detail{background:#f8fbff;border:1px solid #dbeafe;border-radius:8px;padding:12px;margin-top:10px}.bidir-location-no{display:inline-flex;width:28px;height:28px;border-radius:50%;align-items:center;justify-content:center;background:#dc2626;color:#fff;font-weight:700}.bidir-location-no.high{background:#d97706}@media(max-width:767px){.bidir-panel{padding:11px}.bidir-sld{padding-left:4px;padding-right:4px}.bidir-point-label{font-size:9px}.bidir-stat strong{font-size:21px}}

.bidir-sld-track{padding:135px 18px 30px;overflow:visible}
.bidir-line-dual{height:5px;background:var(--sld-color);border-radius:5px;position:relative;margin:26px 4px 28px}
.bidir-line-dual .bidir-tick{top:5px;height:11px}
.bidir-line-dual .bidir-tick-label{top:17px}
.bidir-line-dual .bidir-point{top:calc(-8px - (var(--marker-lane,0) * 5px));z-index:5;width:15px;height:15px}
.bidir-line-dual .bidir-point-label{position:absolute;top:var(--label-top,-31px);left:var(--label-left,50%);transform:translateX(var(--label-shift,-50%));max-width:min(220px,42vw);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:10px;line-height:1.25;padding:3px 6px;border-radius:5px;z-index:6;pointer-events:none;box-shadow:0 1px 3px rgba(15,23,42,.08)}
.bidir-line-dual .bidir-point-label:after{content:"";position:absolute;bottom:-5px;left:var(--label-pointer,50%);border-width:5px 5px 0;border-style:solid;border-color:currentColor transparent transparent}
@media(max-width:767px){.bidir-line-dual .bidir-point-label{font-size:9px;max-width:135px}.bidir-sld-track{padding-left:4px;padding-right:4px}}
</style>
<div class="bidir-wrap">
<div class="bidir-hero"><div class="d-flex flex-wrap justify-content-between align-items-center"><div><h2 class="mb-1"><i class="fas fa-wave-square mr-2"></i>Bi-Directional OTDR Analysis</h2><div>Collect all cores · Match exact event distances · Group repair locations</div></div><span class="badge badge-light p-2 mt-2">READ-ONLY ANALYSIS</span></div></div>
<?php if ($pageError !== ''): ?><div class="alert alert-danger"><?=h($pageError)?></div><?php endif; ?>
<div class="bidir-panel"><form method="get" class="form-row align-items-end"><div class="form-group col-lg-5 col-md-12 mb-2"><label for="route_id">Select Route</label><select class="form-control" id="route_id" name="route_id" required><option value="">Choose route…</option><?php foreach($routes as $r): ?><option value="<?= (int)$r['id']?>" <?=((int)$r['id']===$routeId?'selected':'')?>><?=h($r['route_name'])?> — <?=h($r['from_node'])?> → <?=h($r['to_node'])?> (<?=h(km($r['distance_km']))?>)</option><?php endforeach; ?></select></div><div class="form-group col-md-2 mb-2"><label>Node A</label><input class="form-control" value="<?=h($selected['from_node']??'—')?>" readonly></div><div class="form-group col-md-2 mb-2"><label>Node B</label><input class="form-control" value="<?=h($selected['to_node']??'—')?>" readonly></div><div class="form-group col-md-2 mb-2"><label>Actual Distance</label><input class="form-control" value="<?=h(km($selected['distance_km']??null))?>" readonly></div><div class="form-group col-md-1 mb-2"><button class="btn btn-primary btn-block" type="submit" title="Analyse"><i class="fas fa-search"></i></button></div></form><small class="text-muted">Event distance dikekalkan kepada 3 tempat perpuluhan. Toleransi padanan semasa: <?=number_format($toleranceKm*1000,0)?> m. Analisis baca-sahaja; tiada status core atau schema database diubah.</small></div>
<?php if ($selected): $actual=(float)($selected['distance_km']??0); $allCoreCount=count($analysis); $repairLocationCount=count($sectorGroups); $coreNoEvent=max(0,$allCoreCount-$eventCoreCount); ?>

<div class="bidir-panel">
 <div class="d-flex justify-content-between align-items-center flex-wrap">
  <h4 class="mb-1"><i class="fas fa-project-diagram mr-2 text-primary"></i>Route SLD — <?=h($selected['route_name'])?></h4>
  <span class="text-muted small"><?=h($selected['cable_name']??'Cable type unknown')?> · <?=h($selected['zone_name']??'Zone')?></span>
 </div>
 <div class="small text-muted mb-2">Klik marker atau “View cores” untuk menyemak core yang terlibat. Label dijarakkan supaya lokasi yang rapat tidak bertindih.</div>
 <?php
   $sldTickStep = $actual <= 12 ? 1 : ($actual <= 60 ? 5 : 10);
   $sldRenderLine = static function(string $direction, bool $reverse) use ($sectorGroups,$actual,$sldTickStep,$routeId,$selected): void {
     $leftNode = $reverse ? (string)$selected['to_node'] : (string)$selected['from_node'];
     $rightNode = $reverse ? (string)$selected['from_node'] : (string)$selected['to_node'];
     $color = $reverse ? '#198754' : '#1769aa';
     echo '<div class="bidir-direction-title" style="color:'.$color.';font-weight:700;margin-top:12px">'.($reverse?'← ':'→ ').h($direction).'</div>';
     echo '<div class="d-flex justify-content-between small font-weight-bold mt-1"><span>'.h($leftNode).' · 0.000 km</span><span>'.h($rightNode).' · '.h(km($actual)).'</span></div>';
     echo '<div class="bidir-sld-track" style="--sld-color:'.$color.'"><div class="bidir-line-dual">';
     if ($actual > 0) {
       for ($tick=$sldTickStep; $tick<$actual; $tick+=$sldTickStep) {
         $tickPct=($tick/$actual)*100;
         echo '<span class="bidir-tick" style="left:'.$tickPct.'%"></span><span class="bidir-tick-label" style="left:'.$tickPct.'%">'.number_format($tick,0).' km</span>';
       }
       // Place labels in separate lanes when events are close together. Keep edge labels inside the SLD panel.
       $lanePositions = [];
       foreach ($sectorGroups as $idx=>$sg) {
         // IMPORTANT: each SLD line may show only events recorded in that direction.
         // The groups are shared for repair-location analysis, so filter before rendering.
         $lineDirection = $reverse ? 'REVERSE' : 'FORWARD';
         $directionEvents = array_values(array_filter(
           $sg['events'],
           static fn($item) => ($item['direction'] ?? '') === $lineDirection && !empty($item['matched'])
         ));
         if (!$directionEvents) continue;

         $physicalA=(float)$sg['location_a'];
         $distanceFromStart=$reverse ? max(0,$actual-$physicalA) : $physicalA;
         $pct=max(0.5,min(99.5,($distanceFromStart/$actual)*100));
         $types=[];
         foreach ($directionEvents as $directionEvent) {
           $types[eventLabel($directionEvent['event'])] = true;
         }
         $primaryType=implode(' / ',array_keys($types));
         $isHigh=stripos($primaryType,'HIGH LOSS')!==false && stripos($primaryType,'CUT')===false;
         // Compare with every prior label in a lane, not just the most recent one.
         $lane=0;
         while (true) {
           $collision=false;
           foreach (($lanePositions[$lane] ?? []) as $priorPct) {
             if (abs($pct-$priorPct) < 12) { $collision=true; break; }
           }
           if (!$collision) break;
           $lane++;
         }
         $lanePositions[$lane][]=$pct;
         if ($pct < 9) { $labelLeft='0%'; $labelShift='0'; $pointer='8px'; }
         elseif ($pct > 91) { $labelLeft='100%'; $labelShift='-100%'; $pointer='calc(100% - 8px)'; }
         else { $labelLeft='50%'; $labelShift='-50%'; $pointer='50%'; }
         $labelText=($isHigh?'HIGH LOSS':'CUT / BREAK').' · '.number_format($distanceFromStart,3).' km';
         $repairHref='?route_id='.(int)$routeId.'&view=detail&repair-location='.($idx+1);
         $inline='left:'.$pct.'%;--label-top:'.(-34-($lane*25)).'px;--label-left:'.$labelLeft.';--label-shift:'.$labelShift.';--label-pointer:'.$pointer.';--marker-lane:'.min($lane,2);
         echo '<a href="'.h($repairHref).'" class="bidir-point '.($isHigh?'high':'').'" style="'.h($inline).'" target="_blank" rel="noopener noreferrer" title="Location '.($idx+1).' · '.h($labelText).' · '.count($sg['cores']).' core(s)" aria-label="Open repair location '.($idx+1).'"><span class="bidir-point-label">'.h($labelText).'</span></a>';
       }
     }
     echo '</div></div>';
   };
   $sldRenderLine((string)$selected['from_node'].' → '.(string)$selected['to_node'].' (Node A → Node B)',false);
   // Only display the reverse SLD when at least one CUT/HIGH_LOSS event is
   // positively matched between forward and reverse readings on the same core.
   // Reverse test sessions alone are not enough to confirm a repair location.
   $hasMatchedBidirectionalEvents = $matchedCoreCount > 0;
   if ($hasReverseData && $hasMatchedBidirectionalEvents) {
     $sldRenderLine((string)$selected['to_node'].' → '.(string)$selected['from_node'].' (Node B → Node A)',true);
   } else {
     echo '<div class="alert alert-warning mt-3 mb-0">SLD Node B → Node A belum dipaparkan kerana belum ada event CUT/HIGH_LOSS yang berjaya dipadankan antara dua arah pada core yang sama. SLD reverse akan muncul selepas kedua-dua bacaan sepadan dalam toleransi 100 m.</div>';
   }
 ?>
 <div class="d-flex justify-content-center flex-wrap small text-muted mt-4" style="gap:8px"><span>↔ Actual route length: <strong><?=h(km($actual))?></strong></span><span class="bidir-pill bidir-red">● CUT / BREAK</span><span class="bidir-pill bidir-amber">● HIGH LOSS</span></div>
</div>
<div class="row"><div class="col-xl-7"><div class="bidir-panel"><div class="d-flex justify-content-between align-items-center flex-wrap"><h4 class="mb-2"><i class="fas fa-map-marker-alt mr-2 text-danger"></i>Repair Locations (<?=count($sectorGroups)?>)</h4><input class="form-control form-control-sm mb-2" style="max-width:220px" id="locationSearch" placeholder="Search distance / core…" oninput="filterRepairLocations()"></div><?php if(!$sectorGroups): ?><div class="bidir-empty">Belum ada event CUT/HIGH_LOSS atau calon lokasi daripada F.Length yang boleh dipaparkan. Semak sama ada event point disimpan untuk setiap core dan arah ujian.</div><?php else: ?><div class="table-responsive"><table class="table table-sm table-bordered bidir-table mb-0" id="repairLocationsTable"><thead><tr><th>No.</th><th>Distance from <?=h($selected['from_node'])?></th><th>Distance from <?=h($selected['to_node'])?></th><th>Event</th><th>Cores</th><th>Direction evidence</th><th>Action</th></tr></thead><tbody><?php foreach($sectorGroups as $idx=>$group): $groupCores=array_keys($group['cores']); sort($groupCores,SORT_NUMERIC); $groupTypes=implode(' / ',array_keys($group['event_types'])); $groupLoc=(float)$group['location_a']; $groupLocB=max(0,$actual-$groupLoc); $groupMatched=count($group['matched_cores']); $isHigh=stripos($groupTypes,'HIGH LOSS')!==false && stripos($groupTypes,'CUT')===false; ?><tr class="bidir-group-row" id="repair-location-<?=$idx+1?>" data-search="<?=h(strtolower(number_format($groupLoc,3).' '.number_format($groupLocB,3).' '.implode(' ',$groupCores).' '.$groupTypes))?>"><td><span class="bidir-location-no <?=$isHigh?'high':''?>"><?=$idx+1?></span></td><td><strong><?=number_format($groupLoc,3)?> km</strong></td><td><strong><?=number_format($groupLocB,3)?> km</strong></td><td><span class="bidir-pill <?=$isHigh?'bidir-amber':'bidir-red'?>"><?=h($groupTypes)?></span><?php if($group['review']): ?><br><small class="text-warning">Unmatched / review</small><?php endif; ?></td><td><strong><?=count($groupCores)?></strong><br><small><?=h(implode(', ',$groupCores))?></small></td><td><?=count($group['directions'])===2?'A→B + B→A':'One direction only'?> · <?= $groupMatched?> matched core(s)</td><td><a class="btn btn-sm btn-primary" href="?route_id=<?=$routeId?>&amp;view=detail&amp;repair-location=<?=$idx+1?>" target="_blank" rel="noopener noreferrer" title="Open affected core details in a new tab">View cores <i class="fas fa-external-link-alt"></i></a></td></tr><?php endforeach; ?></tbody></table></div><div class="small text-muted mt-2">Jumlah core dalam setiap lokasi dikira daripada semua event calon. Kumpulan berlabel review belum mempunyai padanan dua arah yang cukup; jangan anggap lokasi itu disahkan untuk repair.</div><?php endif; ?></div>
<div class="bidir-panel"><h4><i class="fas fa-check-circle text-success mr-2"></i>Cores Without Major Event (<?=number_format($coreNoEvent)?>)</h4><div class="d-flex flex-wrap" style="gap:6px"><?php $noEventCores=[]; foreach($analysis as $ar) if(empty($ar['forward_events'])&&empty($ar['reverse_events'])) $noEventCores[]=(int)$ar['core_no']; if(!$noEventCores): ?><span class="text-muted">Tiada core dalam kategori ini.</span><?php else: foreach($noEventCores as $n): ?><span class="bidir-pill bidir-green">Core <?=$n?></span><?php endforeach; endif; ?></div></div></div>
<div class="col-xl-5"><div class="bidir-panel" id="selected-repair-location"><h4><i class="fas fa-list-check text-primary mr-2"></i>Selected Repair Location</h4><div id="locationDetails"><?php if($selectedRepairIndex>0 && isset($sectorGroups[$selectedRepairIndex-1])): $detailGroup=$sectorGroups[$selectedRepairIndex-1]; $detailCores=array_keys($detailGroup['cores']); sort($detailCores,SORT_NUMERIC); $detailLoc=(float)$detailGroup['location_a']; ?><h5>Location <?=$selectedRepairIndex?> — <?=number_format($detailLoc,3)?> km from <?=h($selected['from_node'])?></h5><p class="mb-2"><strong><?=number_format(max(0,$actual-$detailLoc),3)?> km from <?=h($selected['to_node'])?></strong> · <?=count($detailCores)?> affected candidate core(s) · <?=$detailGroup['review']?'Needs review':'Matched evidence exists'?></p><div class="mb-2"><?php foreach($detailCores as $cn): ?><span class="bidir-core-chip">Core <?= (int)$cn ?></span><?php endforeach; ?></div><div class="table-responsive"><table class="table table-sm table-bordered bidir-table"><thead><tr><th>Core</th><th>Direction</th><th>Event distance</th><th>Event</th><th>Match</th></tr></thead><tbody><?php foreach($detailGroup['events'] as $ev): ?><tr><td><?= (int)$ev['core_no']?></td><td><?=$ev['direction']==='FORWARD'?'A → B':'B → A'?></td><td><?=number_format((float)$ev['distance_original'],3)?> km</td><td><?=h(eventLabel($ev['event']))?></td><td><?=$ev['matched']?'<span class="bidir-pill bidir-green">MATCH</span>':'<span class="bidir-pill bidir-amber">REVIEW</span>'?></td></tr><?php endforeach; ?></tbody></table></div><p class="small text-muted mb-0">Jumlah core dikira unik. Event satu arah sahaja kekal REVIEW sehingga bacaan lawan arah disahkan.</p><?php else: ?><div class="bidir-empty">Klik “View cores” pada mana-mana lokasi untuk memaparkan semua core dan bacaan dua arah.</div><?php endif; ?></div><div class="small text-muted mt-2">Nota: database semasa menyimpan event point, bukan sampel trace OTDR mentah. Oleh itu halaman ini tidak mereka graf trace; paparan jarak dan event menggunakan data yang tersimpan sahaja.</div></div><div class="bidir-panel"><h4><i class="fas fa-chart-bar text-primary mr-2"></i>Analysis Summary</h4><div class="bidir-event-row">Actual distance <strong class="float-right"><?=h(km($actual))?></strong></div><div class="bidir-event-row">Forward test cores <strong class="float-right"><?=count($forwardTests)?></strong></div><div class="bidir-event-row">Reverse test cores <strong class="float-right"><?=count($reverseTests)?></strong></div><div class="bidir-event-row">Matched core count <strong class="float-right"><?=$matchedCoreCount?></strong></div><div class="bidir-event-row">Unmatched event cores <strong class="float-right"><?=$unmatchedEventCount?></strong></div><?php if(!$hasReverseData): ?><div class="alert alert-warning mt-3 mb-0">Reverse test belum dijumpai. Lokasi sehala dipaparkan sebagai calon review sahaja.</div><?php elseif($matchedCoreCount): ?><div class="alert alert-success mt-3 mb-0">Ada core dengan event yang sepadan dua arah. Sahkan lokasi fizikal di lapangan sebelum kerja pembaikan.</div><?php else: ?><div class="alert alert-info mt-3 mb-0">Belum ada padanan dua arah dalam toleransi semasa.</div><?php endif; ?></div><div class="bidir-panel"><h4 class="text-danger"><i class="fas fa-tools mr-2"></i>Technician Action</h4><ol class="mb-0 pl-3"><li>Pilih lokasi dan semak nombor core terlibat.</li><li>Sahkan joint / closure / kabel di lokasi itu.</li><li>Repair atau replace selepas punca disahkan.</li><li>Uji OTDR dan continuity semula.</li><li>THROUGH hanya selepas continuity disahkan.</li></ol></div></div></div>
<div class="bidir-panel"><h4><i class="fas fa-list-alt mr-2"></i>OTDR Event Comparison — 5 cores per page</h4><?php if(!$analysis): ?><div class="bidir-empty">Tiada core untuk dipaparkan.</div><?php else: ?><div class="table-responsive"><table class="table table-sm table-bordered bidir-table mb-0"><thead><tr><th>Core</th><th>Forward test</th><th>Reverse test</th><th>Event candidates / matches</th></tr></thead><tbody><?php foreach($comparisonRows as $a): $f=$a['forward'];$r=$a['reverse']; ?><tr><td><strong><?= (int)$a['core_no']?></strong></td><td><?=$f?h($f['test_date']).'<br><small>'.h($f['direction']?:'Direction not recorded').'</small>':'<span class="text-muted">No data</span>'?></td><td><?=$r?h($r['test_date']).'<br><small>'.h($r['direction']?:'Direction not recorded').'</small>':'<span class="text-muted">No reverse data</span>'?></td><td><?php if($a['matches']): ?><span class="bidir-pill bidir-green"><?=count($a['matches'])?> MATCH</span><?php endif; ?><?php if($a['forward_events']): ?><div>Forward: <?php foreach($a['forward_events'] as $ev): ?><?=h(eventLabel($ev))?> @ <?=h(km($ev['distance_km']))?>; <?php endforeach; ?></div><?php endif; ?><?php if($a['reverse_events']): ?><div>Reverse: <?php foreach($a['reverse_events'] as $ev): ?><?=h(eventLabel($ev))?> @ <?=h(km($ev['distance_km']))?>; <?php endforeach; ?></div><?php endif; ?><?php if(empty($a['forward_events'])&&empty($a['reverse_events'])): ?><span class="text-muted">No saved CUT/HIGH_LOSS event</span><?php endif; ?></td></tr><?php endforeach; ?></tbody></table></div><?php if($comparisonPages>1): ?><div class="d-flex justify-content-between align-items-center mt-3"><small class="text-muted">Paparan <?=($comparisonOffset+1)?>–<?=min($comparisonOffset+$comparisonPerPage,$comparisonTotal)?> daripada <?=$comparisonTotal?> core</small><nav><ul class="pagination pagination-sm mb-0"><li class="page-item <?=$comparisonPage<=1?'disabled':''?>"><a class="page-link" href="?route_id=<?=$routeId?>&amp;page=<?=max(1,$comparisonPage-1)?>">Previous</a></li><?php for($pg=max(1,$comparisonPage-2);$pg<=min($comparisonPages,$comparisonPage+2);$pg++): ?><li class="page-item <?=$pg===$comparisonPage?'active':''?>"><a class="page-link" href="?route_id=<?=$routeId?>&amp;page=<?=$pg?>"><?=$pg?></a></li><?php endfor; ?><li class="page-item <?=$comparisonPage>=$comparisonPages?'disabled':''?>"><a class="page-link" href="?route_id=<?=$routeId?>&amp;page=<?=min($comparisonPages,$comparisonPage+1)?>">Next</a></li></ul></nav></div><?php endif; ?><?php endif; ?></div>
<script>
const repairLocationData = <?=json_encode(array_map(function($g,$i) use($actual){$cores=array_keys($g['cores']);sort($cores,SORT_NUMERIC);$rows=[];foreach($g['events'] as $ev){$rows[]=['core'=>(int)$ev['core_no'],'direction'=>$ev['direction'],'distance'=>round((float)$ev['distance_original'],3),'event'=>eventLabel($ev['event']),'matched'=>(bool)$ev['matched'],'delta'=>$ev['delta']===null?null:round((float)$ev['delta']*1000)];}return ['number'=>$i+1,'locationA'=>round((float)$g['location_a'],3),'locationB'=>round(max(0,$actual-(float)$g['location_a']),3),'types'=>array_keys($g['event_types']),'cores'=>$cores,'matchedCores'=>array_map('intval',array_keys($g['matched_cores'])),'review'=>(bool)$g['review'],'rows'=>$rows];},$sectorGroups,array_keys($sectorGroups)),JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>;
function showLocationDetails(number){const g=repairLocationData.find(x=>x.number===number);if(!g)return;let chips=g.cores.map(c=>`<span class="bidir-core-chip">Core ${c}</span>`).join('');let rows=g.rows.map(r=>`<tr><td>${r.core}</td><td>${r.direction==='FORWARD'?'A → B':'B → A'}</td><td>${r.distance.toFixed(3)} km</td><td>${r.event}</td><td>${r.matched?'<span class="bidir-pill bidir-green">MATCH</span>':'<span class="bidir-pill bidir-amber">REVIEW</span>'}</td></tr>`).join('');document.getElementById('locationDetails').innerHTML=`<h5>Location ${g.number} — ${g.locationA.toFixed(3)} km from Node A</h5><p class="mb-2"><strong>${g.locationB.toFixed(3)} km from Node B</strong> · ${g.cores.length} affected candidate core(s) · ${g.review?'Needs review':'Matched evidence exists'}</p><div class="mb-2">${chips}</div><div class="table-responsive"><table class="table table-sm table-bordered bidir-table"><thead><tr><th>Core</th><th>Direction</th><th>Event distance</th><th>Event</th><th>Match</th></tr></thead><tbody>${rows}</tbody></table></div><p class="small text-muted mb-0">Jumlah core dikira unik bagi lokasi ini. Event dari satu arah sahaja kekal REVIEW sehingga bacaan lawan arah disahkan.</p>`;document.getElementById('locationDetails').scrollIntoView({behavior:'smooth',block:'nearest'});}
function filterRepairLocations(){const q=(document.getElementById('locationSearch').value||'').toLowerCase();document.querySelectorAll('#repairLocationsTable tbody tr').forEach(tr=>{tr.style.display=(tr.dataset.search||'').includes(q)?'':'none';});}
document.querySelectorAll('.bidir-point').forEach((el,i)=>el.addEventListener('click',()=>showLocationDetails(i+1)));
</script>
<?php else: ?><div class="alert alert-info">No active routes are available for your account / Zone.</div><?php endif; ?>
</div>
<?php require_once __DIR__ . '/_footer.php'; ?>
