<?php

include 'db.class.php';
include 'qr.class.php';
include 'strings.class.php';

session_start();



if (!isset($_SESSION['username'])) {
    header("location:login.php");
}

if (!isset($_SESSION['array'])) {
    $_SESSION['array'] = array();
}

$SkipBackButtonArr = [
    '/inspections.php',
    '/jobcard.php',
    '/open_jobcard.php',
    '/fuel_step_a.php',
    '/fuel_step_b.php',
    '/fuel_report.php',

];

$ScriptName = $_SERVER['SCRIPT_NAME'];
// echo $ScriptName;
if (!in_array($ScriptName, $SkipBackButtonArr)) {

    //add or edit dont add to array
    //scripts where the script name is singular dont add
    //scripts that contain save dont add to array

    //Only add to array if currenturl doesnt match the last url in the array
    //&& !strings::contains($ScriptName, "save") && !strings::contains($ScriptName,"add") && !strings::contains($ScriptName,"edit")
    if (!in_array($ScriptName, $_SESSION['array'])) {
        $_SESSION['array'][] = $ScriptName;
    }

    if (20 == count($_SESSION['array'])) {
        array_shift($_SESSION['array']);
    }
}

// var_dump($_SESSION['array']);

if (isset($_POST['BACK'])) {

    $last_index_value = count($_SESSION['array']) - 2;
    unset($_SESSION['array'][$last_index_value + 1]);

    $url = $_SESSION['array'][$last_index_value];

    echo "<script>window.location = '$url';</script>";
}



class html
{


    function __construct($title)
    {
        ?>
        <html>

        <head>
            <title><? echo strtoupper($title); ?></title>
            <link rel="stylesheet" type="text/css" href="styles/stylev1_4.css?v=2.2">
            <meta content="width=device-width, initial-scale=1" name="viewport" />

        </head>

        <body>
            <div class='header'>
                <div class='page'>
                    <? if (strtoupper($title) == 'HOME') { ?>
                        <a href='index.php?logout'>
                            <div class='page'>
                                LOG OUT
                            </div>
                        </a>
                    <? } else { ?>
                        <div class='page'>
                            <? echo strtoupper($title); ?>
                        </div>
                    <? } ?>
                </div>

                <div class='header_logo'><img src="../images/logo.svg" width='20%' onclick="window.location.href='home.php'"
                        style='border-radius:1vw;' /></div>

                <div class='username'>
                    <?php echo $_SESSION['username']; ?>
                </div>

                <?php

                // if ($_SERVER['REQUEST_URI'] != '/home.php') {
        
                ?>
                <dev class="back_button">

                    <input type="SUBMIT" name="BACK" onclick="window.location.href = 'home.php'" value="BACK" class="form_btn"
                        id="back_button" />
                </dev>

                <?php //} ?>

                <script>
                    function home() {
                        window.location.href = 'index.php';
                    }
                </script>
            </div>
            <?php
    }

    function loading($unique_id, $id_of_element)
    { ?>

            <script>
                function first_step_<? echo $unique_id; ?>() {
                    // console.log(document.getElementById('btn_{$jobcard_info['record_id']}').value.length);
                    if (document.getElementById('<? echo $id_of_element; ?>_<? echo $unique_id; ?>').value.length == 10) {
                        document.getElementById('<? echo $id_of_element; ?>_<? echo $unique_id; ?>').value = 'LOADING';
                    } else if (document.getElementById('<? echo $id_of_element; ?>_<? echo $unique_id; ?>').value.length == 7) {
                        document.getElementById('<? echo $id_of_element; ?>_<? echo $unique_id; ?>').value = 'LOADING.';
                    } else if (document.getElementById('<? echo $id_of_element; ?>_<? echo $unique_id; ?>').value.length == 8) {
                        document.getElementById('<? echo $id_of_element; ?>_<? echo $unique_id; ?>').value = 'LOADING..';
                    } else if (document.getElementById('<? echo $id_of_element; ?>_<? echo $unique_id; ?>').value.length == 9) {
                        document.getElementById('<? echo $id_of_element; ?>_<? echo $unique_id; ?>').value = 'LOADING...';
                    }
                }

                function LOADING_<? echo $unique_id; ?>() {
                    document.getElementById('<? echo $id_of_element; ?>_<? echo $unique_id; ?>').value = 'LOADING...';
                    setInterval(first_step_<? echo $unique_id; ?>, 500);
                }
            </script>
        <? }

    public function QRrender($idTag, $function)
    {
        $this->idTag = $idTag;
        $idTag = htmlspecialchars($this->idTag, ENT_QUOTES, 'UTF-8');
        ?>
            <div id="scanner-container">
                <button id="start-scanner" class="form_btn">SCAN</button>
                <div id="reader" style="width: 300px; height: 300px; display: none; margin-left:auto; margin-right:aut">
                    <video id="video" width="300" height="300" style="border: 1px solid black;"></video>
                </div>
            </div>
            <script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.js"></script>
            <script>
                document.getElementById('start-scanner').addEventListener('click', function () {
                    const scannerElement = document.getElementById('reader');
                    const video = document.getElementById('video');

                    // Make the video element visible
                    scannerElement.style.display = 'block';

                    // Request camera access
                    navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } })
                        .then((stream) => {
                            video.srcObject = stream;
                            video.play();

                            // Once the video starts playing, begin scanning for QR codes
                            video.onplay = function () {
                                scanQRCode(video);
                            };
                        })
                        .catch((err) => {
                            console.error("Error accessing webcam:", err);
                        });

