<?php
require_once 'admin_topbar.php';
require_once 'admin_bizLayer.php';
$biz = new admin_bizLayer();
$maxQuestionSize = 100;
$questionsPerPage = 10;
$surveyName = '';
$questions = array();
$errors = array();
$hasError = false;
$isActive = 'checked';
$saveMessage = '';
$numberOfQuestions = 0;
function StringToFloat( $val )
{
    preg_match( "#^([\+\-]|)([0-9]*)(\.([0-9]*?)|)(0*)$#", trim($val), $o );
    if(count($o) == 0 )
        return 'NaN';
    return floatval($o[1].sprintf('%d',$o[2]).($o[3]!='.'?$o[3]:''));
}

//do stuff only if create button has been hit.
if (array_key_exists('btnSave', $_REQUEST))
{
    //Confirm that survey name is not empty
    $surveyName = trim($_REQUEST['surveyName']);
    
    if(strlen($surveyName) == 0)
    {
        $errors['surveyNameError'] = 'Please enter name of the survey.';
        $hasError = true;
    }
    //check if the survey name has been used already
    else if(!$biz->IsSurveyNameAvailable($surveyName))
    {
        $errors['surveyNameError'] = 'This survey name is not available.';
        $hasError = true;
    }
    
    //determine if survey is checked to be active immediately
    if(!array_key_exists('isActive', $_REQUEST))
    {
        $isActive = '';
    }
    
    //get all values of question and corresponding co-ordinates
    for($i = 1; $i<$questionsPerPage +1; $i++)
    {
        $quesId = 'q'.$i;
        $question = array(
                            'text' => trim($_REQUEST[$quesId]),
                            'x' => trim($_REQUEST[$quesId.'x']),
                            'y' => trim($_REQUEST[$quesId.'y']),
                            'z' => trim($_REQUEST[$quesId.'z'])
                         );
        $questions[$i] = $question;
        //if either of the fields is full, check that all fields are full
        //and x,y and z only have numbers in it.
        if(strlen($question['text']) > 0 || strlen($question['x']) > 0
                || strlen($question['y']) > 0 || strlen($question['z']) > 0)
        {
            if(strlen($question['text']) == 0)
            {
                $errors[$quesId.'Error'] = 'Please enter some text for the question.';
                $hasError = true;
            }
            
            //check for x values
            if(strlen($question['x']) == 0)
            {
                $errors[$quesId.'xError'] = '\'x\' cannot<br/>be empty';
                $hasError = true;
            }
            else if(strlen($question['x']) > 17)
            {    
                $errors[$quesId.'xError'] = 'Please enter<br/>less than<br/>17 characters.';
                $hasError = true;
            }
            else if(StringToFloat($question['x']) === 'NaN')
            {
                $errors[$quesId.'xError'] = 'Invalid decimal<br/>number.';
                $hasError = true;
            }
            
            //check for y values
            if(strlen($question['y']) == 0)
            {
                $errors[$quesId.'yError'] = '\'y\' cannot<br/>be empty';
                $hasError = true;
            }
            else if(strlen($question['y']) > 17)
            {    
                $errors[$quesId.'yError'] = 'Please enter<br/>less than<br/>17 characters.';
                $hasError = true;
            }
            else if(StringToFloat($question['y']) === 'NaN')
            {
                $errors[$quesId.'yError'] = 'Invalid decimal<br/>number.';
                $hasError = true;
            }
            
            //check for z values
            if(strlen($question['z']) == 0)
            {
                $errors[$quesId.'zError'] = '\'z\' cannot<br/>be empty';
                $hasError = true;
            }
            else if(strlen($question['z']) > 17)
            {    
                $errors[$quesId.'zError'] = 'Please enter<br/>less than<br/>17 characters.';
                $hasError = true;
            }
            else if(StringToFloat($question['z']) === 'NaN')
            {
                $errors[$quesId.'zError'] = 'Invalid decimal<br/>number.';
                $hasError = true;
            }
            
            $numberOfQuestions++;
        }
    }
    
    if(!$hasError && $numberOfQuestions > 0)
    {
        //if there are no errors, then try putting data in to database.
        $isSuccessfulInsert = $biz->AddNewSurvey($surveyName, $isActive == 'checked', $questions);
        if($isSuccessfulInsert)
        {
            $questions = array();
            $errors = array();
            $surveyName = '';
            $saveMessage = '<span class=\'success\'>Survey was successfully saved to the database.</span>';
        }
        else
        {
            $saveMessage = '<span class=\'error\'>There was an error saving the survey to the database.'.$isSuccessfulInsert->errorDescription.'</span>';
        }
    }
    else
    {
        $saveMessage = '<span class=\'error\'>Kindly resolve the shown errors before saving the survey.</span>';
        if($numberOfQuestions === 0)
        {
            $saveMessage = '<span class=\'error\'>Please enter at least one question to the survey.</span>';
        }
    }
}

