<?php
ini_set('display_errors', 1);
include_once 'header.php';
// Initialize the session
if (!isset($_SESSION)) {
  session_start();
}


$username = $_SESSION["username"];
$sqlchecksurveynumber= "SELECT id,country,state,city,total_survey_number FROM users WHERE username = '$username'";
$checksurveynumberquery = mysqli_query($mysqli,$sqlchecksurveynumber);
$surveynumberrow = mysqli_fetch_assoc($checksurveynumberquery);
$total_survey_number = $surveynumberrow['total_survey_number'];

$surveyscore = 0;
if (isset($_POST['submit']) and ! empty($_POST['submit'])) {

  if (isset($_POST['stresslvl'])) {
    $Q1_input = $_POST['stresslvl'];
    $surveyscore = $surveyscore +$Q1_input;
  }

  //for user information
  //updating total number of surveys
  $total_survey_number++;
  $sqlupdatetotal_survey_number = "UPDATE users SET survey_score=$surveyscore, last_survey_date = '".date("Y-m-d")."', total_survey_number=$total_survey_number WHERE username='$username'";
  // print_r($sqlupdatetotal_survey_number);
  // exit;
  $stmt2 = $mysqli->prepare($sqlupdatetotal_survey_number);
  $stmt2->execute();

  $sqlscores = "INSERT INTO scores (user_id, country_id, state_id,city_id,score) VALUES (?, ?, ?,?,?)";
        
  if($stmt = $mysqli->prepare($sqlscores)){
      // Bind variables to the prepared statement as parameters
    $stmt->bind_param("sssss",$param_userid,$param_country,$param_state,$param_city,$param_survey);
      // Set parameters
      $param_userid   = $surveynumberrow['id'];
      $param_country  = $surveynumberrow['country'];
      $param_state    = $surveynumberrow['state'];
      $param_city     = $surveynumberrow['city'];
      $param_survey   = $surveyscore;
    }
    $stmt->execute();
  //for paid group information
  /*$sqlcurrentpaidgroups= "SELECT paid_groups FROM users WHERE username='$username'";
  $currentpaidgroupsquery = mysqli_query($mysqli,$sqlcurrentpaidgroups);
  $currentpaidgroupsgrab = mysqli_fetch_assoc($currentpaidgroupsquery);
  $currentpaidgroups = $currentpaidgroupsgrab['paid_groups'];
  if (!empty($currentpaidgroups))
  {
    $currentpaidgroups = str_replace("_"," ",$currentpaidgroups);
    $currentpaidgroups = trim($currentpaidgroups);
    $currentpaidgroups = explode(" ", $currentpaidgroups);
  }
  
  if (!empty($currentpaidgroups))
  {

   for($i = 0; $i < count($currentpaidgroups); $i++)
   {

     $currentpaidgroupstocheck = $currentpaidgroups[$i];

     $sqlAlertsOnPersonalDataStatus= "SELECT AlertsOnPersonalData,Score FROM $currentpaidgroupstocheck WHERE MemberName='$username'";

     $AlertsOnPersonalDataStatusquery = mysqli_query($mysqli, $sqlAlertsOnPersonalDataStatus);
     $AlertsOnPersonalDataStatus = mysqli_fetch_assoc($AlertsOnPersonalDataStatusquery);
     $AlertsOnPersonalData = $AlertsOnPersonalDataStatus['AlertsOnPersonalData'];
     $Scoretosubtractfrom = $AlertsOnPersonalDataStatus['Score'];
     $Scoretocheckvalueof = $Scoretosubtractfrom - $surveyscore; 
     $threshholdscore = (-8);
     $HighScoreWarning = "False";
     $SendAlert = "False";
     if($Scoretosubtractfrom > 13 &&  $surveyscore > 13 )
     {
       $HighScoreWarning = "True";

     }
     if($Scoretocheckvalueof <  $threshholdscore || $HighScoreWarning == "True")
     {

       $SendAlert = "True";

     }
     if($AlertsOnPersonalData == "True" && $SendAlert == "True")
     {
             //get the users to update 
      $sqlGroupMembersofActiveGroup = "SELECT MemberName FROM $currentpaidgroupstocheck";
      $GroupMembersofActiveGroupquery = mysqli_query($mysqli,$sqlGroupMembersofActiveGroup);
      while ($GroupMembersofActiveGroup = mysqli_fetch_assoc($GroupMembersofActiveGroupquery))
      { 
        $MemberNameOnNow = $GroupMembersofActiveGroup['MemberName'];

        if($username != $MemberNameOnNow)
        {


            //Get current PendingUserAlerts
          $sqlPendingUserAlerts= "SELECT PendingUserAlerts FROM users WHERE username='$MemberNameOnNow'";
          $PendingUserAlertsquery = mysqli_query($mysqli,$sqlPendingUserAlerts);
          $PendingUserAlertsGrab = mysqli_fetch_assoc($PendingUserAlertsquery);
          $PendingUserAlerts = $PendingUserAlertsGrab['PendingUserAlerts'];
          $PendingUserAlerts = "{$PendingUserAlerts}_{$currentpaidgroupstocheck}:{$username}";

          $sqlupdatePendingUserAlerts = "UPDATE users SET PendingUserAlerts='$PendingUserAlerts' WHERE username='$MemberNameOnNow'";
          $stmt = $mysqli->prepare($sqlupdatePendingUserAlerts);
          $stmt->execute();
        }
      }
    }


      $sqlupdateuserpaidgroupsscores = "UPDATE $currentpaidgroupstocheck SET Score=$surveyscore WHERE MemberName='$username'";
      $stmt = $mysqli->prepare($sqlupdateuserpaidgroupsscores);
      $stmt->execute();

    }
  }*/
    //for free group information

// $sqlcurrentfreeMemberTotal = "SELECT MemberTotal,GroupMembers,AverageGroupScore, GroupName FROM Groups";
// $currentfreeMemberTotalsquery = mysqli_query($mysqli,$sqlcurrentfreeMemberTotal);


// while ($currentfreeMemberTotalgrab = mysqli_fetch_assoc($currentfreeMemberTotalsquery))
// {

//   $currentfreeMemberTotal = $currentfreeMemberTotalgrab['MemberTotal'];
//   $currentfreeGroupMembers = $currentfreeMemberTotalgrab['GroupMembers'];
//   $currentfreeGroupName = $currentfreeMemberTotalgrab['GroupName'];
//   $currentfreeGroupScore = $currentfreeMemberTotalgrab['AverageGroupScore'];
//   $currentfreeGroupMembers = str_replace("_"," ",$currentfreeGroupMembers);

//   $currentfreeGroupMembers = explode(" ", $currentfreeGroupMembers);

//   for($i = 0; $i < count($currentfreeGroupMembers); $i++)
//   {
//     if($currentfreeGroupMembers[$i] == $username)
//     {

//       $currentfreeGroupScore = $currentfreeGroupScore * $currentfreeMemberTotal;
//       $currentfreeMemberTotal = $currentfreeMemberTotal + 1;
//       $currentfreeGroupScore = $surveyscore + $currentfreeGroupScore;
//       $currentfreeGroupScore = $currentfreeGroupScore / $currentfreeMemberTotal;

//           //updating the userscore
//       $sqlupdateAverageGroupScore = "UPDATE Groups SET AverageGroupScore=$currentfreeGroupScore WHERE GroupName='$currentfreeGroupName'";
//       $stmt = $mysqli->prepare($sqlupdateAverageGroupScore);
//       $stmt->execute();

//     }
//   }
// }
include_once 'address_scores.php';
header("location:".getBaseUrl());
}