                    // Function to scan the QR code
                    function scanQRCode(video) {
                        const canvas = document.createElement("canvas");
                        const context = canvas.getContext("2d");

                        // Set the canvas size to match the video feed
                        canvas.width = video.width;
                        canvas.height = video.height;

                        // Capture the video frame and process it
                        function processFrame() {
                            // Draw the current frame to the canvas
                            context.drawImage(video, 0, 0, canvas.width, canvas.height);

                            // Get the image data from the canvas
                            const imageData = context.getImageData(0, 0, canvas.width, canvas.height);

                            // Invert the colors (black becomes white, white becomes black)
                            invertColors(imageData);

                            // Attempt to decode the QR code from the image data
                            const qrCode = jsQR(imageData.data, canvas.width, canvas.height);

                            // If a QR code is found
                            if (qrCode) {
                                // Insert result into the input field
                                document.getElementById('<?php echo $idTag; ?>').value = qrCode.data;
                                document.getElementById('start-scanner').innerHTML = qrCode.data;
                                alert("Scanned Code: " + qrCode.data);
                                // Stop scanning
                                video.srcObject.getTracks().forEach(track => track.stop());
                                scannerElement.style.display = 'none';
                                <?php echo $function; ?>();
                            } else {
                                // Continue scanning
                                requestAnimationFrame(processFrame);
                            }
                        }

                        // Start processing the video feed
                        processFrame();
                    }

                    // Function to invert the colors of the image
                    function invertColors(imageData) {
                        const data = imageData.data;

                        for (let i = 0; i < data.length; i += 4) {
                            // Invert colors: R, G, B
                            data[i] = 255 - data[i];     // Red
                            data[i + 1] = 255 - data[i + 1]; // Green
                            data[i + 2] = 255 - data[i + 2]; // Blue
                        }

                        // Update the image data
                        imageData.data = data;
                    }
                });
            </script>
            <?php
    }


    function block($redirect, $name)
    {
        ?>

            <a href='<?php echo $redirect; ?>'>
                <div class='icons'>
                    <?php echo strtoupper($name); ?>
                </div>
            </a>
            <?
    }

    function http_get_curl($url, $get_variables_array, $get_values_array)
    {
        $get_variables_array[] = 'username';
        $get_variables_array[] = 'password';
        $get_values_array[] = 'MUX01';
        $get_values_array[] = 'MUX01!@';
        $index = 0;
        $get_vars = "?";
        foreach ($get_variables_array as $variables) {
            $get_vars = $get_vars . $variables . "=" . $get_values_array[$index] . "&";
            $index++;
        }

        $url = $url . $get_vars;
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        $resp = curl_exec($curl);
        curl_close($curl);

        return $resp;
    }

    function pie_chart($amount)
    {
        ?>
            <style>
                @property --p {
                    syntax: '<number>';
                    inherits: true;
                    initial-value: 1;
                }

                .pie {
                    --p: 20;
                    --b: 22px;
                    --c: darkred;
                    --w: 150px;

                    width: var(--w);
                    aspect-ratio: 1;
                    position: relative;
                    display: inline-grid;
                    margin: 5px;
                    place-content: center;
                    font-size: 25px;
                    font-weight: bold;
                    font-family: sans-serif;
                }

                .pie:before,
                .pie:after {
                    content: "";
                    position: absolute;
                    border-radius: 50%;
                }

                .pie:before {
                    inset: 0;
                    background:
                        radial-gradient(farthest-side, var(--c) 98%, #0000) top/var(--b) var(--b) no-repeat,
                        conic-gradient(var(--c) calc(var(--p)*1%), #0000 0);
                    -webkit-mask: radial-gradient(farthest-side, #0000 calc(99% - var(--b)), #000 calc(100% - var(--b)));
                    mask: radial-gradient(farthest-side, #0000 calc(99% - var(--b)), #000 calc(100% - var(--b)));
                }

                .pie:after {
                    inset: calc(50% - var(--b)/2);
                    background: var(--c);
                    transform: rotate(calc(var(--p)*3.6deg)) translateY(calc(50% - var(--w)/2));
                }

                .animate {
                    animation: p 1s .5s both;
                }

                .no-round:before {
                    background-size: 0 0, auto;
                }

                .no-round:after {
                    content: none;
                }

                @keyframes p {
                    from {
                        --p: 0
                    }
                }
            </style>


            <div class="pie animate no-round" style="--p:<? echo $amount; ?>;--c:orange;"><? echo $amount; ?>%</div>

            <?
    }
}
