summaryrefslogtreecommitdiff
path: root/lib/alert.php
blob: 7aa8d32e95e643f7dee0ac09b99c6ac54ea2a700 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
include_once "{$_SERVER['DOCUMENT_ROOT']}/lib/utils.php";

function generate_alert(string $path, string $error, int $status = 400)
{
    http_response_code($status);

    if (isset($_SERVER["HTTP_ACCEPT"]) && $_SERVER["HTTP_ACCEPT"] == "application/json") {
        header("Content-Type: application/json");
        echo json_encode([
            "status_code" => $status,
            "message" => $error,
            "data" => null
        ]);
    } else {
        if (session_status() != PHP_SESSION_ACTIVE)
            session_start();
        $_SESSION['alert'] = [
            'code' => $status,
            'reason' => $error
        ];
        header("Location: $path");
    }
}

function display_alert()
{
    if (!isset($_SESSION["alert"])) {
        return;
    }

    $alert = $_SESSION["alert"];
    unset($_SESSION["alert"]);

    $status = $alert["code"];
    $reason = str_safe($alert["reason"], 100);
    $ok = substr($status, 0, 1) == '2';

    echo '' ?>
    <div class="box row alert <?= $ok ? '' : 'red' ?>" style="gap:8px;" id="alert-box">
        <img src="/static/img/icons/<?= $ok ? 'yes' : 'no' ?>.png" alt="">
        <p><b><?= $reason ?></b></p>
    </div>
    <script>
        setTimeout(() => {
            const alertBox = document.getElementById("alert-box");
            alertBox.remove();
        }, 5000);
    </script>
    <?php ;
}