<?php

require 'conn/codeblocs.php';


$get = $_GET ?? '';
//preprint($get);

if(!isset($get['tkstr'])){
    echo '<div style="text-align:center; padding:3em">Error: No token found</div>';
    return;

}
$G = json_decode(base64_decode($get['tkstr']), true);
// preprint($G);

// $survey_instance = 2;
$survey_slug = $G['survey'] ?? '';
$survey_token = $G['token'] ?? '';
$survey_vendee = $G['vendee'] ?? 'our Hospital';


if( empty($survey_slug) || empty($survey_token)){
  echo '<div style="text-align:center; padding:3em">Error: The survey could not be identified.</div>';
  return;

}

$vendee = SW('*', 'survey_vendee', 'short_vendee = ? AND suspended = 0 LIMIT 1', 1, 1, [$survey_vendee]);

if( empty($vendee['vendee_id']) ){
  echo '<div style="text-align:center; padding:3em">Error: An authorized entity could not be found.</div>';
  return;
}else{
  // preprint($vendee);
  $survey_vendee_id = $vendee['vendee_id'];
  $survey_vendee_email = $vendee['email'];

}
// $survey = SW('*', 'survey_instance', 'survey_id = ?', 1, 1, [$survey_instance]);
$survey = SW('*', 'survey_instance', 'survey_slug = ?', 1, 1, [$survey_slug]);
// preprint($survey);
$survey_instance = $survey['survey_id'];


$response_batch_insitu = SW('COUNT(*)', 'survey_response_batch', 'response_token = ? AND vendee_id = ?', 0, 0, [$survey_token, $survey_vendee_id]);
// preprint($response_batch_insitu);


if( $response_batch_insitu ){
  echo '<div style="text-align:center; padding:3em">Error: This token has already been used.</div>';
  return;

}
// preprint($response_batch_insitu);


$scales = doPDOQ("SELECT rating_scale_id, rating_scale_name FROM rating_scales", []);
// preprint($scales);

$rankarr = [];
foreach($scales as $scale){
  // preprint($scale['rating_scale_name']);
  $scale_options = doPDOQ("SELECT scale_option_id, scale_option_rank, scale_option FROM rating_scale_options WHERE rating_scale_id = ?", [$scale['rating_scale_id']]);
  // preprint($scale_options);
  $rankarr[$scale['rating_scale_id']] = array_column($scale_options, 'scale_option', 'scale_option_rank');
}
// preprint($rankarr);



$sections = doPDOQ("SELECT section_id, section_name, section_descr FROM survey_instance_section WHERE survey_id = ?", [$survey_instance]);
// preprint($sections);

$questions = [];
foreach ($sections as $section) {
  // preprint($section);
  $quests = doPDOQ("SELECT question_id, question_name, question_datatype, rating_scale_id FROM survey_questions WHERE section_id = ?", [$section['section_id']]);
  // preprint($questions);
  foreach($quests as $quest){
    $questions[$quest['question_id']] = $quest;
    // preprint($quest);
    $questions[$quest['question_id']]['scale'] = $rankarr[ $quest['rating_scale_id'] ] ?? '';
  }

}
// preprint($questions);




?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html class="supernova"><head>

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, user-scalable=1" />
<meta name="HandheldFriendly" content="true" />
<title><?=$survey_vendee?> Follow Up Survey</title>

<link rel="shortcut icon" href="assets/img/swiftpractice_favicon.png" />
<style type="text/css">
    @media print{.form-section{display:inline!important}.form-pagebreak{display:none!important}.form-section-closed{height:auto!important}.page-section{position:initial!important}}
</style>
<link type="text/css" rel="stylesheet" href="assets/styles/surveytemplates.css"/>
<style type="text/css" id="form-designer-style">
    /* Injected CSS Code */
@import "https://fonts.googleapis.com/css?family=Candal:light,lightitalic,normal,italic,bold,bolditalic";

