<?php
// Buffer page output so POST redirects can set HTTP headers before output is sent.
if (!ob_get_level()) {
    ob_start();
}
require_once '_header.php';

$id = (int)($_GET['id'] ?? 0);
$pdo = db();

/*
 * Core detail:
 * - Keeps the existing core status/service/remark form.
 * - Shows OTDR events attached to each core_tests record.
 * - Does not change core status or continuity automatically.
 */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $status = (string)($_POST['status'] ?? 'FREE');
    $allowedStatuses = ['FREE', 'USED', 'FAULTY', 'RESERVED', 'CUT', 'DECOMMISSIONED'];
    if (!in_array($status, $allowedStatuses, true)) {
        $status = 'FREE';
    }

    $faultType = trim((string)($_POST['fault_type'] ?? ''));
    $allowedFaults = ['CUT', 'HIGH_LOSS', 'BEND', 'DAMAGED', 'UNKNOWN'];
    if ($faultType !== '' && !in_array($faultType, $allowedFaults, true)) {
        $faultType = '';
    }

    $st = $pdo->prepare(
        'UPDATE fiber_cores
         SET status = ?, fault_type = ?, service_name = ?, remark = ?
         WHERE id = ?'
    );
    $st->execute([
        $status,
        $faultType !== '' ? $faultType : null,
        trim((string)($_POST['service_name'] ?? '')),
        trim((string)($_POST['remark'] ?? '')),
        $id
    ]);

    // _header.php has already emitted page output; do not send a redirect here.
    // The UPDATE above is complete; continue rendering with fresh database values.
    $saveMessage = 'Perubahan core berjaya disimpan.';
}

$s = $pdo->prepare(
    'SELECT fc.*, r.route_name, r.id AS route_id, c.name AS cable_name
     FROM fiber_cores fc
     JOIN routes r ON r.id = fc.route_id
     JOIN cable_types c ON c.id = r.cable_type_id
     WHERE fc.id = ?
     LIMIT 1'
);
$s->execute([$id]);
$c = $s->fetch(PDO::FETCH_ASSOC);

if (!$c) {
    echo '<div class="alert alert-danger">Core tidak dijumpai. Sila kembali ke Route Detail.</div>';
    require_once '_footer.php';
    exit;
}

$testsStmt = $pdo->prepare(
    'SELECT ct.*, ts.test_date, ts.direction, ts.equipment
     FROM core_tests ct
     LEFT JOIN test_sessions ts ON ts.id = ct.session_id
     WHERE ct.core_id = ?
     ORDER BY ct.id DESC'
);
$testsStmt->execute([$id]);
$tests = $testsStmt->fetchAll(PDO::FETCH_ASSOC);

/* Load all events for each test. Schema confirmed: core_test_id, event_no,
   distance_km, loss_db, event_type, remark. Reflection/sum-loss may be in remark
   in this installation, so show the remark without fabricating separate values. */
$eventsStmt = $pdo->prepare(
    'SELECT id, core_test_id, event_no, distance_km, loss_db, event_type, remark
     FROM core_events
     WHERE core_test_id = ?
     ORDER BY event_no ASC, id ASC'
);
?>
<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h2><?= e($c['route_name']) ?> · Core <?= e($c['core_no']) ?></h2>
        <div class="text-muted small"><?= e($c['cable_name'] ?? '') ?></div>
    </div>
    <a href="route_detail.php?id=<?= (int)$c['route_id'] ?>" class="btn btn-secondary">Back</a>
</div>

