<?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';
include_once './settings/systemcartest.php';

$page = 'cartest_manage';
//Check if allowed
if (isAllowed($page,$_SESSION['profile'],$_SESSION['permission'],'R') === 0){
    header('location: index.php');
    exit;
}
//PAGE Security
$update_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'U');
$delete_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'D');
$create_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'C');

$bearertoken = createCommunicationToken($_SESSION['userkey']);

$rowID = $_GET['rowID'] ?? '';

if ($rowID !=''){
    $url = 'index.php?page=cartest&rowID='.$rowID.'';
} else {
    $url = 'index.php?page=cartests';
}

// Default input product values
$cartest = [
    'rowID' => '',
    'carbrand' => '',
    'cartype' => '',
    'header' => [
        'CarVIN' => '',
        'year' => '',
        'NameTester'=> $_SESSION['username'],
        'SN' =>'',
        'HW' =>'',
        'FW' =>''
    ],
    'questions' => [
        'cartest_19' => '',
        'cartest_20' => '',
        'cartest_22' => ''
    ],
    'datapoints' => [],
    'created' => ''
];

if (isset($_GET['rowID'])) {
    // ID param exists, edit an existing product
       //CALL TO API
       $api_url = '/v1/cartests/rowID='.$_GET['rowID'];
       $responses = ioServer($api_url,'');
       //Decode Payload
       if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = null;}
       
       $cartest = json_decode(json_encode($responses[0]), true);

       $cartest['header'] = (is_string($cartest['header']))? json_decode($cartest['header'],true) : ''; 
       $cartest['questions'] = (is_string($cartest['questions']))? json_decode($cartest['questions'],true) : ''; 
       $cartest['datapoints'] = (is_string($cartest['datapoints']))? json_decode($cartest['datapoints'],true) : ''; 

    if ($update_allowed === 1){
        if (isset($_POST['submit'])) {
            //UPLOAD ALL PICTURES
            foreach ($_FILES["fileToUpload"]["name"] as $key => $value){
                //ONLY UPDATE PICTURES IF SOMETHING IS RETURNED
                if($value !='' || !empty($value)){
                    uploadrequest($key);
                }
             }
            //ARRAY convert to JSON
            $_POST['header'] = json_encode($_POST['header'], JSON_UNESCAPED_UNICODE);
            $_POST['questions'] = json_encode($_POST['questions'], JSON_UNESCAPED_UNICODE);
       
            //CHECK IF DATAPOINTS IS NOT EMPTY THEN UPDATE IF NOT REMOVE EMPTY ARRAY FROM POST         
            if (!empty($_POST['datapoints']) || $_POST['datapoints'] !="") {
                $_POST['datapoints'] = json_encode($_POST['datapoints'], JSON_UNESCAPED_UNICODE);
            }
            else {
                unset($_POST['datapoints']);
            }
            
             //GET ALL POST DATA
            $data = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            //Secure data
            $payload = generate_payload($data);
            //API call
            $responses = ioServer('/v1/cartests', $payload);
            if ($responses === 'NOK'){

            } else {
            header('Location: index.php?page=cartest&rowID='.$_GET['rowID'].'&success_msg=2');
            exit;
            }
        }
    }
    
    if ($delete_allowed === 1){
        if (isset($_POST['delete'])) {
            //GET ALL POST DATA
            $data = json_encode($_POST , JSON_UNESCAPED_UNICODE);
            //Secure data
            $payload = generate_payload($data);
            //API call
            $responses = ioServer('/v1/cartests', $payload);
            // Redirect and delete equipment
            if ($responses === 'NOK'){

            } else {
            header('Location: index.php?page=cartests&success_msg=3');
            exit;
            }
        }
    }
   
} else {
    // Create a new equipment
    if (isset($_POST['submit'])) {
        //UPLOAD ALL PICTURES
        foreach ($_FILES["fileToUpload"]["name"] as $key => $value){
        //ONLY UPDATE PICTURES IF SOMETHING IS RETURNED
        if($value !='' || !empty($value)){
            uploadrequest($key);
        }
        }
        //ARRAY convert to JSON
        $_POST['header'] = json_encode($_POST['header'], JSON_UNESCAPED_UNICODE);
        $_POST['questions'] = json_encode($_POST['questions'], JSON_UNESCAPED_UNICODE);
        $_POST['datapoints'] = json_encode($_POST['datapoints'], JSON_UNESCAPED_UNICODE);
        //GET ALL POST DATA
        $data = json_encode($_POST, JSON_UNESCAPED_UNICODE);
        //Secure data
        $payload = generate_payload($data);
        //API call
        $responses = ioServer('/v1/cartests', $payload);
        if ($responses === 'NOK'){

        } else {
        header('Location: index.php?page=cartests&success_msg=1');
        exit;
        }
    }
}