*,
*:after,
*:before {
  box-sizing: border-box;
}
.form-all {
  font-family: "Inter", sans-serif;
}
.main .jotform-form {
  width: 100%;
  padding: 0 3%;
}
.form-all {
  display: flex;
  /* flex-direction: column; */
  width: 100%;
  /* max-width: 752px; */
}
.form-line-active {
  background-color: #ffffe0;
}
.form-all {
  /* font-size: 16px; */
}
li.form-line {
  margin-top: 12px;
  margin-bottom: 12px;
}
.form-line {
  padding: 12px 10px;
}
.form-section {
  padding: 0px 38px;
}
.form-textbox,
.form-textarea,
.form-radio-other-input,
.form-checkbox-other-input,
.form-captcha input,
.form-spinner input {
  background-color: #ffffff;
  color: #0c91df;
}
.form-label {
  font-family: "Inter", sans-serif;
}
.form-line-column {
  width: calc(50% - 8px);
}


input.form-radio:checked+label {
  color: #0c91df;
}

.form-radio-item,
.form-checkbox-item {
  padding-bottom: 0px !important;
}
.form-radio-item:last-child,
.form-checkbox-item:last-child {
  padding-bottom: 0;
}
.form-single-column .form-checkbox-item,
.form-single-column .form-radio-item {
  width: 100%;
}
.form-checkbox-item .editor-container div,
.form-radio-item .editor-container div {
  position: relative;
}
.form-checkbox-item .editor-container div:before,
.form-radio-item .editor-container div:before {
  display: inline-block;
  vertical-align: middle;
  left: 0;
  width: 20px;
  height: 20px;
}
.form-all .form-submit-button,
.form-all .form-submit-print {
  font-size: 16px;
  font-weight: normal;
  font-family: "Inter", sans-serif;
}
.form-all .form-submit-button {
  min-width: 180px;
}
.form-all .form-submit-button.js-new-sacl-button,
.form-all .form-submit-print {
  min-width: 98px;
}
.form-all .form-pagebreak-back,
.form-all .form-pagebreak-next {
  font-family: "Inter", sans-serif;
  font-size: 16px;
  font-weight: normal;
}
.form-all .form-pagebreak-back,
.form-all .form-pagebreak-next {
  min-width: 128px;
}
li[data-type="control_image"] div {
  text-align: left;
}
li[data-type="control_image"] img {
  border: none;
  border-width: 0px !important;
  border-style: solid !important;
  border-color: false !important;
}
.supernova {
  height: 100%;
  background-repeat: no-repeat;
  background-attachment: scroll;
  background-position: center top;
  background-repeat: repeat;
}
.supernova {
  background-image: none;
}
#stage {
  background-image: none;
}
/* | */
.form-all {
  background-repeat: no-repeat;
  background-attachment: scroll;
  background-position: center top;
  background-repeat: repeat;
}
.form-header-group {
  background-repeat: no-repeat;
  background-attachment: scroll;
  background-position: center top;
}
.header-large h1.form-header {
  font-size: 1.6em;
}
.header-large h2.form-header {
  font-size: 1.5em;
}
.header-large h3.form-header {
  font-size: 1.17em;
}
.header-large h1 + .form-subHeader {
  font-size: 1em;
}
.header-large h2 + .form-subHeader {
  font-size: .875em;
}
.header-large h3 + .form-subHeader {
  font-size: .75em;
}
.header-default h1.form-header {
  font-size: 2em;
}
.header-default h2.form-header {
  font-size: 1.5em;
}
.header-default h3.form-header {
  font-size: 1.17em;
}
.header-default h1 + .form-subHeader {
  font-size: 1em;
}
.header-default h2 + .form-subHeader {
  font-size: .875em;
}
.header-default h3 + .form-subHeader {
  font-size: .75em;
}
.header-small h1.form-header {
  font-size: 2em;
}
.header-small h2.form-header {
  font-size: 1.5em;
}
.header-small h3.form-header {
  font-size: 1.17em;
}
.header-small h1 + .form-subHeader {
  font-size: 1em;
}
.header-small h2 + .form-subHeader {
  font-size: .875em;
}
.header-small h3 + .form-subHeader {
  font-size: .75em;
}
.form-header-group {
  text-align: left;
}
.form-header-group {
  font-family: "Candal", sans-serif;
}
div.form-header-group.header-large {
  margin: 0px -38px;
}
div.form-header-group.header-large {
  padding: 40px 52px;
}
.form-header-group .form-header,
.form-header-group .form-subHeader {
  color: #07669d;
}
.form-header-group {
  background-color: #ffffff;
}
.form-line-error {
  overflow: hidden;
  -webkit-transition-property: none;
  -moz-transition-property: none;
  -ms-transition-property: none;
  -o-transition-property: none;
  transition-property: none;
  -webkit-transition-duration: 0.3s;
  -moz-transition-duration: 0.3s;
  -ms-transition-duration: 0.3s;
  -o-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -webkit-transition-timing-function: ease;
  -moz-transition-timing-function: ease;
  -ms-transition-timing-function: ease;
  -o-transition-timing-function: ease;
  transition-timing-function: ease;
  background-color: #fff4f4;
}
.form-line-error .form-error-message {
  background-color: #f23a3c;
  clear: both;
  float: none;
}
.form-line-error .form-error-message .form-error-arrow {
  border-bottom-color: #f23a3c;
}
.form-line-error input:not(#coupon-input),
.form-line-error textarea,
.form-line-error .form-validation-error {
  border: 1px solid #f23a3c;
  box-shadow: 0 0 3px #f23a3c;
}
.supernova {
  background-color: #e5e5e5;
  background-color: #ababab;
}
.supernova body {
  background-color: transparent;
}
.supernova .form-all,
.form-all {
  background-color: #e5e5e5;
}

.form-matrix-table tr {
  border-color: #cccccc;
}
.form-matrix-table tr:nth-child(2n) {
  background-color: #d8d8d8;
}
.form-all {
  color: #78373f;
}
.form-label-top,
.form-label-left,
.form-label-right,
.form-html {
  color: #333;
}
.form-line-error {
  overflow: hidden;
  -webkit-transition-property: none;
  -moz-transition-property: none;
  -ms-transition-property: none;
  -o-transition-property: none;
  transition-property: none;
  -webkit-transition-duration: 0.3s;
  -moz-transition-duration: 0.3s;
  -ms-transition-duration: 0.3s;
  -o-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -webkit-transition-timing-function: ease;
  -moz-transition-timing-function: ease;
  -ms-transition-timing-function: ease;
  -o-transition-timing-function: ease;
  transition-timing-function: ease;
  background-color: #fff4f4;
}

/*__INSPECT_SEPERATOR__*/
.form-header {
    /* font-size : 35px; */
}

#main-survey-postlude{
  display:none;
  width: 60%;
  margin: 10% auto;
  padding:1em 3em 3em;
  background-color :#fff4f4;
  border-radius: 10px;
  text-align: center;
}
#main-survey-postlude div#imgsection {
}
#main-survey-postlude div#mainsection {
  margin-top:1em;
  padding: 0;
}

