<?php

declare(strict_types=1);

require_once '_header.php';

$pdo = db();

$user = current_user();

$userId = (int)($user['id'] ?? 0);

$role = strtoupper(
    (string)($user['role'] ?? '')
);

$isSuperAdmin = ($role === 'SUPERADMIN');


/*
|--------------------------------------------------------------------------
| USER ZONE
|--------------------------------------------------------------------------
*/

$userZoneId = null;

try {

    $stmt = $pdo->prepare("
        SELECT zone_id
        FROM users
        WHERE id = ?
        LIMIT 1
    ");

    $stmt->execute([
        $userId
    ]);

    $zone = $stmt->fetchColumn();

    if (
        $zone !== false &&
        $zone !== null &&
        $zone !== ''
    ) {
        $userZoneId = (int)$zone;
    }

} catch (Throwable $e) {

    $userZoneId = null;
}


/*
|--------------------------------------------------------------------------
| VIEW ALL ROUTES
|--------------------------------------------------------------------------
|
| SUPERADMIN:
|   - boleh lihat semua Zone
|
| User biasa:
|   - hanya boleh lihat semua route jika
|     can_view_all_routes = 1
|
| Jika column belum wujud:
|   - automatically FALSE
|
|--------------------------------------------------------------------------
*/

$canViewAllRoutes = false;

if ($isSuperAdmin) {

    $canViewAllRoutes = true;

} else {

    try {

        $stmt = $pdo->prepare("
            SELECT can_view_all_routes
            FROM users
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->execute([
            $userId
        ]);

        $canViewAllRoutes =
            ((int)$stmt->fetchColumn() === 1);

    } catch (Throwable $e) {

        /*
        | Column belum ada:
        | user biasa tidak boleh lihat semua.
        */
        $canViewAllRoutes = false;
    }
}


/*
|--------------------------------------------------------------------------
| SEARCH
|--------------------------------------------------------------------------
*/

$search = trim(
    (string)($_GET['search'] ?? '')
);


/*
|--------------------------------------------------------------------------
| PAGINATION
|--------------------------------------------------------------------------
*/

$page = max(
    1,
    (int)($_GET['page'] ?? 1)
);

$perPage = 10;


/*
|--------------------------------------------------------------------------
| WHERE
|--------------------------------------------------------------------------
*/

$where = [
    "r.status = 'ACTIVE'"
];

$params = [];


/*
|--------------------------------------------------------------------------
| ZONE ACCESS CONTROL
|--------------------------------------------------------------------------
|
| SUPERADMIN / approved View All:
|     semua route
|
| USER BIASA:
|     zone sendiri sahaja
|
|--------------------------------------------------------------------------
*/

if (!$canViewAllRoutes) {

    if (
        $userZoneId === null ||
        $userZoneId <= 0
    ) {

        /*
        | Tiada Zone = tiada data
        */
        $where[] = "1 = 0";

    } else {

        $where[] = "r.zone_id = ?";

        $params[] = $userZoneId;
    }
}


/*
|--------------------------------------------------------------------------
| SEARCH
|--------------------------------------------------------------------------
*/

if ($search !== '') {

    $where[] = "
        (
            r.route_name LIKE ?
            OR c.name LIKE ?
            OR r.civil_type LIKE ?
            OR z.zone_name LIKE ?
        )
    ";

    $like = '%' . $search . '%';

    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}


$whereSql = implode(
    ' AND ',
    $where
);


/*
|--------------------------------------------------------------------------
| COUNT TOTAL 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();


/*
|--------------------------------------------------------------------------
| PAGINATION TOTAL
|--------------------------------------------------------------------------
*/

$totalPages = max(
    1,
    (int)ceil(
        $totalRoutes / $perPage
    )
);


if ($page > $totalPages) {

    $page = $totalPages;
}


$offset =
    ($page - 1)
    * $perPage;


/*
|--------------------------------------------------------------------------
| GET ROUTES
|--------------------------------------------------------------------------
*/

$sql = "
    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'
                )
        ) 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}
";


$stmt = $pdo->prepare(
    $sql
);

$stmt->execute(
    $params
);

$routes = $stmt->fetchAll();


/*
|--------------------------------------------------------------------------
| PAGE URL
|--------------------------------------------------------------------------
*/

function core_utilisation_page_url(
    int $page,
    string $search
): string {

    $query = [
        'page' => $page
    ];

    if ($search !== '') {

        $query['search'] = $search;
    }

    return
        'core_utilisation.php?'
        . http_build_query($query);
}


/*
|--------------------------------------------------------------------------
| CURRENT ZONE NAME
|--------------------------------------------------------------------------
*/

$currentZoneName = 'All Zones';

