<?php

/**
 * Ask question form
 */
defined('MOODLE_INTERNAL') || die;
require_once('../../config.php');
require_once($CFG->libdir . '/formslib.php');
require_once('lib.php');

class askquestion_edit_form extends moodleform {   

    function definition() {
        global $USER, $CFG, $DB;

        $mform = $this->_form;
        $profile_field_category_id = get_config('local_askquestion', 'security_question_profile_field_category_id');
		
		$profile_fields = $DB->get_records('user_info_field', array('categoryid' => $profile_field_category_id));
		$extraprofilefields = array();

		//if (isset($_SESSION['profileshortname'])) {
        //    $profileshortname = $_SESSION['profileshortname'];
        //} else {
		  if ($profile_fields) {
			  foreach ($profile_fields as $profile_field) {
				  $extraprofilefields[] = $profile_field->shortname;
			  }
			  $_SESSION['no_ques']=count($extraprofilefields);
			  //echo "<pre>";
			  //print_r($extraprofilefields);
			  
			  if(!isset($_SESSION['qno'])){
				   $_SESSION['qno']=0;
				  //echo "qno not set =".$_SESSION['qno'];
				  
			  }
			  //$_SESSION['qno']=0;
			  $rand_key = $_SESSION['qno'];
			  //echo "Total Ques=".$_SESSION['no_ques'];
			  //echo "ranKey=".$rand_key;
			  $profileshortname = $extraprofilefields[$rand_key];
			  $_SESSION['profileshortname'] = $profileshortname;
			  
		  }
		//}
		
		//echo "Profile Short Name=".$profileshortname;
		
        //print_r($_SESSION);
		$profileinfo = $DB->get_record('user_info_field', array('shortname' => $profileshortname));
        $displayquestion = true;
        $securityquestiontext = $profileinfo->name;

        if ($displayquestion) {
            require_once($CFG->dirroot.'/user/profile/lib.php');
            require_once($CFG->dirroot.'/user/profile/field/'.$profileinfo->datatype.'/field.class.php');
            $newfield = 'profile_field_'.$profileinfo->datatype;			
            $formfield = new $newfield($profileinfo->id, $USER->id);			
            $formfield->edit_field($mform);
            $this->add_action_buttons(false, 'Submit');
        }
		
    }

