<?php

include("{$_SERVER['DOCUMENT_ROOT']}/admin/includes/config.php");
include("{$_SERVER['DOCUMENT_ROOT']}/admin/includes/function.php");

session_start();

$response = array(
    'type' => '',
    'data' => ''
);

$mode = $_REQUEST['mode'];

switch($_REQUEST['mode']){
    
    case 'question_answer':
        
        if( !filterRequestVar($_REQUEST['answer_key'], $primaryKeyFilter) ){
            $response['type'] = 'error';
            $response['data'] = "Podane dane nie są prawidłowe";
            break;
        }
        
        if(!(bool)$_SESSION['already_answered']){
            $_SESSION['already_answered'] = array();
        }

        if( !in_array($_REQUEST['answer_key'],  $_SESSION['already_answered']) ){
            $_SESSION['already_answered'][] = $_REQUEST['answer_key'];
        }
        
        $answers_str = mysql_fetch_assoc(mysql_query("SELECT LOWER(`correct_answers`) as 'correct_answers' FROM `pytania` WHERE id = {$_REQUEST['answer_key']}"));
        $answers = explode(',', $answers_str['correct_answers']);
        
        $got_it = false;
        
        foreach($answers as $iter => &$value){
            
            $value = trim($value, ' ');
            
            if(strtolower($_REQUEST['answer_content']) == $value){
                $got_it = true;
                break;
            }
        }
        
        $response['type'] = 'success';
        $response['data'] = ( ($got_it) ? 1 : 0 );
        
    break;
    
    case 'get_next_question':
        
        if( !filterRequestVar($_REQUEST['answer_key'], $primaryKeyFilter) ){
            $response['type'] = 'error';
            $response['data'] = "Podane dane nie są prawidłowe";
            goto end;
        }
        
        if(!(bool)$_SESSION['already_answered']){
            $_SESSION['already_answered'] = array();
        }
        
        if( !in_array($_REQUEST['answer_key'],  $_SESSION['already_answered']) ){
            $_SESSION['already_answered'][] = $_REQUEST['answer_key'];
        }
        
        $already_answered = implode(',', $_SESSION['already_answered']);

        $next_question = mysql_fetch_assoc(mysql_query("SELECT `id` as 'akey', `title` FROM `pytania` WHERE id NOT IN ({$already_answered}) ORDER BY RAND() LIMIT 1"));
        
        $response['type'] = 'success';
        $response['data'] = $next_question;
        
    break;
    
    default:
        $response['type'] = 'error';
        $response['data'] = "Nieprawidłowy identyfikator akcji";
    break;
    
}

end:
    echo json_encode($response);

?>