//CREATE CARTEST BRAND DROPDOWN
$carbrands_input ='
   
    <select id="carbrands" name="carbrand">';
//CHECK IF BRAND IS PROVIDED
if ($cartest['carbrand'] !='' && !empty($cartest['carbrand'])){
    $carbrands_input .=  '<option value="'.$cartest['carbrand'].'" selected>'.$cartest['carbrand'].'</option>';
} else {
    $carbrands_input .=  '<option></option>';
}

foreach ($carbrands_array as $brand) {
    $carbrands_input .= '<option value="'.$brand.'">'.$brand.'</option>';
}
$carbrands_input .= '</select>';
//END CARBRAND DROPDOWN

template_header('Cartesttool', 'cartesttool','manage');

$view ='
<form action="" method="post" enctype="multipart/form-data">
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100"><?=$page?>'.$cartest_h2.'</h2>
        <a href="'.$url .'" class="btn alt mar-right-2">'.$button_cancel.'</a>
    ';

if ($delete_allowed === 1){
    $view .= '<input type="submit" name="delete" value="Delete" class="btn red mar-right-2" onclick="return confirm(\'Are you sure you want to delete this cartest?\')">';
}
if ($update_allowed === 1){
    $view .= '<input type="submit" name="submit" value="Save" class="btn">';
}
    
$view .= '</div>';
$view .= '<div class="content-block-wrapper">';
$view .= '  <div class="content-block order-details">
                <div class="block-header">
                <i class="fa-solid fa-circle-info"></i></i>'.$cartest_information.'
                </div>
                <div class="order-detail">
                    <h3>'.$cartest_carvin.'</h3>
                    <p><input id="VIN" type="text" name="header[CarVIN]" onchange="decodeVIN()" value="'.$cartest['header']['CarVIN'].'"></p>
                    <p id="token" value="" hidden>'.$bearertoken.'</p>
                </div>
                <div class="order-detail">
                    <h3>'.$cartest_carbrand.'</h3>
                    <p>'.$carbrands_input.'
                        <input type="hidden" name="rowID" value="'.$rowID.'">
                    </p>
                </div>
                <div class="order-detail">
                    <h3>'.$cartest_cartype.'</h3>
                    <p><input type="text" name="cartype" value="'.$cartest['cartype'].'"></p>
                </div>
                 <div class="order-detail">
                    <h3>'.$general_year.'</h3>
                    <p><input id="year" type="text" name="header[year]" value="'.$cartest['header']['year'].'"></p>
                </div>
              </div>
';

$view .='<div class="content-block order-details">
            <div class="block-header">
                <i class="fa-solid fa-user fa-sm"></i>'.$cartest_details_text.'
            </div>
            <div class="order-detail">
                    <h3>'.$cartest_created.'</h3>
                    <p>'.$cartest['created'].'</p>
            </div>
            <div class="order-detail">
                    <h3>'.$cartest_tester.'</h3>
                    <p><input type="text" name="header[NameTester]" value="'.$cartest['header']['NameTester'].'"></p>
            </div>
            <div class="order-detail">
                    <h3>'.$cartest_device.'</h3>
                    <p><input type="text" name="header[SN]" value="'.$cartest['header']['SN'].'"></p>
            </div>
            <div class="order-detail">
                    <h3>'.$cartest_device_hw.'</h3>
                    <p><input type="text" name="header[HW]" value="'.$cartest['header']['HW'].'"></p>
            </div>
            <div class="order-detail">
                    <h3>'.$cartest_device_sw.'</h3>
                    <p><input type="text" name="header[FW]" value="'.$cartest['header']['FW'].'"></p>
            </div>
        </div>';