$biz->CloseDatabaseConnection();
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
        <title>Carview | VRoom 360 Create Survey</title>
        <link rel="stylesheet" href="admin_main.css" type="text/css" />
        <script type="text/javascript">
            function UpdateCharactersRemaining(targetElement, srcTextarea)
            {
                var maxSize = 100;
                var tag = document.getElementById(targetElement);
                var textBox = document.getElementById(srcTextarea);
                var charLeft = maxSize - textBox.value.length;
                
                if(charLeft <0)
                {
                    textBox.value = textBox.value.substr(0, maxSize);
                    charLeft = 0;
                }
                tag.textContent = charLeft;
            }
        </script>
    </head>
    <body>
        <?php PrintTopbar('Create Survey'); ?>
        <div id='content' class='mainContent'>
            <p class='helpText'>A few things to keep in mind
                <ol class='helpText'>
                    <li>Owing to the nature of the experience, <ul>
                            <li>please consider adding as less questions as possible.</li>
                            <li>watch out for questions that may feel redundant to the end user.</li>
                            <li>please remember that 'How do you feel about...' appears before every question in the application.</li>
                        </ul></li>
                    <li>You need not fill all questions. Fill the ones you want and hit Save.</li>
                </ol></p>
            <form action='admin_survey_create.php' method='post'>
                <table border='0'>
                    <tbody>
                        <tr>
                            <td>Survey Name:</td>
                            <td><input type='text' name='surveyName' id='surveyName' value='<?php echo $surveyName ?>' />&nbsp;&nbsp;<span id="surveyNameError" class='error'><?php if(array_key_exists('surveyNameError', $errors)) echo $errors['surveyNameError']; ?></span></td>
                        </tr>
                        <tr>
                            <td>Is Active:</td>
                            <td><input type='checkbox' name='isActive' value='checked' <?php echo $isActive ?> />&nbsp;<span class='helpText'>Will this survey be active as soon as the information is saved?</span></td>
                        </tr>
                    </tbody>
                </table>
                <p style='clear: left;'><?php echo $saveMessage; ?></p>
                <table border='0px' id='tblQuestions' cellspacing='0px'>
                    <tr>
                        <td colspan='5'>
                            <input type='submit' name='btnSave' id='btnSave' value='Save' />&nbsp;&nbsp;<span class='helpText'>Hit this button to save the changes made on this page. <em>Page will be cleared once the changes are successfully saved.</em></span>
                        </td>
                    </tr>
                    <tr>
                        <th>Question<br/>Number</th>
                        <th>Question Text</th>
                        <th>x</th>
                        <th>y</th>
                        <th>z</th>
                    </tr>
                    <tbody>
                        
                        <?php 
                        for($i = 1; $i<$questionsPerPage +1; $i++)
                        {
                            $quesId = 'q'.$i;
                            $quesTextError = '';
                            $xError = '';
                            $yError = '';
                            $zError = '';
                            $charLeft = $maxQuestionSize;
                            $quesText = '';//
                            $x = '';
                            $y = '';
                            $z = '';
                            
                            //put in the values fetched from the user
                            if(array_key_exists($i, $questions))
                            {
                                $charLeft = $maxQuestionSize - strlen($questions[$i]['text']);
                                $quesText = htmlspecialchars($questions[$i]['text'], ENT_QUOTES);
                            }
                            if(array_key_exists($i, $questions))
                            {
                                $x = htmlspecialchars($questions[$i]['x'], ENT_QUOTES);
                            }
                            if(array_key_exists($i, $questions))
                            {
                                $y = htmlspecialchars($questions[$i]['y'], ENT_QUOTES);
                            }
                            if(array_key_exists($i, $questions))
                            {
                                $z = htmlspecialchars($questions[$i]['z'], ENT_QUOTES);
                            }
                            
                            //set the errors
                            if(array_key_exists($quesId.'Error', $errors))
                            {
                                $quesTextError = $errors[$quesId.'Error'];
                            }
                            if(array_key_exists($quesId.'xError', $errors))
                            {
                                $xError = $errors[$quesId.'xError'];
                            }
                            if(array_key_exists($quesId.'yError', $errors))
                            {
                                $yError = $errors[$quesId.'yError'];
                            }
                            if(array_key_exists($quesId.'zError', $errors))
                            {
                                $zError = $errors[$quesId.'zError'];
                            }
                            echo "
                        <tr valign='top'>
                            <td>$i.</td>
                            <td>
                                <textarea cols='50' rows='5' title='Please enter the question here.' id='q".$i."' name='q".$i."' 
                                          onkeydown=\"UpdateCharactersRemaining('q".$i."CharCount', 'q".$i."');\"
                                          onkeyup=\"UpdateCharactersRemaining('q".$i."CharCount', 'q".$i."');\"
                                          >$quesText</textarea>
                                <span style='white-space: nowrap'><span id='q".$i."CharCount'>$charLeft</span> characters left.</span><br/>
                                <span id='q".$i."Error' class='error'>$quesTextError</span>
                            </td>
                            <td>
                                <input id='q".$i."x' name='q".$i."x' maxlength=10 type='text' size='17' value='$x'></input>
                                <br/><span id='q".$i."xError' class='error'>$xError</span>
                            </td>
                            <td>
                                <input id='q".$i."y' name='q".$i."y' maxlength=10 type='text' size='17' value='$y'></input>
                                <br/><span id='q".$i."yError' class='error'>$yError</span>
                            </td>
                            <td>
                                <input id='q".$i."z' name='q".$i."z' maxlength=10 type='text' size='17' value='$z'></input>
                                <br/><span id='q".$i."zError' class='error'>$zError</span>
                            </td>
                        </tr>";
                        }
                        ?>
                        <tfoot>
                            <td colspan='5'><input type='submit' name='btnSave' id='btnSave' value='Save' />&nbsp;&nbsp;<span class='helpText'>Hit this button to save the changes made on this page. <em>Page will be cleared once the changes are successfully saved.</em></span></td>
                        </tfoot>
                    </tbody>
                </table>
            </form>
        </div>
    </body>
</html>