<?php
class SelectionTestQuestion extends Core {
    
    function store() {
        
        $question = $_POST;        

        $sql = "INSERT INTO selection_test_questions(description, question_type, required, selection_test)
            VALUES(?, ?, ?, ?)";
        $stmt = parent::$conn->prepare($sql);               
        $stmt->execute([
            $question['descriptionQuestion'],
            $question['questionType'],
            $question['required'] == 'true' ? true : false,
            $question['testId']
        ]);
        $question_id = parent::$conn->lastInsertId();
        
        if($question['questionType'] !== 'dissertative') {

            $options = json_decode($question['options'], true);
            foreach($options as $option) {

                $sql = "INSERT INTO selection_test_question_options(selection_test_question, description, is_right)
                    VALUES(?, ?, ?)";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([
                    $question_id,
                    $option['name'],
                    $option['isRight'] == 'true' ? true : false
                ]);

            }

        }
        

        return [ 'type' => 'OK' ];

    }

    function update() {
        
        $question = $_POST;
        
        $sql = "UPDATE selection_test_questions SET description = ?, question_type = ?, required = ? WHERE id = ?";
        $stmt = parent::$conn->prepare($sql);     
        $stmt->execute([
            $question['descriptionQuestion'],
            $question['questionType'],
            $question['required'] == 'true' ? true : false,
            $question['id']
        ]);
        
        $sql = "DELETE FROM selection_test_question_options WHERE selection_test_question = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([ $question['id'] ]);

        if($question['questionType'] !== 'dissertative') {

            $options = json_decode($question['options'], true);
            
            foreach($options as $option) {

                $sql = "INSERT INTO selection_test_question_options(selection_test_question, description, is_right)
                    VALUES(?, ?, ?)";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([
                    $question['id'],
                    $option['name'],
                    $option['isRight'] == 'true' ? true : false
                ]);

            }

        }        

        return [ 'type' => 'OK' ];        

    }

}