?>

<section>
    <div class="container">
      <div class="row">
          <div class="col-md-12">
              <div class="create-account text-center">
                  <img src="./public/images/right.png" alt="">
                  <h2>ALL SET!</h2>
              </div>
          </div>
      </div>
  </div>
  </section>
  <section class="st-full-hd">
      <div class="container">
          <div class="row">
              <div class="col-md-12">
                  <div class="st-full-title">
                      <h3>HOW STRESSED OR OVERWHELMED DO YOU FEEL TODAY?</h3>
                  </div>
              </div>
          </div>
      </div>
  </section>
<section class="st-survey">
    <div class="container-fluid">
        <!-- <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="st-survey-title text-center">
                    <h2>HOW STRESSED OR OVERWHELMED DO YOU FEEL TODAY?</h2>
                </div>
            </div>
        </div> -->
    <div class="row">
      <div class="col-md-12">
        <form action="#" method="post">
          <div class="row justify-content-center">
            <div class="col-md-8">
              <div class="st-range">
                <input type="range" class="custom-range" id="range-type" min="1" max="5" id="customRange2" />
                <input type="hidden" class=""  id="rangevalue" name="stresslvl" />

              </div>
            </div>
          </div>
          <div class="row justify-content-center">
            <div class="col-md-8">
              <div class="st-range-text">
                <div class="st-range-text-item range-1">
                  <p>VERY SLIGHTLY OR NOT AT ALL</p>
                </div>
                <div class="st-range-text-item range-2">
                  <p>A LITTLE</p>
                </div>
                <div class="st-range-text-item range-3">
                  <p>MODERATELY</p>
                </div>
                <div class="st-range-text-item range-4">
                  <p>QUITE A BIT</p>
                </div>
                <div class="st-range-text-item range-5">
                  <p>EXTREMELY</p>
                </div>
              </div>
              <div class="st-range-btn text-center">
                <input type="submit" name="submit" class="btn btn-primary" value="SUBMIT" id="submit">
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</section>




<?php
include_once 'footer.php';
?>
<script type="text/javascript">
  $(document).ready(function(){
    var r_val = $('#range-type').val();
    $('#rangevalue').val(r_val);
    $('.range-'+r_val).addClass('range-color');
    $(document).on('change', '#range-type', function() {
      var r_val = $(this).val();
      var data = 0;
      // $('.range-'+r_val).addClass('range-color');

        $('.st-range-text-item').removeClass('range-color');
        $('.range-'+r_val).addClass('range-color');

      /*if(r_val == 1){
       $('.range-color-'+r_val).addClass('')
      }else if(r_val == 2){
        data = 4;
      }else if(r_val == 3){
        data = 8;
      }else if(r_val == 4){
        data = 12;
      }else if(r_val == 5){
        data = 16;
      }*/
      // alert(data);
      $('#rangevalue').val(r_val);
    });
  });
</script>