<?php

declare(strict_types=1);

require_once '_header.php';

$pdo = db();

$user = current_user();

$isSuperAdmin =
    strtoupper(
        (string)($user['role'] ?? '')
    ) === 'SUPERADMIN';


/*
|--------------------------------------------------------------------------
| USER VIEW ALL ROUTES
|--------------------------------------------------------------------------
| SUPERADMIN = sentiasa boleh lihat semua.
| User lain = check database.
|--------------------------------------------------------------------------
*/

$canViewAllRoutes = false;

if ($isSuperAdmin) {

    $canViewAllRoutes = true;

} else {

    try {

        $stmt = $pdo->prepare("
            SELECT can_view_all_routes
            FROM users
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->execute([
            (int)($user['id'] ?? 0)
        ]);

        $canViewAllRoutes =
            (bool)$stmt->fetchColumn();

    } catch (Throwable $e) {

        /*
        | Kalau column belum wujud,
        | jangan rosakkan dashboard.
        */
        $canViewAllRoutes = false;
    }
}


/*
|--------------------------------------------------------------------------
| CURRENT USER ZONE
|--------------------------------------------------------------------------
*/

$userZoneId = null;

try {

    $stmt = $pdo->prepare("
        SELECT zone_id
        FROM users
        WHERE id = ?
        LIMIT 1
    ");

    $stmt->execute([
        (int)($user['id'] ?? 0)
    ]);

    $zoneValue = $stmt->fetchColumn();

    if ($zoneValue !== false && $zoneValue !== null) {

        $userZoneId = (int)$zoneValue;
    }

} catch (Throwable $e) {

    $userZoneId = null;
}


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

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


/*
|--------------------------------------------------------------------------
| FILTER ZONE
|--------------------------------------------------------------------------
*/

$filterZone = trim(
    (string)($_GET['zone'] ?? '')
);


/*
|--------------------------------------------------------------------------
| FILTER CABLE
|--------------------------------------------------------------------------
*/

$filterRoute = trim(
    (string)($_GET['route'] ?? '')
);


/*
|--------------------------------------------------------------------------
| PAGE
|--------------------------------------------------------------------------
*/

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

$perPage = 10;


/*
|--------------------------------------------------------------------------
| GET ZONES
|--------------------------------------------------------------------------
*/

$zones = [];

try {

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

} catch (Throwable $e) {

    $zones = [];
}


/*
|--------------------------------------------------------------------------
| ROUTE FILTER OPTIONS
|--------------------------------------------------------------------------
| Options respect the user's route access and selected zone.
|--------------------------------------------------------------------------
*/

$availableRoutes = [];
try {
    $routeOptionWhere = ["r.status = 'ACTIVE'"];
    $routeOptionParams = [];

    if (!$canViewAllRoutes) {
        if ($userZoneId === null || $userZoneId <= 0) {
            $routeOptionWhere[] = "1 = 0";
        } else {
            $routeOptionWhere[] = "r.zone_id = ?";
            $routeOptionParams[] = $userZoneId;
        }
    }

    if ($canViewAllRoutes && $filterZone !== '') {
        $routeOptionWhere[] = "r.zone_id = ?";
        $routeOptionParams[] = (int)$filterZone;
    }

    $routeOptionStmt = $pdo->prepare(
        "SELECT r.id, r.route_name FROM routes r WHERE " .
        implode(' AND ', $routeOptionWhere) .
        " ORDER BY r.route_name ASC"
    );
    $routeOptionStmt->execute($routeOptionParams);
    $availableRoutes = $routeOptionStmt->fetchAll();
} catch (Throwable $e) {
    error_log('FiberCore dashboard route filter error: ' . $e->getMessage());
    $availableRoutes = [];
}


/*
|--------------------------------------------------------------------------
| BUILD WHERE
|--------------------------------------------------------------------------
*/

$where = [
    "r.status = 'ACTIVE'"
];

$params = [];


/*
|--------------------------------------------------------------------------
| ACCESS CONTROL
|--------------------------------------------------------------------------
|
| SUPERADMIN
|   -> semua route
|
| USER + VIEW ALL
|   -> semua route
|
| USER BIASA
|   -> Zone sendiri sahaja
|
|--------------------------------------------------------------------------
*/

if (!$canViewAllRoutes) {

    if ($userZoneId === null || $userZoneId <= 0) {

        /*
        | User tiada Zone = tiada route.
        */
        $where[] = "1 = 0";

    } else {

        $where[] = "r.zone_id = ?";

        $params[] = $userZoneId;
    }
}


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

if ($search !== '') {

    $where[] = "
        (
            r.route_name LIKE ?
            OR r.from_node LIKE ?
            OR r.to_node LIKE ?
            OR r.civil_type LIKE ?
            OR c.name LIKE ?
            OR z.zone_name LIKE ?
        )
    ";

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

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


/*
|--------------------------------------------------------------------------
| ZONE FILTER
|--------------------------------------------------------------------------
|
| Hanya SUPERADMIN / View All boleh pilih Zone.
|--------------------------------------------------------------------------
*/

if (
    $canViewAllRoutes &&
    $filterZone !== ''
) {

    $where[] = "r.zone_id = ?";

    $params[] = (int)$filterZone;
}


/*
|--------------------------------------------------------------------------
| CHOOSE ROUTE FILTER
|--------------------------------------------------------------------------
*/

if ($filterRoute !== '' && ctype_digit($filterRoute)) {
    $where[] = "r.id = ?";
    $params[] = (int)$filterRoute;
}


$whereSql = implode(
    " AND ",
    $where
);


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

$countSql = "
    SELECT COUNT(*)

    FROM routes r

    JOIN cable_types c
        ON c.id = r.cable_type_id

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

    WHERE {$whereSql}
";

$countStmt = $pdo->prepare($countSql);

$countStmt->execute(
    $params
);

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


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

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


if ($page > $totalPages) {

    $page = $totalPages;
}


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


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

$routeSql = "
    SELECT

        r.id,
        r.route_name,
        r.distance_km,
        r.civil_type,
        r.zone_id,

        z.zone_name,
        z.zone_code,

        c.name AS cable_name,
        c.core_count,

        (
            SELECT COUNT(*)
            FROM fiber_cores fc
            WHERE
                fc.route_id = r.id
                AND fc.status = 'USED'
        ) AS used_count,

        (
            SELECT COUNT(*)
            FROM fiber_cores fc
            WHERE
                fc.route_id = r.id
                AND fc.status = 'FREE'
        ) AS free_count,

        (
            SELECT COUNT(*)
            FROM fiber_cores fc
            WHERE
                fc.route_id = r.id
                AND (
                    fc.status = 'FAULTY'
                    OR (fc.fault_type = 'HIGH_LOSS' AND fc.status <> 'CUT')
                )
        ) AS faulty_count

    FROM routes r

    JOIN cable_types c
        ON c.id = r.cable_type_id

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

    WHERE {$whereSql}

    ORDER BY
        r.route_name ASC

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

$routeStmt = $pdo->prepare(
    $routeSql
);

$routeStmt->execute(
    $params
);

$routes = $routeStmt->fetchAll();


/*
|--------------------------------------------------------------------------
| DASHBOARD TOTALS
|--------------------------------------------------------------------------
|
| Kira berdasarkan SEMUA route yang user boleh akses,
| bukan hanya 10 route pada page semasa.
|--------------------------------------------------------------------------
*/

$summarySql = "
    SELECT

        COUNT(DISTINCT r.id) AS total_routes,

        COALESCE(
            SUM(c.core_count),
            0
        ) AS total_cores,

        COALESCE(
            SUM(
                (
                    SELECT COUNT(*)
                    FROM fiber_cores fc1
                    WHERE
                        fc1.route_id = r.id
                        AND fc1.status = 'USED'
                )
            ),
            0
        ) AS used_cores,

        COALESCE(
            SUM(
                (
                    SELECT COUNT(*)
                    FROM fiber_cores fc2
                    WHERE
                        fc2.route_id = r.id
                        AND fc2.status = 'FREE'
                )
            ),
            0
        ) AS free_cores,

        COALESCE(
            SUM(
                (
                    SELECT COUNT(*)
                    FROM fiber_cores fc3
                    WHERE
                        fc3.route_id = r.id
                        AND (
                            fc3.status = 'FAULTY'
                            OR fc3.fault_type = 'HIGH_LOSS'
                        )
                )
            ),
            0
        ) AS faulty_cores,

        COALESCE(
            SUM((
                SELECT COUNT(*)
                FROM fiber_cores fc4
                WHERE fc4.route_id = r.id
                  AND fc4.fault_type = 'HIGH_LOSS'
                  AND fc4.status <> 'CUT'
            )),
            0
        ) AS highloss_cores

    FROM routes r

    JOIN cable_types c
        ON c.id = r.cable_type_id

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

    WHERE {$whereSql}
";

$summaryStmt = $pdo->prepare(
    $summarySql
);

$summaryStmt->execute(
    $params
);

$summary = $summaryStmt->fetch();


$totalRoutesDashboard =
    (int)($summary['total_routes'] ?? 0);

$totalCores =
    (int)($summary['total_cores'] ?? 0);

$used =
    (int)($summary['used_cores'] ?? 0);

$free =
    (int)($summary['free_cores'] ?? 0);

$faulty =
    (int)($summary['faulty_cores'] ?? 0);

/*
|--------------------------------------------------------------------------
| DASHBOARD KPI VALUES
|--------------------------------------------------------------------------
| Every KPI uses the same route-access, search, zone and Choose Route filter.
|--------------------------------------------------------------------------
*/

$utilisationPercent = $totalCores > 0
    ? round(($used / $totalCores) * 100, 1)
    : 0;
$throughPercent = 0;
$faultyPercent = $totalCores > 0
    ? round(($faulty / $totalCores) * 100, 1)
    : 0;
$totalHighLoss = (int)($summary['highloss_cores'] ?? 0);

try {
    $throughSql = "
        SELECT COUNT(*)
        FROM fiber_cores fc
        INNER JOIN routes r ON r.id = fc.route_id
        JOIN cable_types c ON c.id = r.cable_type_id
        LEFT JOIN zones z ON z.id = r.zone_id
        INNER JOIN (
            SELECT cc.route_id, cc.core_id, MAX(cc.id) AS latest_id
            FROM core_continuity cc
            GROUP BY cc.route_id, cc.core_id
        ) latest ON latest.route_id = fc.route_id AND latest.core_id = fc.id
        INNER JOIN core_continuity cc ON cc.id = latest.latest_id
        WHERE {$whereSql}
          AND cc.continuity_status = 'CONFIRMED_THROUGH'
    ";
    $throughStmt = $pdo->prepare($throughSql);
    $throughStmt->execute($params);
    $confirmedThroughCores = (int)$throughStmt->fetchColumn();
    $throughPercent = $totalCores > 0
        ? round(($confirmedThroughCores / $totalCores) * 100, 1)
        : 0;
} catch (Throwable $e) {
    error_log('FiberCore dashboard through KPI error: ' . $e->getMessage());
    $throughPercent = 0;
}


/*
|--------------------------------------------------------------------------
| PAGE URL
|--------------------------------------------------------------------------
*/

function dashboard_page_url(
    int $page,
    string $search,
    string $zone,
    string $route
): string {

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

    if ($search !== '') {

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

    if ($zone !== '') {

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

    if ($route !== '') {
        $query['route'] = $route;
    }

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

?>

<!-- =========================================================
     HEADER
========================================================= -->

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

    <div>

        <h1 class="mb-0">
            Dashboard
        </h1>

        <div class="text-muted">
            <i class="fas fa-globe-asia"></i>

            <?php if ($canViewAllRoutes): ?>

                All Zones

            <?php else: ?>

                <?php
                $currentZoneName = 'Zone Not Assigned';

                foreach ($zones as $zone) {

                    if (
                        (int)$zone['id']
                        ===
                        (int)$userZoneId
                    ) {

                        $currentZoneName =
                            $zone['zone_name'];

                        break;
                    }
                }

                echo e($currentZoneName);
                ?>

            <?php endif; ?>

        </div>

    </div>


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

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

        Manage Routes

    </a>

</div>


<style>
/* Keep dashboard KPI cards visible while scrolling the dashboard content. */
.fc-sticky-kpi-wrap{
    position: sticky;
    top: 0;
    z-index: 1025;
    padding: 8px 0 2px;
    margin-top: -8px;
    background: rgba(244,246,249,.97);
    backdrop-filter: blur(7px);
    -webkit-backdrop-filter: blur(7px);
    border-bottom: 1px solid rgba(203,213,225,.65);
}
.fc-sticky-kpi-row{margin-bottom:0;}
.fc-sticky-kpi-row .small-box{margin-bottom:8px;}
@media(max-width:767px){.fc-sticky-kpi-wrap{top:0;padding-top:6px}.fc-sticky-kpi-row .small-box{margin-bottom:7px}}
</style>

<!-- =========================================================
     STATISTICS: FIVE REQUIRED KPIs (STICKY WHILE SCROLLING)
========================================================= -->

<div class="fc-sticky-kpi-wrap">
<div class="row fc-sticky-kpi-row">
    <!-- TOTAL ROUTE -->
    <div class="col-lg col-md-4 col-sm-6">
        <div class="small-box bg-primary">
            <div class="inner">
                <h3><?= number_format($totalRoutesDashboard) ?></h3>
                <p>Total Route</p>
                <small>Routes in current filter</small>
            </div>
            <div class="icon"><i class="fas fa-route"></i></div>
        </div>
    </div>

    <!-- TOTAL CORE UTILISATION -->
    <div class="col-lg col-md-4 col-sm-6">
        <div class="small-box bg-success">
            <div class="inner">
                <h3><?= number_format($utilisationPercent, 1) ?>%</h3>
                <p>Total Core Utilisation</p>
                <small><?= number_format($used) ?> USED / <?= number_format($totalCores) ?> cores</small>
            </div>
            <div class="icon"><i class="fas fa-chart-line"></i></div>
        </div>
    </div>

    <!-- FREE CORE THROUGH -->
    <div class="col-lg col-md-4 col-sm-6">
        <div class="small-box bg-warning">
            <div class="inner">
                <h3><?= number_format($throughPercent, 1) ?>%</h3>
                <p>Free Core (Through)</p>
                <small>Confirmed through / total cores</small>
            </div>
            <div class="icon"><i class="fas fa-check-circle"></i></div>
        </div>
    </div>

    <!-- FAULTY CORE -->
    <div class="col-lg col-md-4 col-sm-6">
        <div class="small-box bg-danger">
            <div class="inner">
                <h3><?= number_format($faulty) ?></h3>
                <p>Faulty Core</p>
                <small><?= number_format($faultyPercent, 1) ?>% of total cores</small>
            </div>
            <div class="icon"><i class="fas fa-exclamation-triangle"></i></div>
        </div>
    </div>

    <!-- TOTAL CORE HIGH LOSS -->
    <div class="col-lg col-md-4 col-sm-6">
        <div class="small-box bg-maroon">
            <div class="inner">
                <h3><?= number_format($totalHighLoss) ?></h3>
                <p>Total Core High Loss</p>
                <small>High-loss cores in current filter</small>
            </div>
            <div class="icon"><i class="fas fa-wave-square"></i></div>
        </div>
    </div>
</div>
</div>


<!-- =========================================================
     SEARCH + FILTER
========================================================= -->

<div class="card">

    <div class="card-header">

        <h3 class="card-title">

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

            Search & Filter Routes

        </h3>

    </div>


    <div class="card-body">

        <form
            method="get"
            action="dashboard.php"
        >

            <div class="row">


                <!-- SEARCH -->

                <div class="col-md-5 mb-2">

                    <label>
                        Search
                    </label>

                    <div class="input-group">

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

                            <span class="input-group-text">

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

                            </span>

                        </div>

                        <input
                            type="text"
                            name="search"
                            class="form-control"
                            placeholder="Search route, node, cable..."
                            value="<?= e($search) ?>"
                        >

                    </div>

                </div>


                <!-- ZONE -->

                <?php if ($canViewAllRoutes): ?>

                    <div class="col-md-3 mb-2">

                        <label>
                            Zone
                        </label>

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

                            <option value="">
                                All Zones
                            </option>

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

                                <option
                                    value="<?= (int)$zone['id'] ?>"
                                    <?= (
                                        (string)$filterZone
                                        ===
                                        (string)$zone['id']
                                    )
                                        ? 'selected'
                                        : ''
                                    ?>
                                >

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

                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>

                <?php endif; ?>


                <!-- CHOOSE ROUTE -->
                <div class="col-md-2 mb-2">
                    <label>Choose Route</label>
                    <select name="route" class="form-control">
                        <option value="">All Routes</option>
                        <?php foreach ($availableRoutes as $routeOption): ?>
                            <option value="<?= (int)$routeOption['id'] ?>" <?= ((string)$filterRoute === (string)$routeOption['id']) ? 'selected' : '' ?>>
                                <?= e($routeOption['route_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- BUTTON -->

                <div class="col-md-2 mb-2 d-flex align-items-end">

                    <div class="w-100">

                        <button
                            type="submit"
                            class="btn btn-primary"
                            style="width:48%;"
                        >

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

                            Search

                        </button>


                        <a
                            href="dashboard.php"
                            class="btn btn-secondary"
                            style="width:48%;"
                        >

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

                            Reset

                        </a>

                    </div>

                </div>


            </div>

        </form>

    </div>

</div>


<!-- =========================================================
     ROUTE UTILISATION
========================================================= -->

<div class="card">

    <div class="card-header">

        <h3 class="card-title">

            <i class="fas fa-chart-pie"></i>

            Route Utilisation

        </h3>

        <div class="card-tools">

            <span class="badge badge-info">

                <?= $totalRoutesDashboard ?>

                Route(s)

            </span>

        </div>

    </div>


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


        <div class="table-responsive">

            <table class="table table-striped table-hover mb-0">

                <thead>

                    <tr>

                        <th>
                            Route
                        </th>

                        <th>
                            Zone
                        </th>

                        <th>
                            Cable
                        </th>

                        <th>
                            Distance
                        </th>

                        <th>
                            Civil
                        </th>

                        <th>
                            Used
                        </th>

                        <th>
                            Free
                        </th>

                        <th>
                            Faulty
                        </th>

                        <th>
                            Util %
                        </th>

                        <th>
                        </th>

                    </tr>

                </thead>


                <tbody>

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

                    <tr>

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

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

                            <br>

                            No routes found.

                        </td>

                    </tr>

                <?php else: ?>


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

                        <?php

                        $coreCount =
                            (int)$r['core_count'];

                        $usedCount =
                            (int)$r['used_count'];

                        $util =
                            $coreCount > 0
                                ? round(
                                    $usedCount
                                    /
                                    $coreCount
                                    *
                                    100,
                                    1
                                )
                                : 0;

                        ?>


                        <tr>


                            <!-- ROUTE -->

                            <td>

                                <strong>

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

                                </strong>

                            </td>


                            <!-- ZONE -->

                            <td>

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

                                    <span
                                        class="badge badge-info"
                                    >

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

                                    </span>

                                <?php else: ?>

                                    <span
                                        class="badge badge-secondary"
                                    >

                                        NOT ASSIGNED

                                    </span>

                                <?php endif; ?>

                            </td>


                            <!-- CABLE -->

                            <td>

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

                            </td>


                            <!-- DISTANCE -->

                            <td>

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

                                KM

                            </td>


                            <!-- CIVIL -->

                            <td>

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

                            </td>


                            <!-- USED -->

                            <td>

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

                            </td>


                            <!-- FREE -->

                            <td>

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

                            </td>


                            <!-- FAULTY -->

                            <td>

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

                            </td>


                            <!-- UTIL -->

                            <td>

                                <span
                                    class="badge badge-<?=
                                        $util >= 70
                                            ? 'danger'
                                            : (
                                                $util >= 40
                                                    ? 'warning'
                                                    : 'success'
                                            )
                                    ?>"
                                >

                                    <?= $util ?>%

                                </span>

                            </td>


                            <!-- OPEN -->

                            <td>

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

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

                                    Open

                                </a>

                            </td>


                        </tr>


                    <?php endforeach; ?>


                <?php endif; ?>

                </tbody>

            </table>

        </div>

    </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">

                    Showing

                    <strong>

                        <?= $totalRoutes > 0
                            ? ($offset + 1)
                            : 0
                        ?>

                    </strong>

                    -

                    <strong>

                        <?= min(
                            $offset + $perPage,
                            $totalRoutes
                        ) ?>

                    </strong>

                    of

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

                    routes

                </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(
                                        dashboard_page_url(
                                            $page - 1,
                                            $search,
                                            $filterZone,
                                            $filterRoute
                                        )
                                    ) ?>"
                                >

                                    Previous

                                </a>

                            <?php else: ?>

                                <span class="page-link">
                                    Previous
                                </span>

                            <?php endif; ?>

                        </li>


                        <!-- PAGE NUMBERS -->

                        <?php

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

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

                        ?>


                        <?php for (
                            $p = $startPage;
                            $p <= $endPage;
                            $p++
                        ): ?>

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

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

                                    <?= $p ?>

                                </a>

                            </li>

                        <?php endfor; ?>


                        <!-- NEXT -->

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

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

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

                                    Next

                                </a>

                            <?php else: ?>

                                <span class="page-link">
                                    Next
                                </span>

                            <?php endif; ?>

                        </li>


                    </ul>

                </nav>

            </div>

        </div>

    <?php endif; ?>


</div>



<!-- Integrated analysis workspace: uses the existing analysis pages and database logic. -->
<style>
.fc-analysis-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin:24px 0 12px}
.fc-analysis-heading h3{font-weight:700;color:#183b63;margin:0;font-size:1.25rem}
.fc-analysis-subtitle{color:#64748b;font-size:.9rem;margin-top:4px}
.fc-analysis-panel{border:1px solid #dbe4ef;border-radius:12px;background:#fff;box-shadow:0 4px 16px rgba(15,35,65,.06);margin-bottom:18px;overflow:hidden}
.fc-analysis-panel summary{list-style:none;cursor:pointer;display:flex;align-items:center;gap:12px;padding:16px 18px;background:linear-gradient(120deg,#f8fbff,#eef5fc);}
.fc-analysis-panel summary::-webkit-details-marker{display:none}
.fc-analysis-icon{width:42px;height:42px;border-radius:10px;display:flex;align-items:center;justify-content:center;color:#fff;font-size:18px;flex-shrink:0}
.fc-analysis-title{font-size:1rem;font-weight:700;color:#16385d;margin:0}
.fc-analysis-desc{font-size:.82rem;color:#64748b;margin-top:3px}
.fc-analysis-actions{margin-left:auto;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.fc-analysis-actions a{white-space:nowrap}
.fc-analysis-frame{display:block;width:100%;height:900px;border:0;background:#f4f6f9;overflow:hidden}
.fc-analysis-note{padding:10px 16px;background:#f8fafc;border-top:1px solid #e2e8f0;color:#64748b;font-size:12px}
@media(max-width:767px){.fc-analysis-frame{height:1000px}.fc-analysis-panel summary{align-items:flex-start;padding:12px}.fc-analysis-actions{width:100%;margin-left:54px}}
</style>

<div class="fc-analysis-heading">
  <div><h3><i class="fas fa-chart-line text-primary mr-2"></i>Advanced Network Analysis</h3><div class="fc-analysis-subtitle">Span loss, route core continuity and bi-directional OTDR analysis in one workspace.</div></div>
  <span class="badge badge-light border p-2"><i class="fas fa-layer-group mr-1 text-primary"></i> Integrated dashboard</span>
</div>

<details class="fc-analysis-panel" open>
  <summary>
    <span class="fc-analysis-icon" style="background:linear-gradient(135deg,#0879d1,#0753a5)"><i class="fas fa-wave-square"></i></span>
    <span><span class="fc-analysis-title d-block">Span Loss Analysis</span><span class="fc-analysis-desc d-block">Review OTDR event points, route distance, loss alerts and repair indicators.</span></span>
    <span class="fc-analysis-actions"><a class="btn btn-sm btn-outline-primary" href="span_loss_analysis.php" target="_blank" rel="noopener"><i class="fas fa-external-link-alt mr-1"></i>Full page</a><i class="fas fa-chevron-down text-muted"></i></span>
  </summary>
  <iframe class="fc-analysis-frame" loading="lazy" title="Span Loss Analysis" src="span_loss_analysis.php?embed=dashboard<?= ($filterRoute !== '' && ctype_digit($filterRoute) && (int)$filterRoute > 0) ? '&amp;route_id=' . (int)$filterRoute : '' ?>"></iframe>
  <div class="fc-analysis-note">Analisis menggunakan data dan peraturan sedia ada. Untuk paparan penuh atau cetakan, gunakan butang Full page.</div>
</details>

<details class="fc-analysis-panel">
  <summary>
    <span class="fc-analysis-icon" style="background:linear-gradient(135deg,#0f9b8e,#08766c)"><i class="fas fa-project-diagram"></i></span>
    <span><span class="fc-analysis-title d-block">Route Core Analysis</span><span class="fc-analysis-desc d-block">Review confirmed THROUGH continuity and core availability by route.</span></span>
    <span class="fc-analysis-actions"><a class="btn btn-sm btn-outline-primary" href="route_core_analysis.php" target="_blank" rel="noopener"><i class="fas fa-external-link-alt mr-1"></i>Full page</a><i class="fas fa-chevron-down text-muted"></i></span>
  </summary>
  <iframe class="fc-analysis-frame" loading="lazy" title="Route Core Analysis" src="route_core_analysis.php?embed=dashboard<?= ($filterRoute !== '' && ctype_digit($filterRoute) && (int)$filterRoute > 0) ? '&amp;route_id=' . (int)$filterRoute : '' ?>"></iframe>
  <div class="fc-analysis-note">Status THROUGH hanya berdasarkan rekod continuity yang disahkan.</div>
</details>

<details class="fc-analysis-panel">
  <summary>
    <span class="fc-analysis-icon" style="background:linear-gradient(135deg,#7c3aed,#4c1d95)"><i class="fas fa-exchange-alt"></i></span>
    <span><span class="fc-analysis-title d-block">Bi-Directional OTDR Analysis</span><span class="fc-analysis-desc d-block">Compare forward and reverse test events, matched cores and candidate repair locations.</span></span>
    <span class="fc-analysis-actions"><a class="btn btn-sm btn-outline-primary" href="bi_directional_otdr.php" target="_blank" rel="noopener"><i class="fas fa-external-link-alt mr-1"></i>Full page</a><i class="fas fa-chevron-down text-muted"></i></span>
  </summary>
  <iframe class="fc-analysis-frame" loading="lazy" title="Bi-Directional OTDR Analysis" src="bi_directional_otdr.php?embed=dashboard<?= ($filterRoute !== '' && ctype_digit($filterRoute) && (int)$filterRoute > 0) ? '&amp;route_id=' . (int)$filterRoute : '' ?>"></iframe>
  <div class="fc-analysis-note">Padanan dua arah bergantung pada event point yang benar-benar disimpan. Lokasi calon yang belum sepadan perlu disahkan di lapangan.</div>
</details>

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