if (!$canViewAllRoutes) {

    $stmt = $pdo->prepare("
        SELECT zone_name
        FROM zones
        WHERE id = ?
        LIMIT 1
    ");

    $stmt->execute([
        $userZoneId
    ]);

    $currentZoneName =
        (string)(
            $stmt->fetchColumn()
            ?: 'Zone Not Assigned'
        );
}

?>


<!-- =========================================================
     PAGE HEADER
========================================================= -->

<div class="d-flex justify-content-between align-items-center mb-3">

    <div>

        <h1 class="mb-1">
            Core Utilisation
        </h1>

        <div class="text-muted">

            <i class="fas fa-globe-asia"></i>

            <?= e($currentZoneName) ?>

        </div>

    </div>


    <a
        href="export_excel.php"
        class="btn btn-success"
    >

        <i class="fas fa-file-excel"></i>

        Download Excel

    </a>

</div>


<!-- =========================================================
     SUMMARY
========================================================= -->

<div class="mb-3">

    <span class="text-muted">

        <?= number_format($totalRoutes) ?>

        route<?= $totalRoutes === 1 ? '' : 's' ?>

    </span>

</div>


<!-- =========================================================
     SEARCH
========================================================= -->

<div class="card">

    <div class="card-body">

        <form
            method="get"
            action="core_utilisation.php"
        >

            <div class="input-group">

                <input
                    type="search"
                    name="search"
                    class="form-control"
                    value="<?= e($search) ?>"
                    placeholder="Search route, cable 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="core_utilisation.php"
                            class="btn btn-secondary"
                        >

                            Clear

                        </a>

                    <?php endif; ?>

                </div>

            </div>

        </form>

    </div>


<!-- =========================================================
     TABLE
========================================================= -->

    <div class="card-body p-0">

        <div class="table-responsive">

            <table class="table table-bordered table-hover mb-0">

                <thead>

                    <tr>

                        <th>
                            Route
                        </th>

                        <th>
                            Cable
                        </th>

                        <th>
                            Total
                        </th>

                        <th>
                            Used
                        </th>

                        <th>
                            Free
                        </th>

                        <th>
                            Faulty
                        </th>

                        <th>
                            Util %
                        </th>

                        <th>
                            Spare %
                        </th>

                        <th>
                            Fault %
                        </th>

                        <th>
                        </th>

                    </tr>

                </thead>


                <tbody>


                <?php if (!$routes): ?>

                    <tr>

                        <td
                            colspan="10"
                            class="text-center text-muted py-5"
                        >

                            <i
                                class="fas fa-route fa-2x mb-3"
                            ></i>

                            <br>

                            <strong>
                                No routes found.
                            </strong>

                            <br>

                            <?php if (!$canViewAllRoutes): ?>

                                <small>

                                    Only routes assigned to
                                    <strong>
                                        <?= e($currentZoneName) ?>
                                    </strong>
                                    are displayed.

                                </small>

                            <?php endif; ?>

                        </td>

                    </tr>

                <?php else: ?>


                    <?php foreach ($routes as $r): ?>

                        <?php

                        $total =
                            (int)$r['core_count'];

                        $used =
                            (int)$r['used_count'];

                        $free =
                            (int)$r['free_count'];

                        $faulty =
                            (int)$r['faulty_count'];


                        $util =
                            $total > 0
                                ? round(
                                    (
                                        $used
                                        /
                                        $total
                                    ) * 100,
                                    1
                                )
                                : 0;


                        $spare =
                            $total > 0
                                ? round(
                                    (
                                        $free
                                        /
                                        $total
                                    ) * 100,
                                    1
                                )
                                : 0;


                        $fault =
                            $total > 0
                                ? round(
                                    (
                                        $faulty
                                        /
                                        $total
                                    ) * 100,
                                    1
                                )
                                : 0;

                        ?>


                        <tr>


                            <!-- ROUTE -->

                            <td>

                                <strong>

                                    <?= e(
                                        $r['route_name']
                                    ) ?>

                                </strong>

                            </td>


                            <!-- CABLE -->

                            <td>

                                <?= e(
                                    $r['cable_name']
                                ) ?>

                            </td>


                            <!-- TOTAL -->

                            <td>

                                <?= $total ?>

                            </td>


                            <!-- USED -->

                            <td>

                                <?= $used ?>

                            </td>


                            <!-- FREE -->

                            <td>

                                <?= $free ?>

                            </td>


                            <!-- FAULTY -->

                            <td>

                                <?= $faulty ?>

                            </td>


                            <!-- UTIL -->

                            <td>

                                <span
                                    class="badge badge-<?=
                                        $util >= 70
                                            ? 'danger'
                                            : (
                                                $util >= 40
                                                    ? 'warning'
                                                    : 'success'
                                            )
                                    ?>"
                                >

                                    <?= $util ?>%

                                </span>

                            </td>


                            <!-- SPARE -->

                            <td>

                                <?= $spare ?>%

                            </td>


                            <!-- FAULT -->

                            <td>

                                <?= $fault ?>%

                            </td>


                            <!-- OPEN -->

                            <td class="text-nowrap">

                                <a
                                    href="route_detail.php?id=<?= (int)$r['id'] ?>"
                                    class="btn btn-sm btn-primary"
                                >

                                    <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"
            >


                <div class="text-muted mb-2">

                    Showing

                    <strong>
                        <?= $offset + 1 ?>
                    </strong>

                    -

                    <strong>
                        <?= min(
                            $offset + $perPage,
                            $totalRoutes
                        ) ?>
                    </strong>

                    of

                    <strong>
                        <?= $totalRoutes ?>
                    </strong>

                    routes

                </div>


                <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(
                                        core_utilisation_page_url(
                                            $page - 1,
                                            $search
                                        )
                                    ) ?>"
                                >

                                    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(
                                        core_utilisation_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(
                                        core_utilisation_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>


<?php require_once '_footer.php'; ?>