<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| FIBRECORE - ROUTES
|--------------------------------------------------------------------------
| - Add Route
| - Auto create fiber cores
| - Search
| - Pagination 10/page
| - Delete route: SUPERADMIN sahaja
| - Delete semua core + OTDR records berkaitan
|--------------------------------------------------------------------------
*/


/*
|--------------------------------------------------------------------------
| CONFIG
|--------------------------------------------------------------------------
*/

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

require_login();

$pdo = db();

$u = current_user();

$userRole = strtoupper(trim((string)($u['role'] ?? '')));
$isSuperAdmin = ($userRole === 'SUPERADMIN');
$isAdmin = ($userRole === 'ADMIN');

$zoneId = current_user_zone_id();

/*
|--------------------------------------------------------------------------
| VIEW ALL ROUTES PERMISSION
|--------------------------------------------------------------------------
| Read permission from DB on each request so changes in User Management
| take effect immediately. This permission is view-only.
*/
$canViewAllRoutes = false;
$currentUserId = (int)($u['id'] ?? $u['user_id'] ?? 0);
if (!$isSuperAdmin && $currentUserId > 0) {
    try {
        $permStmt = $pdo->prepare("
            SELECT can_view_all_routes
            FROM users
            WHERE id = ?
            LIMIT 1
        ");
        $permStmt->execute([$currentUserId]);
        $canViewAllRoutes = ((int)$permStmt->fetchColumn() === 1);
    } catch (Throwable $e) {
        // Fail closed if the migration is missing or the permission lookup fails.
        $canViewAllRoutes = false;
    }
}

$zones = $pdo->query("
    SELECT id, zone_name, zone_code
    FROM zones
    WHERE is_active = 1
    ORDER BY id ASC
")->fetchAll();


/*
|--------------------------------------------------------------------------
| HELPER
|--------------------------------------------------------------------------
*/

function route_redirect(): void
{
    header('Location: routes.php');
    exit;
}


/*
|--------------------------------------------------------------------------
| SESSION MESSAGES
|--------------------------------------------------------------------------
*/

$routeError =
    $_SESSION['route_error']
    ?? '';

$routeSuccess =
    $_SESSION['route_success']
    ?? '';

unset($_SESSION['route_error']);
unset($_SESSION['route_success']);


/*
|--------------------------------------------------------------------------
| UPDATE ROUTE ZONE
|--------------------------------------------------------------------------
| SUPERADMIN SAHAJA
|--------------------------------------------------------------------------
*/

if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    &&
    ($_POST['action'] ?? '') === 'update_route_zone'
) {

    if (!$isSuperAdmin) {
        $_SESSION['route_error'] =
            'Access denied. Hanya SUPERADMIN boleh assign Zone.';
        route_redirect();
    }

    $routeId = (int)($_POST['route_id'] ?? 0);
    $newZoneId = trim((string)($_POST['zone_id'] ?? ''));

    if ($routeId <= 0) {
        $_SESSION['route_error'] = 'Route ID tidak sah.';
        route_redirect();
    }

    try {
        if ($newZoneId === '') {
            $stmt = $pdo->prepare("
                UPDATE routes
                SET zone_id = NULL
                WHERE id = ?
            ");
            $stmt->execute([$routeId]);
        } else {
            $newZoneId = (int)$newZoneId;

            $checkZone = $pdo->prepare("
                SELECT id
                FROM zones
                WHERE id = ?
                  AND is_active = 1
                LIMIT 1
            ");
            $checkZone->execute([$newZoneId]);

            if (!$checkZone->fetchColumn()) {
                throw new RuntimeException('Zone tidak sah.');
            }

            $stmt = $pdo->prepare("
                UPDATE routes
                SET zone_id = ?
                WHERE id = ?
            ");
            $stmt->execute([$newZoneId, $routeId]);
        }

        $_SESSION['route_success'] =
            'Zone route berjaya dikemaskini.';

    } catch (Throwable $e) {
        $_SESSION['route_error'] =
            'Failed to update route Zone: ' . $e->getMessage();
    }

    route_redirect();
}



/*
|--------------------------------------------------------------------------
| UPDATE ROUTE DETAILS (SUPERADMIN ONLY)
|--------------------------------------------------------------------------
*/
if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && ($_POST['action'] ?? '') === 'update_route_details'
) {
    if (!$isSuperAdmin) {
        $_SESSION['route_error'] = 'Access denied. Hanya SUPERADMIN boleh edit route.';
        route_redirect();
    }

    $routeId = (int)($_POST['route_id'] ?? 0);
    $from = strtoupper(trim((string)($_POST['from_node'] ?? '')));
    $to = strtoupper(trim((string)($_POST['to_node'] ?? '')));
    $junction = strtoupper(trim((string)($_POST['junction_code'] ?? '')));
    $routeName = strtoupper(trim((string)($_POST['route_name'] ?? '')));
    $cableId = (int)($_POST['cable_type_id'] ?? 0);
    $distanceRaw = trim((string)($_POST['distance_km'] ?? ''));
    $civil = strtoupper(trim((string)($_POST['civil_type'] ?? '')));
    $zoneRaw = trim((string)($_POST['zone_id'] ?? ''));

    if ($routeId <= 0 || $from === '' || $to === '' || $cableId <= 0) {
        $_SESSION['route_error'] = 'Sila lengkapkan Node A, Node B dan Cable Type.';
        route_redirect();
    }
    if (!preg_match('/^[A-Z0-9]+$/', $from) || !preg_match('/^[A-Z0-9]+$/', $to)) {
        $_SESSION['route_error'] = 'Nama node hanya boleh mengandungi huruf dan nombor.';
        route_redirect();
    }
    if (!in_array($junction, ['A','B','C'], true)) {
        $_SESSION['route_error'] = 'Sila pilih junction A, B atau C.';
        route_redirect();
    }
    $expectedName = $from . '-' . $to . '_J_' . $junction;
    // Use the standardized name as the single source of truth.
    $routeName = $expectedName;
    $distance = null;
    if ($distanceRaw !== '') {
        if (!is_numeric($distanceRaw) || (float)$distanceRaw < 0) {
            $_SESSION['route_error'] = 'Actual Distance mesti nombor positif.';
            route_redirect();
        }
        $distance = number_format((float)$distanceRaw, 3, '.', '');
    }
    $zoneNew = ($zoneRaw === '') ? null : (int)$zoneRaw;

    try {
        $current = $pdo->prepare("SELECT id, cable_type_id, zone_id FROM routes WHERE id = ? LIMIT 1");
        $current->execute([$routeId]);
        $currentRoute = $current->fetch(PDO::FETCH_ASSOC);
        if (!$currentRoute) {
            throw new RuntimeException('Route tidak dijumpai.');
        }

        $cable = $pdo->prepare("SELECT id, core_count FROM cable_types WHERE id = ? AND status = 'ACTIVE' LIMIT 1");
        $cable->execute([$cableId]);
        $newCable = $cable->fetch(PDO::FETCH_ASSOC);
        if (!$newCable) {
            throw new RuntimeException('Cable Type tidak aktif atau tidak sah.');
        }

        // Prevent changing cable capacity when it would invalidate existing core records.
        $coreCountStmt = $pdo->prepare("SELECT COUNT(*) FROM fiber_cores WHERE route_id = ?");
        $coreCountStmt->execute([$routeId]);
        $existingCoreCount = (int)$coreCountStmt->fetchColumn();
        if ($cableId !== (int)$currentRoute['cable_type_id'] && $existingCoreCount !== (int)$newCable['core_count']) {
            throw new RuntimeException('Cable Type tidak boleh ditukar kerana bilangan core tidak sepadan dengan rekod core sedia ada.');
        }

        if ($zoneNew !== null) {
            $zoneCheck = $pdo->prepare("SELECT id FROM zones WHERE id = ? AND is_active = 1 LIMIT 1");
            $zoneCheck->execute([$zoneNew]);
            if (!$zoneCheck->fetchColumn()) {
                throw new RuntimeException('Zone tidak sah atau tidak aktif.');
            }
        }

        $duplicate = $pdo->prepare("SELECT id FROM routes WHERE route_name = ? AND id <> ? LIMIT 1");
        $duplicate->execute([$routeName, $routeId]);
        if ($duplicate->fetchColumn()) {
            throw new RuntimeException('Nama route ' . $routeName . ' sudah digunakan.');
        }

        $update = $pdo->prepare("
            UPDATE routes
            SET route_name = ?, from_node = ?, to_node = ?, cable_type_id = ?,
                distance_km = ?, civil_type = ?, zone_id = ?
            WHERE id = ?
            LIMIT 1
        ");
        $update->execute([$routeName, $from, $to, $cableId, $distance, $civil, $zoneNew, $routeId]);

        $_SESSION['route_success'] = 'Route ' . $routeName . ' berjaya dikemaskini. Rekod core dan OTDR dikekalkan.';
    } catch (Throwable $e) {
        $_SESSION['route_error'] = 'Gagal mengemaskini route: ' . $e->getMessage();
    }
    route_redirect();
}

/*
|--------------------------------------------------------------------------
| UPDATE ROUTE NAME
|--------------------------------------------------------------------------
| SUPERADMIN SAHAJA
|--------------------------------------------------------------------------
*/

if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    &&
    ($_POST['action'] ?? '') === 'update_route_name'
) {

    if (!$isSuperAdmin) {
        $_SESSION['route_error'] =
            'Access denied. Hanya SUPERADMIN boleh edit Route Name.';
        route_redirect();
    }

    $routeId = (int)($_POST['route_id'] ?? 0);
    $newRouteName = trim((string)($_POST['route_name'] ?? ''));

    if ($routeId <= 0) {
        $_SESSION['route_error'] = 'Route ID tidak sah.';
        route_redirect();
    }

    if ($newRouteName === '') {
        $_SESSION['route_error'] = 'Route Name diperlukan.';
        route_redirect();
    }

    try {
        $check = $pdo->prepare("
            SELECT id
            FROM routes
            WHERE route_name = ?
              AND id <> ?
            LIMIT 1
        ");
        $check->execute([
            $newRouteName,
            $routeId
        ]);

        if ($check->fetchColumn()) {
            throw new RuntimeException(
                'Route "' . $newRouteName . '" sudah wujud.'
            );
        }

        $stmt = $pdo->prepare("
            UPDATE routes
            SET route_name = ?
            WHERE id = ?
            LIMIT 1
        ");
        $stmt->execute([
            $newRouteName,
            $routeId
        ]);

        if ($stmt->rowCount() <= 0) {
            $exists = $pdo->prepare("SELECT id FROM routes WHERE id = ? LIMIT 1");
            $exists->execute([$routeId]);
            if (!$exists->fetchColumn()) {
                throw new RuntimeException('Route tidak dijumpai.');
            }
        }

        $_SESSION['route_success'] =
            'Route Name berjaya dikemaskini kepada "'
            . $newRouteName
            . '".';

    } catch (Throwable $e) {
        $_SESSION['route_error'] =
            'Failed to update Route Name: '
            . $e->getMessage();
    }

    route_redirect();
}


/*
|--------------------------------------------------------------------------
| DELETE ROUTE
|--------------------------------------------------------------------------
| SUPERADMIN SAHAJA
|--------------------------------------------------------------------------
*/

if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    &&
    ($_POST['action'] ?? '') === 'delete_route'
) {

    /*
    |--------------------------------------------------------------------------
    | SECURITY CHECK
    |--------------------------------------------------------------------------
    */

    if (!$isSuperAdmin) {

        $_SESSION['route_error'] =
            'Access denied. Hanya SUPERADMIN boleh delete route.';

        route_redirect();
    }


    /*
    |--------------------------------------------------------------------------
    | ROUTE ID
    |--------------------------------------------------------------------------
    */

    $routeId =
        (int)(
            $_POST['route_id']
            ?? 0
        );


    if ($routeId <= 0) {

        $_SESSION['route_error'] =
            'Route ID tidak sah.';

        route_redirect();
    }


    try {

        $pdo->beginTransaction();


        /*
        |--------------------------------------------------------------------------
        | CHECK ROUTE
        |--------------------------------------------------------------------------
        */

        $check =
            $pdo->prepare("
                SELECT
                    id,
                    route_name
                FROM routes
                WHERE id = ?
                LIMIT 1
            ");

        $check->execute([
            $routeId
        ]);

        $route =
            $check->fetch();


        if (!$route) {

            throw new RuntimeException(
                'Route tidak dijumpai.'
            );
        }


        /*
        |--------------------------------------------------------------------------
        | GET CORE IDS
        |--------------------------------------------------------------------------
        */

        $coreStmt =
            $pdo->prepare("
                SELECT id
                FROM fiber_cores
                WHERE route_id = ?
            ");

        $coreStmt->execute([
            $routeId
        ]);

        $coreIds =
            $coreStmt->fetchAll(
                PDO::FETCH_COLUMN
            );


        /*
        |--------------------------------------------------------------------------
        | GET TEST IDS
        |--------------------------------------------------------------------------
        */

        $testIds = [];


        if (!empty($coreIds)) {

            $placeholders =
                implode(
                    ',',
                    array_fill(
                        0,
                        count($coreIds),
                        '?'
                    )
                );


            $testStmt =
                $pdo->prepare("
                    SELECT id
                    FROM core_tests
                    WHERE core_id IN ($placeholders)
                ");

            $testStmt->execute(
                $coreIds
            );

            $testIds =
                $testStmt->fetchAll(
                    PDO::FETCH_COLUMN
                );
        }


        /*
        |--------------------------------------------------------------------------
        | DELETE CORE EVENTS
        |--------------------------------------------------------------------------
        */

        if (!empty($testIds)) {

            $placeholders =
                implode(
                    ',',
                    array_fill(
                        0,
                        count($testIds),
                        '?'
                    )
                );


            $deleteEvents =
                $pdo->prepare("
                    DELETE FROM core_events
                    WHERE core_test_id IN ($placeholders)
                ");

            $deleteEvents->execute(
                $testIds
            );
        }


        /*
        |--------------------------------------------------------------------------
        | DELETE CORE TESTS
        |--------------------------------------------------------------------------
        */

        if (!empty($testIds)) {

            $placeholders =
                implode(
                    ',',
                    array_fill(
                        0,
                        count($testIds),
                        '?'
                    )
                );


            $deleteTests =
                $pdo->prepare("
                    DELETE FROM core_tests
                    WHERE id IN ($placeholders)
                ");

            $deleteTests->execute(
                $testIds
            );
        }


        /*
        |--------------------------------------------------------------------------
        | DELETE TEST SESSIONS
        |--------------------------------------------------------------------------
        */

        $deleteSessions =
            $pdo->prepare("
                DELETE FROM test_sessions
                WHERE route_id = ?
            ");

        $deleteSessions->execute([
            $routeId
        ]);


        /*
        |--------------------------------------------------------------------------
        | DELETE ATTACHMENTS
        |--------------------------------------------------------------------------
        |
        | Cuba delete berdasarkan core_id.
        | Kalau table/column tidak ada, teruskan.
        |--------------------------------------------------------------------------
        */

        if (!empty($coreIds)) {

            try {

                $placeholders =
                    implode(
                        ',',
                        array_fill(
                            0,
                            count($coreIds),
                            '?'
                        )
                    );


                $deleteAttachments =
                    $pdo->prepare("
                        DELETE FROM attachments
                        WHERE core_id IN ($placeholders)
                    ");

                $deleteAttachments->execute(
                    $coreIds
                );

            } catch (Throwable $attachmentError) {

                /*
                | Abaikan jika attachments tidak mempunyai
                | column core_id.
                */

            }
        }


        /*
        |--------------------------------------------------------------------------
        | DELETE FIBER CORES
        |--------------------------------------------------------------------------
        */

        $deleteCores =
            $pdo->prepare("
                DELETE FROM fiber_cores
                WHERE route_id = ?
            ");

        $deleteCores->execute([
            $routeId
        ]);


        /*
        |--------------------------------------------------------------------------
        | DELETE ROUTE
        |--------------------------------------------------------------------------
        */

        $deleteRoute =
            $pdo->prepare("
                DELETE FROM routes
                WHERE id = ?
            ");

        $deleteRoute->execute([
            $routeId
        ]);


        /*
        |--------------------------------------------------------------------------
        | CHECK
        |--------------------------------------------------------------------------
        */

        if ($deleteRoute->rowCount() <= 0) {

            throw new RuntimeException(
                'Route gagal dipadam.'
            );
        }


        /*
        |--------------------------------------------------------------------------
        | COMMIT
        |--------------------------------------------------------------------------
        */

        $pdo->commit();


        $_SESSION['route_success'] =
            'Route "'
            . $route['route_name']
            . '" berjaya dipadam.';


    } catch (Throwable $e) {

        if ($pdo->inTransaction()) {

            $pdo->rollBack();
        }


        $_SESSION['route_error'] =
            'Failed to delete route: '
            . $e->getMessage();
    }


    /*
    |--------------------------------------------------------------------------
    | REDIRECT
    |--------------------------------------------------------------------------
    */

    route_redirect();
}


/*
|--------------------------------------------------------------------------
| ADD ROUTE
|--------------------------------------------------------------------------
*/

if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    &&
    ($_POST['action'] ?? '') === 'add_route'
) {
    /*
    |--------------------------------------------------------------------------
    | ROLE ACCESS
    |--------------------------------------------------------------------------
    | SUPERADMIN: boleh create route untuk Zone pilihan.
    | ADMIN: hanya boleh create route dalam Zone akaun sendiri.
    | USER / role lain: tidak dibenarkan create route.
    |--------------------------------------------------------------------------
    */
    $userRole = strtoupper(trim((string)($u['role'] ?? '')));

    if (!in_array($userRole, ['SUPERADMIN', 'ADMIN'], true)) {
        $_SESSION['route_error'] =
            'Access denied. Akaun USER tidak dibenarkan create route.';
        route_redirect();
    }

    /*
    |--------------------------------------------------------------------------
    | RESOLVE ZONE SERVER-SIDE
    |--------------------------------------------------------------------------
    */
    if ($isSuperAdmin) {
        $newRouteZoneId = (int)($_POST['zone_id'] ?? 0);

        if ($newRouteZoneId <= 0) {
            $_SESSION['route_error'] =
                'Sila pilih Zone untuk route baharu.';
            route_redirect();
        }
    } else {
        // ADMIN tidak boleh memilih atau memalsukan Zone melalui POST.
        $newRouteZoneId = (int)($zoneId ?? 0);

        if ($newRouteZoneId <= 0) {
            $_SESSION['route_error'] =
                'Zone akaun ADMIN belum ditetapkan. Hubungi SUPERADMIN.';
            route_redirect();
        }
    }

    $validZone = $pdo->prepare("
        SELECT id
        FROM zones
        WHERE id = ?
          AND is_active = 1
        LIMIT 1
    ");
    $validZone->execute([$newRouteZoneId]);

    if (!$validZone->fetchColumn()) {
        $_SESSION['route_error'] =
            'Zone tidak sah atau tidak aktif.';
        route_redirect();
    }

    /*
    |--------------------------------------------------------------------------
    | INPUT
    |--------------------------------------------------------------------------
    */
    $from = strtoupper(trim((string)($_POST['from_node'] ?? '')));
    $to = strtoupper(trim((string)($_POST['to_node'] ?? '')));
    $junction = strtoupper(trim((string)($_POST['junction_code'] ?? 'A')));
    $name = '';
    if ($from !== '' && $to !== '' && in_array($junction, ['A', 'B', 'C'], true)) {
        $name = $from . '-' . $to . '_J_' . $junction;
    }
    $cid = (int)($_POST['cable_type_id'] ?? 0);

    $dist = (($_POST['distance_km'] ?? '') !== '')
        ? $_POST['distance_km']
        : null;

    $civil = trim((string)($_POST['civil_type'] ?? ''));

    /*
    |--------------------------------------------------------------------------
    | VALIDATION
    |--------------------------------------------------------------------------
    */
    if ($from === '' || $to === '' || !preg_match('/^[A-Z0-9]+$/', $from) || !preg_match('/^[A-Z0-9]+$/', $to)) {
        $_SESSION['route_error'] = 'Sila masukkan Node A dan Node B menggunakan huruf/nombor sahaja.';
        route_redirect();
    }
    if (!in_array($junction, ['A', 'B', 'C'], true) || $from === $to) {
        $_SESSION['route_error'] = 'Junction mesti A/B/C dan Node A tidak boleh sama dengan Node B.';
        route_redirect();
    }

    if ($cid <= 0) {
        $_SESSION['route_error'] = 'Cable type diperlukan.';
        route_redirect();
    }

    try {
        $pdo->beginTransaction();

        /*
        |--------------------------------------------------------------------------
        | CHECK DUPLICATE ROUTE
        |--------------------------------------------------------------------------
        */
        $duplicate = $pdo->prepare("
            SELECT id
            FROM routes
            WHERE route_name = ?
            LIMIT 1
        ");
        $duplicate->execute([$name]);

        if ($duplicate->fetch()) {
            throw new RuntimeException(
                'Route "' . $name . '" sudah wujud.'
            );
        }

        /*
        |--------------------------------------------------------------------------
        | INSERT ROUTE WITH VERIFIED ZONE
        |--------------------------------------------------------------------------
        */
        $insertRoute = $pdo->prepare("
            INSERT INTO routes
            (
                route_name,
                from_node,
                to_node,
                cable_type_id,
                distance_km,
                civil_type,
                zone_id
            )
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");

        $insertRoute->execute([
            $name,
            $from,
            $to,
            $cid,
            $dist,
            $civil,
            $newRouteZoneId
        ]);

        $routeId = (int)$pdo->lastInsertId();

        /*
        |--------------------------------------------------------------------------
        | GET CORE COUNT
        |--------------------------------------------------------------------------
        */
        $cc = $pdo->prepare("
            SELECT core_count
            FROM cable_types
            WHERE id = ?
              AND status = 'ACTIVE'
            LIMIT 1
        ");
        $cc->execute([$cid]);

        $coreCount = (int)$cc->fetchColumn();

        if ($coreCount <= 0) {
            throw new RuntimeException(
                'Cable type tidak aktif atau tidak mempunyai core count.'
            );
        }

        /*
        |--------------------------------------------------------------------------
        | CREATE FIBER CORES
        |--------------------------------------------------------------------------
        */
        $insertCore = $pdo->prepare("
            INSERT INTO fiber_cores (route_id, core_no)
            VALUES (?, ?)
        ");

        for ($i = 1; $i <= $coreCount; $i++) {
            $insertCore->execute([$routeId, $i]);
        }

        $pdo->commit();

        $_SESSION['route_success'] =
            'Route "' . $name . '" berjaya ditambah dalam Zone '
            . (string)$newRouteZoneId
            . ' dengan ' . $coreCount . ' cores.';

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        $_SESSION['route_error'] =
            'Failed to add route: ' . $e->getMessage();
    }

    route_redirect();
}

/*
|--------------------------------------------------------------------------
| SEARCH
|--------------------------------------------------------------------------
*/

$search =
    trim(
        $_GET['search']
        ?? ''
    );


/*
|--------------------------------------------------------------------------
| PAGINATION
|--------------------------------------------------------------------------
*/

$page =
    max(
        1,
        (int)(
            $_GET['page']
            ?? 1
        )
    );


$perPage = 10;


/*
|--------------------------------------------------------------------------
| SEARCH WHERE
|--------------------------------------------------------------------------
*/

$where = '';

$params = [];


if ($search !== '') {

    $where = "
        WHERE
        (
            r.route_name LIKE ?
            OR r.from_node LIKE ?
            OR r.to_node LIKE ?
            OR r.civil_type LIKE ?
            OR c.name LIKE ?
        )
    ";


    $like =
        '%' . $search . '%';


    $params = [
        $like,
        $like,
        $like,
        $like,
        $like
    ];
}


/*
|--------------------------------------------------------------------------
| ZONE FILTER
|--------------------------------------------------------------------------
| SUPERADMIN boleh lihat semua route.
| User biasa hanya boleh lihat route Zone sendiri.
| Route yang belum assigned (NULL) tidak boleh dilihat oleh user biasa.
|--------------------------------------------------------------------------
*/

if (!$isSuperAdmin && !$canViewAllRoutes) {

    if ($zoneId === null) {
        $where = 'WHERE 1 = 0';
        $params = [];
    } else {
        if ($where === '') {
            $where = 'WHERE r.zone_id = ?';
        } else {
            $where .= ' AND r.zone_id = ?';
        }

        $params[] = $zoneId;
    }
}


/*
|--------------------------------------------------------------------------
| COUNT ROUTES
|--------------------------------------------------------------------------
*/

$count =
    $pdo->prepare("
        SELECT COUNT(*)
        FROM routes r

        LEFT JOIN zones z
            ON z.id = r.zone_id

        JOIN cable_types c
            ON c.id = r.cable_type_id

        {$where}
    ");


$count->execute(
    $params
);


$totalRoutes =
    (int)$count->fetchColumn();


/*
|--------------------------------------------------------------------------
| TOTAL PAGES
|--------------------------------------------------------------------------
*/

$totalPages =
    max(
        1,
        (int)ceil(
            $totalRoutes / $perPage
        )
    );


if ($page > $totalPages) {

    $page =
        $totalPages;
}


$offset =
    ($page - 1)
    * $perPage;


/*
|--------------------------------------------------------------------------
| GET ROUTES
|--------------------------------------------------------------------------
*/

$stmt =
    $pdo->prepare("
        SELECT
            r.*,
            z.zone_name,
            z.zone_code,
            c.name AS cable_name,
            c.core_count

        FROM routes r

        LEFT JOIN zones z
            ON z.id = r.zone_id

        JOIN cable_types c
            ON c.id = r.cable_type_id

        {$where}

        ORDER BY r.id DESC

        LIMIT {$perPage}
        OFFSET {$offset}
    ");


$stmt->execute(
    $params
);


$routes =
    $stmt->fetchAll();


/*
|--------------------------------------------------------------------------
| GET CABLE TYPES
|--------------------------------------------------------------------------
*/

$cables =
    $pdo->query("
        SELECT *
        FROM cable_types
        WHERE status = 'ACTIVE'
        ORDER BY core_count
    ")
    ->fetchAll();


/*
|--------------------------------------------------------------------------
| PAGINATION URL
|--------------------------------------------------------------------------
*/

function route_page_url(
    int $page,
    string $search
): string {

    $query = [
        'page' => $page
    ];


    if ($search !== '') {

        $query['search'] =
            $search;
    }


    return
        'routes.php?'
        . http_build_query($query);
}


/*
|--------------------------------------------------------------------------
| IMPORTANT
|--------------------------------------------------------------------------
| HEADER HANYA DIPANGGIL SELEPAS SEMUA POST/REDIRECT SELESAI.
|--------------------------------------------------------------------------
*/

require_once '_header.php';

?>


<style>
/* FibreCore Route Master layout */
.route-master-table {
    width: 100%;
    margin-bottom: 0;
    font-size: 13px;
}
.route-master-table th {
    white-space: nowrap;
    vertical-align: middle !important;
    background: #f4f7fb;
    color: #243247;
    font-weight: 700;
    padding: 12px 10px;
    border-top: 0;
}
.route-master-table td {
    vertical-align: middle !important;
    padding: 11px 10px;
}
.route-master-table tbody tr:hover {
    background: #f7fbff;
}
.route-name-cell {
    min-width: 190px;
}
.route-name-line {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
}
.route-edit-btn {
    border-radius: 6px;
    padding: 3px 8px;
    font-size: 12px;
    white-space: nowrap;
}
.route-zone-form {
    min-width: 165px;
    max-width: 220px;
}
.route-zone-form .form-control {
    min-width: 0;
    font-size: 12px;
}
.route-actions {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 6px;
    min-width: 145px;
}
.route-actions .btn {
    border-radius: 6px;
    white-space: nowrap;
}
.route-add-card .card-body label {
    margin-top: 4px;
    margin-bottom: 5px;
    font-size: 13px;
}
.route-add-card .form-control {
    border-radius: 6px;
}
.route-add-card .card-footer {
    background: #f8fafc;
}
@media (max-width: 991.98px) {
    .route-master-table { font-size: 12px; }
    .route-master-table th,
    .route-master-table td { padding: 9px 8px; }
}
</style>

<!-- ========================================================= -->
<!-- SUCCESS -->
<!-- ========================================================= -->

<?php if ($routeSuccess !== ''): ?>

<div class="alert alert-success">

    <i class="fas fa-check-circle"></i>

    <?= e($routeSuccess) ?>

</div>

<?php endif; ?>


<!-- ========================================================= -->
<!-- ERROR -->
<!-- ========================================================= -->

<?php if ($routeError !== ''): ?>

<div class="alert alert-danger">

    <i class="fas fa-exclamation-circle"></i>

    <?= e($routeError) ?>

</div>

<?php endif; ?>






<?php if ($isSuperAdmin): ?>
<div id="routeEditModal" class="route-modal" aria-hidden="true">
  <div class="route-modal-backdrop js-close-route-modal"></div>
  <section class="route-modal-dialog" role="dialog" aria-modal="true" aria-labelledby="routeEditTitle">
    <div class="route-modal-header">
      <h3 id="routeEditTitle"><i class="fas fa-edit"></i> Edit Route Details</h3>
      <button type="button" class="route-modal-x js-close-route-modal" aria-label="Close">&times;</button>
    </div>
    <form method="post" action="routes.php">
      <input type="hidden" name="action" value="update_route_details">
      <input type="hidden" name="route_id" id="editRouteId">
      <div class="route-modal-body">
        <div class="alert alert-info py-2">Edit ini mengemaskini butiran route sahaja. Rekod core dan OTDR tidak dipadam. Cable Type hanya boleh ditukar jika bilangan core sedia ada sepadan.</div>
        <div class="row">
          <div class="col-md-6 form-group">
            <label for="editFromNode">Node A / From</label>
            <input class="form-control" id="editFromNode" name="from_node" maxlength="60" required>
          </div>
          <div class="col-md-6 form-group">
            <label for="editToNode">Node B / To</label>
            <input class="form-control" id="editToNode" name="to_node" maxlength="60" required>
          </div>
          <div class="col-md-6 form-group">
            <label for="editJunction">Junction</label>
            <select class="form-control" id="editJunction" name="junction_code" required>
              <option value="A">Junction A</option><option value="B">Junction B</option><option value="C">Junction C</option>
            </select>
          </div>
          <div class="col-md-6 form-group">
            <label for="editRouteName">Standard Route Name</label>
            <input class="form-control" id="editRouteName" readonly>
            <small class="text-muted">Dijana automatik daripada Node A, Node B dan Junction.</small>
          </div>
          <div class="col-md-6 form-group">
            <label for="editCableType">Cable Type</label>
            <select class="form-control" id="editCableType" name="cable_type_id" required>
              <?php foreach ($cables as $c): ?>
                <option value="<?= (int)$c['id'] ?>"><?= e($c['name']) ?> (<?= (int)$c['core_count'] ?> cores)</option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-6 form-group">
            <label for="editDistance">Actual Distance (KM)</label>
            <input class="form-control" type="number" min="0" step="0.001" id="editDistance" name="distance_km">
          </div>
          <div class="col-md-6 form-group">
            <label for="editCivil">Civil Type</label>
            <input class="form-control" id="editCivil" name="civil_type" placeholder="UG / OH / UG/OH">
          </div>
          <div class="col-md-6 form-group">
            <label for="editZone">Zone</label>
            <select class="form-control" id="editZone" name="zone_id">
              <option value="">NOT ASSIGNED</option>
              <?php foreach ($zones as $zone): ?>
                <option value="<?= (int)$zone['id'] ?>"><?= e($zone['zone_name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
      </div>
      <div class="route-modal-footer">
        <button type="button" class="btn btn-secondary js-close-route-modal">Cancel</button>
        <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Changes</button>
      </div>
    </form>
  </section>
</div>
<?php endif; ?>

<!-- ========================================================= -->
<!-- MAIN ROW -->
<!-- ========================================================= -->

<div class="row">


    <!-- ===================================================== -->
    <!-- ADD ROUTE -->
    <!-- ===================================================== -->

    <?php if ($isSuperAdmin || $isAdmin): ?>
    <div class="col-lg-3">

        <div class="card card-primary route-add-card">

            <div class="card-header">

                <h3 class="card-title">

                    <i class="fas fa-plus-circle"></i>

                    Add Route

                </h3>

            </div>


            <form method="post">

                <input
                    type="hidden"
                    name="action"
                    value="add_route"
                >


                <div class="card-body">

                    <!-- ZONE: SUPERADMIN SELECTS; ADMIN IS FIXED TO OWN ZONE -->
                    <?php if ($isSuperAdmin): ?>
                        <label>Zone</label>
                        <select class="form-control mb-2" name="zone_id" required>
                            <option value="">-- Select Zone --</option>
                            <?php foreach ($zones as $zone): ?>
                                <option value="<?= (int)$zone['id'] ?>">
                                    <?= e($zone['zone_name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    <?php else: ?>
                        <?php
                        $adminZoneName = '';
                        if ($zoneId !== null && (int)$zoneId > 0) {
                            foreach ($zones as $zone) {
                                if ((int)$zone['id'] === (int)$zoneId) {
                                    $adminZoneName = (string)$zone['zone_name'];
                                    break;
                                }
                            }
                        }
                        ?>
                        <label>Zone</label>
                        <input type="text"
                               class="form-control mb-2"
                               value="<?= e($adminZoneName !== '' ? $adminZoneName : 'Zone belum ditetapkan') ?>"
                               readonly>
                    <?php endif; ?>

                    <!-- ROUTE NAME -->

                    <label>
                        Route Name
                    </label>

                    <input
                        class="form-control mb-2"
                        id="addRouteName"
                        name="route_name"
                        placeholder="Auto: KMU-KDT_J_A"
                        required
                        readonly
                    >
                    <small class="form-text text-muted mb-2">Nama route dijana automatik mengikut format NODEA-NODEB_J_A/B/C.</small>
                    <label>Junction</label>
                    <select class="form-control mb-2" name="junction_code" id="addJunction" required>
                        <option value="A">Junction A</option>
                        <option value="B">Junction B</option>
                        <option value="C">Junction C</option>
                    </select>


                    <!-- FROM / TO -->

                    <div class="row">

                        <div class="col">

                            <label>
                                From
                            </label>

                            <input
                                class="form-control mb-2"
                                name="from_node"
                                id="addFromNode"
                                placeholder="Node A (e.g. KMU)"
                            >

                        </div>


                        <div class="col">

                            <label>
                                To
                            </label>

                            <input
                                class="form-control mb-2"
                                name="to_node"
                                id="addToNode"
                                placeholder="Node B (e.g. KDT)"
                            >

                        </div>

                    </div>


                    <!-- CABLE -->

                    <label>
                        Cable Type
                    </label>

                    <select
                        class="form-control mb-2"
                        name="cable_type_id"
                        required
                    >

                        <?php foreach ($cables as $c): ?>

                            <option
                                value="<?= (int)$c['id'] ?>"
                            >

                                <?= e($c['name']) ?>

                                (<?= (int)$c['core_count'] ?> cores)

                            </option>

                        <?php endforeach; ?>

                    </select>


                    <!-- DISTANCE -->

                    <label>
                        Distance KM
                    </label>

                    <input
                        class="form-control mb-2"
                        type="number"
                        step="0.001"
                        name="distance_km"
                        placeholder="Distance KM"
                    >


                    <!-- CIVIL -->

                    <label>
                        Civil Type
                    </label>

                    <input
                        class="form-control"
                        name="civil_type"
                        placeholder="UG / OH / UG/OH"
                    >

                </div>


                <div class="card-footer">

                    <button
                        type="submit"
                        class="btn btn-primary"
                    >

                        <i class="fas fa-save"></i>

                        Save Route

                    </button>

                </div>

            </form>

        </div>

    </div>
    <?php endif; ?>


    <!-- ===================================================== -->
    <!-- ROUTE MASTER -->
    <!-- ===================================================== -->

    <div class="<?= ($isSuperAdmin || $isAdmin) ? 'col-lg-9' : 'col-12' ?>">

        <div class="card">


            <!-- HEADER -->

            <div class="card-header">

                <div class="d-flex justify-content-between align-items-center">

                    <h3 class="card-title mb-0">

                        <i class="fas fa-route"></i>

                        Route Master

                    </h3>


                    <span class="text-muted">

                        <?= $totalRoutes ?>

                        route<?= $totalRoutes === 1 ? '' : 's' ?>

                    </span>

                </div>

            </div>


            <!-- ================================================= -->
            <!-- SEARCH -->
            <!-- ================================================= -->

            <div class="card-body border-bottom">

                <form method="get">

                    <div class="input-group">

                        <input
                            type="search"
                            name="search"
                            value="<?= e($search) ?>"
                            class="form-control"
                            placeholder="Search route, cable, From, To or Civil..."
                            autocomplete="off"
                        >


                        <div class="input-group-append">

                            <button
                                type="submit"
                                class="btn btn-primary"
                            >

                                <i class="fas fa-search"></i>

                                Search

                            </button>


                            <?php if ($search !== ''): ?>

                                <a
                                    href="routes.php"
                                    class="btn btn-secondary"
                                >

                                    Clear

                                </a>

                            <?php endif; ?>

                        </div>

                    </div>

                </form>

            </div>


            <!-- ================================================= -->
            <!-- TABLE -->
            <!-- ================================================= -->

            <div class="card-body table-responsive p-0">

                <table class="table table-hover mb-0 route-master-table">

                    <thead>

                        <tr>

                            <th>
                                Route
                            </th>

                            <th>
                                Cable
                            </th>

                            <th>
                                Core
                            </th>

                            <th>
                                Distance
                            </th>

                            <th>
                                Civil
                            </th>

                            <th>
                                Zone
                            </th>

                            <th>
                                Action
                            </th>

                        </tr>

                    </thead>


                    <tbody>


                        <?php if (!$routes): ?>

                            <tr>

                                <td
                                    colspan="7"
                                    class="text-center text-muted py-4"
                                >

                                    <i class="fas fa-route fa-2x mb-2"></i>

                                    <br>

                                    No route found.

                                </td>

                            </tr>

                        <?php endif; ?>


                        <?php foreach ($routes as $r): ?>

                            <tr>


                                <!-- ROUTE -->

                                <td class="route-name-cell">

                                    <div class="route-name-line">

                                        <strong class="text-nowrap">
                                            <?= e($r['route_name']) ?>
                                        </strong>

                                        <?php if ($isSuperAdmin): ?>

                                            <button
                                                type="button"
                                                class="btn btn-sm btn-light border route-edit-btn js-edit-route"
                                                title="Edit semua butiran route"
                                                data-id="<?= (int)$r['id'] ?>"
                                                data-from="<?= e((string)($r['from_node'] ?? '')) ?>"
                                                data-to="<?= e((string)($r['to_node'] ?? '')) ?>"
                                                data-name="<?= e((string)$r['route_name']) ?>"
                                                data-cable="<?= (int)$r['cable_type_id'] ?>"
                                                data-distance="<?= e((string)($r['distance_km'] ?? '')) ?>"
                                                data-civil="<?= e((string)($r['civil_type'] ?? '')) ?>"
                                                data-zone="<?= (int)($r['zone_id'] ?? 0) ?>"
                                            >
                                                <i class="fas fa-edit"></i> Edit
                                            </button>

                                        <?php endif; ?>

                                    </div>

                                </td>


                                <!-- CABLE -->

                                <td>

                                    <?= e(
                                        $r['cable_name']
                                    ) ?>

                                </td>


                                <!-- CORE -->

                                <td>

                                    <span class="badge badge-info">

                                        <?= (int)$r['core_count'] ?>

                                    </span>

                                </td>


                                <!-- DISTANCE -->

                                <td>

                                    <?= e(
                                        $r['distance_km']
                                    ) ?>

                                    KM

                                </td>


                                <!-- CIVIL -->

                                <td>

                                    <?= e(
                                        $r['civil_type']
                                    ) ?>

                                </td>


                                <!-- ZONE -->

                                <td>

                                    <?php if (!empty($r['zone_name'])): ?>

                                        <span class="badge badge-primary">

                                            <?= e($r['zone_name']) ?>

                                        </span>

                                    <?php else: ?>

                                        <span class="badge badge-warning">

                                            NOT ASSIGNED

                                        </span>

                                    <?php endif; ?>

                                    <?php if ($isSuperAdmin): ?>

                                        <form method="post" class="mt-2 route-zone-form">

                                            <input type="hidden" name="action" value="update_route_zone">

                                            <input type="hidden" name="route_id" value="<?= (int)$r['id'] ?>">

                                            <div class="input-group input-group-sm">

                                                <select name="zone_id" class="form-control">

                                                    <option value="">NOT ASSIGNED</option>

                                                    <?php foreach ($zones as $zone): ?>

                                                        <option
                                                            value="<?= (int)$zone['id'] ?>"
                                                            <?= ((int)($r['zone_id'] ?? 0) === (int)$zone['id']) ? 'selected' : '' ?>
                                                        >

                                                            <?= e($zone['zone_name']) ?>

                                                        </option>

                                                    <?php endforeach; ?>

                                                </select>

                                                <div class="input-group-append">

                                                    <button type="submit" class="btn btn-primary">
                                                        Save
                                                    </button>

                                                </div>

                                            </div>

                                        </form>

                                    <?php endif; ?>

                                </td>


                                <!-- ACTION -->

                                <td>

                                    <div class="route-actions">

                                    <!-- OPEN -->

                                    <a
                                        class="btn btn-sm btn-primary"
                                        href="route_detail.php?id=<?= (int)$r['id'] ?>"
                                    >

                                        <i class="fas fa-folder-open"></i>

                                        Open

                                    </a>


                                    <!-- DELETE SUPERADMIN SAHAJA -->

                                    <?php if ($isSuperAdmin): ?>

                                        <form
                                            method="post"
                                            class="d-inline"
                                            onsubmit="return confirm('Anda pasti mahu DELETE route <?= e($r['route_name']) ?>?\\n\\nSemua core dan rekod OTDR berkaitan route ini akan dipadam.');"
                                        >

                                            <input
                                                type="hidden"
                                                name="action"
                                                value="delete_route"
                                            >


                                            <input
                                                type="hidden"
                                                name="route_id"
                                                value="<?= (int)$r['id'] ?>"
                                            >


                                            <button
                                                type="submit"
                                                class="btn btn-sm btn-danger"
                                            >

                                                <i class="fas fa-trash"></i>

                                                Delete

                                            </button>

                                        </form>

                                    <?php endif; ?>

                                    </div>

                                </td>

                            </tr>

                        <?php endforeach; ?>


                    </tbody>

                </table>

            </div>


            <!-- ================================================= -->
            <!-- PAGINATION -->
            <!-- ================================================= -->

            <?php if ($totalPages > 1): ?>

                <div class="card-footer">

                    <div class="d-flex justify-content-between align-items-center flex-wrap">


                        <!-- INFO -->

                        <div class="text-muted mb-2 mb-md-0">

                            Page

                            <strong>
                                <?= $page ?>
                            </strong>

                            of

                            <strong>
                                <?= $totalPages ?>
                            </strong>

                            &nbsp; | &nbsp;

                            Total:

                            <strong>
                                <?= $totalRoutes ?>
                            </strong>

                        </div>


                        <!-- PAGINATION -->

                        <nav>

                            <ul class="pagination pagination-sm mb-0">


                                <!-- PREVIOUS -->

                                <li
                                    class="page-item
                                    <?= $page <= 1 ? 'disabled' : '' ?>"
                                >

                                    <?php if ($page > 1): ?>

                                        <a
                                            class="page-link"
                                            href="<?= e(
                                                route_page_url(
                                                    $page - 1,
                                                    $search
                                                )
                                            ) ?>"
                                        >

                                            Previous

                                        </a>

                                    <?php else: ?>

                                        <span class="page-link">

                                            Previous

                                        </span>

                                    <?php endif; ?>

                                </li>


                                <!-- PAGE NUMBERS -->

                                <?php

                                $start =
                                    max(
                                        1,
                                        $page - 2
                                    );


                                $end =
                                    min(
                                        $totalPages,
                                        $page + 2
                                    );


                                for (
                                    $p = $start;
                                    $p <= $end;
                                    $p++
                                ):

                                ?>

                                    <li
                                        class="page-item
                                        <?= $p === $page
                                            ? 'active'
                                            : '' ?>"
                                    >

                                        <a
                                            class="page-link"
                                            href="<?= e(
                                                route_page_url(
                                                    $p,
                                                    $search
                                                )
                                            ) ?>"
                                        >

                                            <?= $p ?>

                                        </a>

                                    </li>

                                <?php endfor; ?>


                                <!-- NEXT -->

                                <li
                                    class="page-item
                                    <?= $page >= $totalPages
                                        ? 'disabled'
                                        : '' ?>"
                                >

                                    <?php if ($page < $totalPages): ?>

                                        <a
                                            class="page-link"
                                            href="<?= e(
                                                route_page_url(
                                                    $page + 1,
                                                    $search
                                                )
                                            ) ?>"
                                        >

                                            Next

                                        </a>

                                    <?php else: ?>

                                        <span class="page-link">

                                            Next

                                        </span>

                                    <?php endif; ?>

                                </li>


                            </ul>

                        </nav>


                    </div>

                </div>

            <?php endif; ?>


        </div>

    </div>

</div>



<style>
.route-modal{display:none;position:fixed;inset:0;z-index:2050;align-items:center;justify-content:center;padding:20px}
.route-modal.is-open{display:flex}
.route-modal-backdrop{position:absolute;inset:0;background:rgba(13,27,48,.62)}
.route-modal-dialog{position:relative;background:#fff;width:min(760px,100%);max-height:92vh;overflow:auto;border-radius:14px;box-shadow:0 20px 60px rgba(0,0,0,.28);z-index:1}
.route-modal-header{display:flex;align-items:center;justify-content:space-between;padding:18px 22px;background:#0878ed;color:#fff;border-radius:14px 14px 0 0}
.route-modal-header h3{font-size:18px;margin:0;font-weight:700}
.route-modal-x{border:0;background:transparent;color:#fff;font-size:28px;line-height:1;cursor:pointer}
.route-modal-body{padding:20px 22px}
.route-modal-footer{display:flex;justify-content:flex-end;gap:8px;padding:14px 22px;background:#f7f9fc;border-top:1px solid #e5eaf1}
.route-modal .form-control{border-radius:7px}
body.route-modal-open{overflow:hidden}
</style>
<script>
document.addEventListener('DOMContentLoaded', function () {
    function makeRouteName(from, to, junction) {
        return (from || '').trim().toUpperCase() + '-' +
               (to || '').trim().toUpperCase() + '_J_' + (junction || 'A');
    }

    const addFrom = document.getElementById('addFromNode');
    const addTo = document.getElementById('addToNode');
    const addJunction = document.getElementById('addJunction');
    const addName = document.getElementById('addRouteName');
    function updateAddName() {
        if (addName && addFrom && addTo && addJunction) {
            addName.value = (addFrom.value.trim() && addTo.value.trim())
                ? makeRouteName(addFrom.value, addTo.value, addJunction.value)
                : '';
        }
    }
    [addFrom, addTo, addJunction].forEach(function (el) {
        if (el) { el.addEventListener('input', updateAddName); el.addEventListener('change', updateAddName); }
    });
    updateAddName();

    const modal = document.getElementById('routeEditModal');
    const editFrom = document.getElementById('editFromNode');
    const editTo = document.getElementById('editToNode');
    const editJunction = document.getElementById('editJunction');
    const editName = document.getElementById('editRouteName');
    function updateEditName() {
        if (editName && editFrom && editTo && editJunction) {
            editName.value = (editFrom.value.trim() && editTo.value.trim())
                ? makeRouteName(editFrom.value, editTo.value, editJunction.value) : '';
        }
    }
    document.querySelectorAll('.js-edit-route').forEach(function (button) {
        button.addEventListener('click', function () {
            if (!modal) return;
            const data = button.dataset;
            document.getElementById('editRouteId').value = data.id || '';
            editFrom.value = data.from || '';
            editTo.value = data.to || '';
            const match = (data.name || '').match(/_J_([ABC])$/i);
            editJunction.value = match ? match[1].toUpperCase() : 'A';
            document.getElementById('editCableType').value = data.cable || '';
            document.getElementById('editDistance').value = data.distance || '';
            document.getElementById('editCivil').value = data.civil || '';
            document.getElementById('editZone').value = data.zone || '';
            updateEditName();
            modal.classList.add('is-open');
            modal.setAttribute('aria-hidden', 'false');
            document.body.classList.add('route-modal-open');
        });
    });
    [editFrom, editTo, editJunction].forEach(function (el) {
        if (el) { el.addEventListener('input', updateEditName); el.addEventListener('change', updateEditName); }
    });
    document.querySelectorAll('.js-close-route-modal').forEach(function (el) {
        el.addEventListener('click', function () {
            if (!modal) return;
            modal.classList.remove('is-open');
            modal.setAttribute('aria-hidden', 'true');
            document.body.classList.remove('route-modal-open');
        });
    });
    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape' && modal && modal.classList.contains('is-open')) {
            modal.classList.remove('is-open');
            modal.setAttribute('aria-hidden', 'true');
            document.body.classList.remove('route-modal-open');
        }
    });
});
</script>

<?php

require_once '_footer.php';

?>