#intro-band{
  background:#b8d4f199;
  /* margin:0px -38px;  */
  padding: 0 20px 0 30px;
  font-size:smaller;
}

    /* Injected CSS Code */
</style>

<script type="text/javascript">	


</script>
</head>
<body style="">
    <div id="main-survey-wrap">
    <form class="jotform-form" id="main-survey-form" method="post">
    
        <div role="main" class="form-all">
        <style>
          .form-all:before { background: none;}
        </style>


        <div  style="text-align:center;background-color:#f7f7f7; padding: 2em" class="">
          <img src="assets/vdlogos/<?=strtolower($survey_vendee)?>.png" style="display:inline-block; vertical-align:middle"/>
          <div style="display:inline-block;vertical-align:middle">
            <h1 style="margin:0; font-size:1.5em; color:#07669d;"><?=$survey['survey_name']?></h1>
            <h4 style="margin:.5em 0;font-size:smaller; color:#4c99c7"><?=$vendee['vendee_name']?></h4>
          </div>
        </div>

        <div id="intro-band" class="">
              <p><?=str_replace('{VENDEE}', $survey_vendee, $survey['survey_intro'])?></p>
              <input type="hidden" name="postdata" value="1" />
              <input type="hidden" name="survey_vendee_id" value="<?=$survey_vendee_id?>" />
              <input type="hidden" name="survey_id" value="<?=$survey['survey_id']?>" />
              <input type="hidden" name="survey_token" value="<?=$survey_token?>" />
        </div>
  
        <div style="text-align:center; font-style:italic; padding:2em 1em 0 2em; color:#333; font-weight:bold; font-size:bigger;">Please rate your experience in the following areas:</div>
        <ol class="form-section page-section">
          <?php foreach ($questions as $q => $question) : ?>

            <li class="form-line" data-type="control_radio" id="id_5">
            <label class="form-label form-label-top" id="label_5" for="input_5"><?= $question['question_name'] ?></label>
            <div id="cid_5" class="form-input-wide" data-layout="full">
              <div class="form-multiple-column" data-columncount="2" role="group" aria-labelledby="label_5" data-component="radio">


              <?php if($question['scale']):?>
                  
                <?php
                  // preprint($question['scale'])
                ?>
                <?php foreach ($question['scale'] as $r => $rate) : ?>
        
                    <span class="form-radio-item">
                    <span class="dragger-item">
                    </span>
                    <input type="radio" aria-describedby="label_5" class="form-radio" value="<?= $r ?>" id="rate_<?= $q ?>_<?= $r ?>" name="response_data[<?= $q ?>]" required />
                    <label for="rate_<?= $q ?>_<?= $r ?>" class="radio"><?= $r ?> - <?= $rate ?></label>

                    </span>
                <?php endforeach ?>

      

              <?php else:?>


                    <textarea id="input_12" class="form-textarea"  name="response_data[<?=$q?>]" style="width:648px;height:163px" data-component="textarea" aria-labelledby="label_12" placeholder="Enter your comments here"></textarea>

                  
              <?php endif?>
                        </div>
                    </div>
                </li>

            <?php endforeach ?>


        
       </ol>
                 
        <div class="" data-type="control_button" id="id_15">
                <div data-align="auto" class="form-buttons-wrapper form-buttons-auto   jsTest-button-wrapperField">
                  <button id="input_15" type="submit" class="form-submit-button form-submit-button-simple_grey submit-button jf-form-buttons jsTest-submitField" data-component="button" data-content="">
                    Submit
                  </button>
                </div>
            </div>
      </div>
    
      
      <div class="formFooter-heightMask">
      </div>
    </form>
 </div>

 <div id="main-survey-postlude">
    <div id="imgsection">
      <img src="assets/vdlogos/<?=strtolower($survey_vendee)?>.png" style=""/> 
    </div>
    <div id="mainsection">
       Thank you for participating in this feedback activity. <br>We truly appreciate the time you took out on this!</div>

 </div>