$view .= '</div>';
// -------------------------------
//BUILD TO INPUT FORM BASED ON ARRAY
// ------------------------------

$view .= '<div class="tabs">';
foreach($arrayQuestions_cartest as $group){

    if ($group['Group_sequence'] == 1){
         $view .= '<a href="#" class="active">'.$group['Group'].'</a>';
    } else {
        $view .= '<a href="#">'.$group['Group'].'</a>';
    }
}
$view .= '</div>';    
    
foreach($arrayQuestions_cartest as $group){    
  
    if ($group['Group_sequence'] == 1){
        $view .= '<div class="content-block tab-content active">
                    <div class="form responsive-width-100">';
   } else {
        $view .= '<div class="content-block tab-content">
                    <div class="form responsive-width-100">';
   }
    
    foreach($group['Questions_in_group'] as $question){
      
      switch ($question['Type']) {
        case 'dropdown':
          $view .= '<label for="" id="'.$question['QuestionID'].'">'.$question['Question'].'</label>';
          $view .= '<select id="" name="questions['.$question['QuestionID'].']" required>';
          $view .= '<option value=>'.$cartest_allowed_label0.'</option>';  
          foreach ($question['Response'] as $response){
                    $view .= '<option value="'.$response['responseID'].'" '.((isset($cartest['questions'][$question['QuestionID']]) && $cartest['questions'][$question['QuestionID']] == $response['responseID'])? 'selected':'').'>'.$response['Response'].'</option>';  
          }
          $view .= '</select>';
          break;

        case 'textarea':
          $view .= '<label for="" id="'.$question['QuestionID'].'">'.$question['Question'].'</label>';
          $view .= '<textarea id="QuestionID" name="questions['.$question['QuestionID'].']" placeholder="">'.(isset($cartest['questions'][$question['QuestionID']])?$cartest['questions'][$question['QuestionID']]:'').'</textarea>';
        break;

        case 'file';
            $view .= '<label for="" id="">'.$question['Question'].'</label>';

            if ($question['QuestionID'] !=''){
                $view .= '<input type="hidden" name="questions['.$question['QuestionID'].']" value="'.$cartest['questions'][$question['QuestionID']].'" />
                          <input type="file" name="fileToUpload['.$question['QuestionID'].']" onchange="preview('.$question['QuestionID'].')" style="width: 30%;padding: 50px 0 0 0;height: 10px;"><img id="'.$question['QuestionID'].'" src="'.$cartest['questions'][$question['QuestionID']].'" width="150px"/>';
            } else {
                $view .= '<input type="file" name="fileToUpload['.$question['QuestionID'].']" onchange="preview('.$question['QuestionID'].')" style="width: 30%;padding: 50px 0 0 0;height: 10px;" required><img id="'.$question['QuestionID'].'" src="" width="150px"/>';
            }
        
            break;
      }
    }
  $view .= '    </div>
            </div>';
} 
//CAPTURE DATA FROM PLUG

$view .= '<input id="plug_data" type="hidden" name="datapoints" value="">';

$view .= '</form>';

$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>
        <input type="hidden" id="lineToSend" >
    
    <div id="connectdevice" style="display:flex;">
      <div>
        <button class="btn" style="margin-right:10px;" onclick="connectSerial();startGraph()">Connect</button>
        <button class="btn" id="clear" onclick="closePortCarTest()" style="">X</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="margin-top: 10px;">
       <div><canvas id="chart_VCP" style="width:400px;max-width:100%"></canvas></div>
       <p><small>STATE: -5 = WAIT_CONNECT, 0 = DISCONNECTED, 3 = REACTIVATE, 5 = FULL_CONNECT</small></p> 
    </div>
      <div id="serialResults" style="display:none;font-family: monospace;white-space: pre;padding: 10px;background-color:#f1f1f1;"></div>    
    </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 startGraph(){
        setInterval(renderChart,5000);
    }

    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 < 0) {
                timer = duration;
            }
        }, 1000);
    }
    
    window.onload = function () {
        var startMinute = 60 * 25,
            display = document.querySelector(\'#time\');
        startTimer(startMinute, display);
    };

function preview(id) {
   id.src=URL.createObjectURL(event.target.files[0]);
}

</script>
';



template_footer();
?>