    //	Custom validation should be added here
    function validation($data, $files) {
        global $USER, $DB,$CFG,$PAGE;
        $errors = array();
        $errors = parent::validation($data, $files);
		
//print $_SESSION['currenturl'];
        $profilefieldshortname = $_SESSION['profileshortname'];
        $profilefieldinfo = $DB->get_record('user_info_field', array('shortname' => $profilefieldshortname));

        if ($DB->record_exists('user_info_data', array('userid' => $USER->id, 'fieldid' => $profilefieldinfo->id))) {
            $datarow = $DB->get_record('user_info_data', array('userid' => $USER->id, 'fieldid' => $profilefieldinfo->id));
				 //echo $profilefieldinfo->datatype; /*just checking to see if the type of question is truly being captured */
			if ($profilefieldinfo->datatype == 'menu') {
    			$options = explode("\n", $profilefieldinfo->param1);
    			$selecteddata = $data['profile_field_'.$profilefieldshortname];
    			//$submittedvalue = $options[$selectedindex]; invalid reference to the data instead of the index
    			$submittedvalue = $selecteddata;
    			/* echo $selectedindex; checking if the correct index for selected answer is being recorded*/
			} else {
    			$submittedvalue = $data['profile_field_'.$profilefieldshortname];
			}
			
			if ($submittedvalue == $datarow->data) { 
				 //echo " // This answer is correct!"; //just checking if it ever comes to this branch of the condition 	 
				
				  if($_SESSION['qno'] < $_SESSION['no_ques']-1){
					  $_SESSION['qno']=$_SESSION['qno']+1;
				  }else{
					  $_SESSION['qno']=0;
				  }
				 if (isset($_SESSION['profileshortname'])) {
        			unset($_SESSION['profileshortname']);
    			 }
    			 $_SESSION['profileshortname']='';
    			 //Added by Desmond on 27Oct2017
    			 ?>
				 <script>
				    window.parent.CountDown.Resume(); //Added by Des on 22Nov
				     window.close();
                     self.close();
                     window.parent.toggle('popUpDiv');
                     window.parent.toggle('blanket');
				 </script>
				 <?php
				 exit();
				 //Added by Desmond on 27Oct2017
				 //redirect($_SESSION['currenturl']); //Commented by Desmond on 27Oct2017
				 //exit();
			        //redirect($CFG->wwwroot . '/course/view.php?id=2'); 
			} else {
				/* echo " // Wrong answer!"; just checking if it comes to this branch when user answers wrongly */
				
				if (isset($_SESSION['how_many_times_failed_in_answering'])) {
                    $_SESSION['how_many_times_failed_in_answering'] = $_SESSION['how_many_times_failed_in_answering'] + 1;
                } else {
                    $_SESSION['how_many_times_failed_in_answering'] = 1;
                }

                $max_attempt_allowed = get_config('local_askquestion', 'max_attempt_allowed_in_security_question');

                if ($_SESSION['how_many_times_failed_in_answering'] >= $max_attempt_allowed) {
                    //invalidate user or suspend user
                    $errors['securityquestion'] = get_string('nomore_attempt', 'local_askquestion');
                    $logouturl = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
                    $userobj = new stdClass();
                    $userobj->id = $USER->id;
                    $userobj->suspended = 1;
                    $return = $DB->update_record('user', $userobj);
                if ($return) {
                        send_account_suspend_email_to_user();
                        $to = $USER->email;
                        $fname = $USER->firstname;
                        $lname = $USER->lastname;
                        $sitename = $DB->get_field('course', 'fullname', array('id' => 1));
			$subject = "79 Dollar Ohio Driver: Your account has been blocked.";
			$txt = "Oh dear...your account was blocked because you did not answer your security questions correctly. Please confirm the following information, and we will get you back on track!";
			$txt .= "\n\n";
		    $txt .= " - Your name\n";
		    $txt .= " - Your date of birth\n";
		    $txt .= " - Your favorite color\n";
		    $txt .= " - Your natural hair color\n";
		    $txt .= " - Your month of birth\n";
		    $txt .= " - Your middle initial\n";
		    $txt .= " - Your eye color\n";
		    $txt .= "";
		    $txt .= "We will respond to your email to let you know your account is reopened.";
			$headers = "From: CustomerCare@79DollarOhioDriver.com";
			mail($to,$subject,$txt,$headers);
                    }
                    echo "<script type='text/javascript'>alert('Oh dear...your account has been blocked because you did not answer your security questions correctly. You will be logged out of the site after clicking the OK button below. Please go to your email account and respond to the email we just sent you, and get you back on track!')</script>";
                    //Added by Desmond on 27Oct2017
                    ?>
				 <script>
				     window.close();
                     self.close();
                     window.parent.toggle('popUpDiv');
                     window.parent.toggle('blanket');
                     window.parent.reloadPage();
				 </script>
				 <?php
				    //Added by Desmond on 27Oct2017
				    redirect($logouturl);
				    exit();
                    
                } else if ($_SESSION['how_many_times_failed_in_answering'] == ($max_attempt_allowed - 1)) {
                    $remaning_attempt = $max_attempt_allowed - $_SESSION['how_many_times_failed_in_answering'];
                     $errors['securityquestion'] = get_string('errormsg', 'local_askquestion', $remaning_attempt);
					
                } else if ($_SESSION['how_many_times_failed_in_answering'] < $max_attempt_allowed) {
                    $remaning_attempt = $max_attempt_allowed - $_SESSION['how_many_times_failed_in_answering'];
                    $errors['securityquestion'] = get_string('errormsg', 'local_askquestion', $remaning_attempt);
					
                }
			}
        } else {
            $errors['securityquestion'] = get_string('incomplete_profiledata', 'local_askquestion');
			
        }
		$_SESSION['errors']=$errors;
        return $errors;
    }

}