<?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;
$isActiveUI = '';
$isActiveDB = false;
$saveMessage = '';
$quesCount = 0;
$setId = -1;
$deletedQuestionIds = array();
if(!(array_key_exists('id', $_GET) && array_key_exists('name', $_GET) && array_key_exists('active', $_GET)))
{
    echo '<script>alert("Important parameters are missing from the link! Please hit the browser\'s back button and try a valid action.")</script>';
    exit();
}
$formSubmitLink ='admin_survey_update.php?id='.$_GET['id'].'&name='.urlencode($_GET['name']).'&active='.$_GET['active'];

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]:''));
}

//when loading the survey, make sure it is not a postback to the page.
if(!array_key_exists('btnUpdate', $_REQUEST))
{
    $setId = trim($_GET['id']);
    
    if(array_key_exists('name', $_GET))
        $surveyName = $_GET['name'];
    
    if(array_key_exists('active', $_GET))
        $isActiveUI = $_GET['active'];
    
    //if we are passed an id in URL, pull data from the DB
    $questions = $biz->GetQuestions(trim($setId));
    if(!is_array($questions) || count($questions) == 0)
        $saveMessage = "<span class='error'>Unable to find data for the selected survey! Please <a href='admin_survey_search.php'>click here</a> to search for a survey.</span>";
    $quesCount = count($questions);
}
//do stuff only if Update button has been hit.
if (array_key_exists('btnUpdate', $_REQUEST))
{
    $setId = $_REQUEST['setId'];
    $deletedQuestionIds = explode(',', trim($_REQUEST['questionsToDelete'], ','));
    
    if(array_key_exists('isActive', $_REQUEST))
    {
        $isActiveUI = 1;
        $isActiveDB = true;
    }
    else
    {
        $isActiveUI = 0;
        $isActiveDB = false;
    }
    //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 only if it has changed
    else if($surveyName != $_GET['name'] && !$biz->IsSurveyNameAvailable($surveyName))
    {
        $errors['surveyNameError'] = 'This survey name is not available.';
        $hasError = true;
    }
        
    //get all values of question and corresponding co-ordinates
    $quesCount = intval(trim($_REQUEST['quesCount']));
    for($i = 0; $i<$quesCount; $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']),
                            'id' => trim($_REQUEST[$quesId.'Id'])
                         );
        $questions []= $question;
        
        //if either of the fields is full, check that all other 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;
            }
        }
    }
    
    if(!$hasError)
    {
        //if there are no errors, then try putting data in to database.
        $isSuccessfulUpdate = $biz->UpdateSurvey($surveyName, $setId, $isActiveDB, $questions, $deletedQuestionIds, array());
        if($isSuccessfulUpdate === true)
        {
            //refetch the questions from the database.
            $questions = $biz->GetQuestions($setId);
            $deletedQuestionIds = array();
            $errors = array();
            $saveMessage = '<span class=\'success\'>Changes were successfully saved to the database.</span>';
            $formSubmitLink ='admin_survey_update.php?id='.$_GET['id'].'&name='.urlencode($surveyName).'$active='.$isActiveUI;
        }
        else
        {
            $saveMessage = '<span class=\'error\'>There was an error saving the survey to the database.<br/>'.$isSuccessfulUpdate->errorDescription.'</span>';
        }
    }
    else
    {
        $saveMessage = '<span class=\'error\'>Kindly resolve the shown errors before saving 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 Edit Survey</title>
        <link rel="stylesheet" href="admin_main.css" type="text/css" />
        <script type="text/javascript">
            function ToggleDeletion(questionId, rowid, button)
            {
                questionsToDelete = document.getElementById('questionsToDelete').value;
                questionArray = questionsToDelete.split(',');
                questionIndex = questionArray.indexOf(questionId);
                if(button.innerHTML == "Delete")
                {
                    document.getElementById(rowid).style.backgroundColor = '#FF9D9D';
                    button.innerHTML = 'Undelete';
                    
                    //do the delete action - add to questionsToDelete
                    //first check if it has been already marked for deletion
                    if(questionIndex == -1)
                    {
                        //questionId does not exist in the array. add it.
                        questionsToDelete = questionsToDelete + questionId.toString() + ',';
                    }
                }
                else
                {
                    document.getElementById(rowid).style.backgroundColor = '#FFFFFF';
                    button.innerHTML = 'Delete';
                    if(questionIndex > -1)
                    {
                        questionArray.splice(questionIndex, 1);
                        //questionId does not exist in the array. add it.
                        questionsToDelete = questionArray.toString();
                    }
                }
                document.getElementById('questionsToDelete').value = questionsToDelete;
            }
            
            
            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('Update Survey'); ?>
        <div id='content' class='mainContent'>
            <p class='helpText'>A few things to keep in mind
                <ol class='helpText'>
                    <li>To Edit the question, please directly modify the data as you see it and hit update at the bottom of the page to save it.</li>
                    <li>Delete does not delete the questions until you hit Update at the end of the page.</li>
                    <li>You do not need to Update after every change. Please perform all edits and deletes and then hit Update once to save all changes at once.</li>
                    <li>Changing the survey name after the users have taken it may cause confusion. This feature has been provided mainly to correct typographical errors.</li>
                </ol></p>
            <form action='<?php echo $formSubmitLink; ?>' 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 $isActiveUI?'checked' : ''; ?> />&nbsp;<span class='helpText'>Will this survey be visible to end users 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='6'><input type='submit' name='btnUpdate' id='btnUpdate' value='Update'/>&nbsp;&nbsp;<span class='helpText'>Hit this button to save the changes you made anywhere in this page.</span></td>
                    </tr>
                    <tr>
                        <th>Question<br/>Number</th>
                        <th>Question Text</th>
                        <th>x</th>
                        <th>y</th>
                        <th>z</th>
                        <th>Action</th>
                    </tr>
                    <tbody>
                        <?php 
                        for($i = 0; $i<count($questions); $i++)
                        {
                            $uiIndex = $i + 1;
                            $quesId = 'q'.$i;
                            $quesTextError = '';
                            $xError = '';
                            $yError = '';
                            $zError = '';
                            $charLeft = $maxQuestionSize;
                            
                            $charLeft = $maxQuestionSize - strlen($questions[$i]['text']);
                            $quesText = htmlspecialchars($questions[$i]['text'], ENT_QUOTES);
                            $x = substr(htmlspecialchars($questions[$i]['x'], ENT_QUOTES), 0, 17);
                            $y = substr(htmlspecialchars($questions[$i]['y'], ENT_QUOTES), 0, 17);
                            $z = substr(htmlspecialchars($questions[$i]['z'], ENT_QUOTES), 0, 17);
                            $quesDbId = $questions[$i]['id'];
                            $isDeleted = !(array_search($quesDbId, $deletedQuestionIds) === false);
                            $style = 'style=\'background-color: #FFFFFF;\'';
                            $btnText = 'Delete';
                            if($isDeleted)
                            {
                                $style = 'style=\'background-color: #FF9D9D;\'';
                                $btnText = 'Undelete';
                            }
                            //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' id='q".$i."Row' $style>
                            <td>$uiIndex.<input name='q".$i."Id' id='q".$i."Id' value='$quesDbId' type='hidden' /></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>
                            <td>
                                <button name='btnToggleDelete' id='btnToggleDelete' type='button' value='$btnText' onclick='ToggleDeletion(\"$quesDbId\", \"q".$i."Row\", this);'>$btnText</button>
                            </td>
                        </tr>";
                        }
                        ?>
                        <tfoot>
                        <td colspan='6'><input type='submit' name='btnUpdate' id='btnUpdate' value='Update'/>&nbsp;&nbsp;<span class='helpText'>Hit this button to save the changes you made anywhere in this page.</span></td>
                        </tfoot>
                    </tbody>
                </table>
                <input value='<?php echo implode(',', $deletedQuestionIds); ?>' name='questionsToDelete' id='questionsToDelete' type='hidden' />
                <input value='<?php echo count($questions); ?>' name='quesCount' id='quesCount' type="hidden" />
                <input value='<?php echo $setId; ?>' name="setId" id="setId" type="hidden" />
            </form>
        </div>
    </body>
</html>