<?php
defined(page_security_key) or exit;

if (debug && debug_id == $_SESSION['id']){
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);  
}

include_once './assets/functions.php';
include_once './settings/settings_redirector.php';

$page = 'buildtool';
//Check if allowed
if (isAllowed($page,$_SESSION['profile'],$_SESSION['permission'],'R') === 0){
    header('location: index.php');
    exit;
}
$bearertoken = createCommunicationToken($_SESSION['userkey']);

//GET PRODUCTS FROM DB
$pdo = dbConnect($dbname);
$sql = 'SELECT rowID, productcode, productname, product_category,sn from products where status = "1" and build = "1"';
$stmt = $pdo->prepare($sql);
//Excute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

template_header('Buildtool', 'buildtool','view');

$view = '
<div class="content-title">
    <div class="title">
        <i class="fa-solid fa-box-open"></i>
        <div class="txt">
            <h2>'.$buildtool_h2 .'</h2>
            <p>'.$buildtool_p.'</p>
        </div>
    </div>
</div>';

$view .= '
    <div class="content-header responsive-flex-column pad-top-5">
        <a href="index.php?page=dashboard" class="btn">'.$button_cancel.'</a>
     </div>
';

$view .= '<div class="content-block">
    <div class="block-header">
        <i class="fa-solid fa-bars fa-sm"></i><span id="time">25:00</span>
    </div>
    <p id="servicetoken" value="" hidden>'.$bearertoken.'</p>
    <div>
    <select id="productlist" style="width: 100%;padding: 15px 5px;margin-bottom: 25px;border: 0;border-bottom: 1px solid #dedfe1;" name="productlist" onchange="storeProduct()">
        <option selected value="0">Assign Product</option>
    ';
    //GET DEFAULT VALUE FROM SESSION STORAGE
    $view .=' <option id="productselected" selected value="0">Assign Product</option>';
    
    foreach ($messages as $message){   
        $view .='<option value="'.$message["rowID"].'|'.$message["product_category"].'|'.$message["sn"].'">'.$message["productcode"].' - '.(${$message["productname"]} ?? $message["productname"]).'</option>';
    }

$view .='</select>
        <input type="hidden" id="lineToSend" >
        <input id="plug_data" type="hidden" value="">
    </div>
    <div id="connectdevice" style="display:flex;">
      <div>
        <button class="btn" style="margin-right:10px;" onclick="startMaintenance()">Assembly</button>
        <button class="btn" onClick="window.location.reload()">&#8634;</button>
      </div>
      <div id="readStatus" style="width: 75%;background-color: #f1f1f1;">
        <div id="readBar"></div>
      </div>
    </div>
    <div id="Device_output" style="display:none;margin-top: 10px;">
      <div id="serialResults" style="font-family: monospace;white-space: pre;padding: 10px;background-color:#f1f1f1;"></div>    
    </div>
    <div>
</div>
';


//OUTPUT
echo $view;

//ADD JS FILES
echo '
<script src = "./assets/readdevice.js?'.script_version.'"></script>
<script src = "./assets/charts.js?'.script_version.'"></script>
<script src = "./assets/jquery-2.1.4.min.js"></script>
<script src = "./assets/DYMO.Label.Framework.latest.js?'.script_version.'" type="text/javascript" charset="UTF-8"> </script>
<script>
	var link = "'.$baseurl.'";

    function startTimer(duration, display) {
        var timer = duration, minutes, seconds;
        setInterval(function () {
            minutes = parseInt(timer / 60, 10);
            seconds = parseInt(timer % 60, 10);
    
            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;
    
            display.textContent = minutes + ":" + seconds;
    
            if (timer === 60) {
                // Show a popup when the timer reaches 60 seconds
                alert("'.($message_build ?? 'Please login again').'");
            }
            if (--timer < 0) {
                timer = duration;
            }
        }, 1000);
    }
    
    window.onload = function () {
        var startMinute = 60 * 25,
            display = document.querySelector(\'#time\');
        startTimer(startMinute, display);
    };

    if (sessionStorage["productvalue"] && sessionStorage["productvalue"].length != 0){
        document.getElementById("productselected").value = sessionStorage.getItem("productvalue");
        document.getElementById("productselected").innerHTML = sessionStorage.getItem("producttext") ;
    }

    function storeProduct(){
        var product = document.getElementById("productlist");
        var productSelected = product.options[product.selectedIndex].value;
        var productSelectedText = product.options[product.selectedIndex].innerHTML;
        sessionStorage.setItem("productvalue", productSelected);
        sessionStorage.setItem("producttext", productSelectedText);
    }


</script>';


template_footer();
?>