<div class="row">
    <div class="col-lg-4 mb-3">
        <div class="card">
            <div class="card-header">Core Status</div>
            <form method="post">
                <div class="card-body">
                    <select name="status" class="form-control mb-2">
                        <?php foreach (['FREE','USED','FAULTY','RESERVED','CUT','DECOMMISSIONED'] as $x): ?>
                            <option value="<?= e($x) ?>" <?= (($c['status'] ?? '') === $x) ? 'selected' : '' ?>>
                                <?= e($x) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <select name="fault_type" class="form-control mb-2">
                        <option value="">No fault</option>
                        <?php foreach (['CUT','HIGH_LOSS','BEND','DAMAGED','UNKNOWN'] as $x): ?>
                            <option value="<?= e($x) ?>" <?= (($c['fault_type'] ?? '') === $x) ? 'selected' : '' ?>>
                                <?= e($x) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <input class="form-control mb-2" name="service_name"
                           value="<?= e($c['service_name'] ?? '') ?>" placeholder="Service">

                    <textarea class="form-control" name="remark" rows="3"
                              placeholder="Remark"><?= e($c['remark'] ?? '') ?></textarea>
                </div>
                <div class="card-footer">
                    <button class="btn btn-primary" type="submit">Save</button>
                </div>
            </form>
        </div>
    </div>

    <div class="col-lg-8 mb-3">
        <div class="card">
            <div class="card-header">Technical Test History</div>
            <div class="card-body table-responsive p-0">
                <table class="table table-sm table-striped table-bordered mb-0">
                    <thead>
                    <tr>
                        <th>Date</th>
                        <th>Length (km)</th>
                        <th>Total Loss (dB)</th>
                        <th>1310</th>
                        <th>1550</th>
                        <th>Direction / Source</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php if (!$tests): ?>
                        <tr><td colspan="6" class="text-muted text-center p-3">Tiada rekod ujian untuk core ini.</td></tr>
                    <?php else: ?>
                        <?php foreach ($tests as $t): ?>
                            <tr>
                                <td><?= e($t['test_date'] ?? $t['created_at'] ?? '—') ?></td>
                                <td><?= $t['fiber_length_km'] !== null ? e(number_format((float)$t['fiber_length_km'], 3, '.', '')) : '—' ?></td>
                                <td><?= $t['total_loss_db'] !== null ? e(number_format((float)$t['total_loss_db'], 3, '.', '')) : '—' ?></td>
                                <td><?= ($t['pm_1310_dbm'] !== null && $t['pm_1310_dbm'] !== '') ? e($t['pm_1310_dbm']) : '—' ?></td>
                                <td><?= ($t['pm_1550_dbm'] !== null && $t['pm_1550_dbm'] !== '') ? e($t['pm_1550_dbm']) : '—' ?></td>
                                <td><?= e($t['direction'] ?: ($t['equipment'] ?: '—')) ?></td>
                            </tr>
                            <?php
                            $eventsStmt->execute([(int)$t['id']]);
                            $events = $eventsStmt->fetchAll(PDO::FETCH_ASSOC);
                            ?>
                            <tr>
                                <td colspan="6" class="p-3">
                                    <div class="font-weight-bold mb-2">
                                        OTDR Events — Test #<?= (int)$t['id'] ?>
                                        <span class="text-muted font-weight-normal">(<?= count($events) ?> event)</span>
                                    </div>
                                    <?php if (!$events): ?>
                                        <div class="alert alert-warning mb-0 py-2">
                                            Tiada event direkodkan untuk ujian ini.
                                        </div>
                                    <?php else: ?>
                                        <div class="table-responsive">
                                            <table class="table table-sm table-bordered table-striped mb-0">
                                                <thead>
                                                <tr>
                                                    <th>Event</th>
                                                    <th>Distance (km)</th>
                                                    <th>Loss (dB)</th>
                                                    <th>Event Type</th>
                                                    <th>Remark / Reflection / Sum Loss</th>
                                                </tr>
                                                </thead>
                                                <tbody>
                                                <?php foreach ($events as $ev): ?>
                                                    <?php
                                                    $eventType = (string)($ev['event_type'] ?? 'UNKNOWN');
                                                    $isHighLoss = ($eventType === 'HIGH_LOSS');
                                                    ?>
                                                    <tr class="<?= $isHighLoss ? 'table-danger' : '' ?>">
                                                        <td><?= (int)$ev['event_no'] ?></td>
                                                        <td><?= $ev['distance_km'] !== null ? e(number_format((float)$ev['distance_km'], 3, '.', '')) : '—' ?></td>
                                                        <td><?= $ev['loss_db'] !== null ? e(number_format((float)$ev['loss_db'], 3, '.', '')) : '—' ?></td>
                                                        <td>
                                                            <?php if ($isHighLoss): ?>
                                                                <span class="badge badge-danger">HIGH_LOSS</span>
                                                            <?php else: ?>
                                                                <?= e($eventType) ?>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td><?= trim((string)($ev['remark'] ?? '')) !== '' ? e($ev['remark']) : '—' ?></td>
                                                    </tr>
                                                <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php require_once '_footer.php'; ?>