<footer style="text-align:center; font-size:smaller">
     Proudly powered by: <a href="https://swiftpracticesoftware.com"> <img src="assets/img/swiftpractice_favicon.png" height="14" /> SwiftPracticeSoftware.com</a>
</footer>

<script src="assets/js/script.js" integrity="" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<?php if( ($_SERVER['SYSTEMROOT']??'') == 'C:\WINDOWS'):?>
    <script src="http://localhost/doc/javascripts/NEW/jquery-2.2.4.min.js" integrity="" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<?php else:?>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<?php endif?>

<script>
    $(function() {
      $('#main-survey-form').submit(function(e) {
        if(!confirm("You are about to submit the feedback, and close it.\nAre you sure you're done?")){
            return false;
        }
        e.preventDefault();
        let data = $(this).serialize();
        // console.log(data);
        $(this).find('button.form-submit-button').text('Please wait...');

        $.post("survey-form-submit.php", data, function(o) {
            // console.log(o);
            // return false;

            if(true){
              $('#main-survey-wrap').remove();
              $('#main-survey-postlude').fadeIn();
            }
        });

      });
    });
    /*
    document.addEventListener('DOMContentLoaded', function() {
    	const f = document.querySelector('form#main-survey-form');
    	// console.log(f);
    	
    	f.addEventListener('submit', function (e) {
    		e.preventDefault();
    		// console.log(e, this);
    		// Get the form

    		let data = Object.fromEntries(new FormData(f));
    		let data2 = serialize( new FormData(f) );
    	

    		doSubmit(data);
    	});
    	
    });
    
    function doSubmit(d) {
      
      fetch("survey-form-submit.php", {
          method: 'post',
          body: JSON.stringify(d),
          headers: {
            'Content-Type': 'application/json'
          },
        })
        .then((response) => response.text())
        .then((res) => {
          console.log('Submitted:', res);
          if (res.status === 201) {
            console.log("Post successfully created!")
          }
        })
        .catch((error) => {
          console.log(error);
        })
      }
      */
  </script>
  </body>
</html>
