<?php

class TestModel extends Core
{

    private function getPostData($key, $filter = FILTER_SANITIZE_SPECIAL_CHARS)
    {
        return filter_input(INPUT_POST, $key, $filter);
        return $order;
    }

    function list()
    {

        $sql = "SELECT * FROM process_test_model";
        $stmt = parent::$conn->query($sql);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return [
            'type' => 'OK',
            'result' => $result
        ];
    }

    function copyModelToProcessList()
    {

        $company_id = $this->getPostData('companyId', FILTER_VALIDATE_INT);
        $id = $this->getPostData('id', FILTER_VALIDATE_INT);

        if (!$id || !$company_id) {
            return ['type' => 'ERROR', 'message' => 'Invalid step ID'];
        }

        $sql = "SELECT * FROM process_test_model WHERE id = :id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([
            ':id' => $id
        ]);
        $model = $stmt->fetch(PDO::FETCH_ASSOC);
        $test_data = json_decode($model['data'], true);

        $sql_test = "INSERT INTO selection_tests(company, name, active) VALUES(:company, :name, 1)";
        $stmt_test = parent::$conn->prepare($sql_test);
        $name = "Cópia de {$model['name']}";
        $stmt_test->execute([
            ':company' => $company_id,
            ':name' => $name
        ]);

        $test_id = parent::$conn->lastInsertId();

        $sql_question = "INSERT INTO selection_test_questions (selection_test, description, question_type) VALUES(:selection_test, :description, 'multiple')";
        $stmt_question = parent::$conn->prepare($sql_question);

        $sql_option = "INSERT INTO selection_test_question_options(selection_test_question, description, is_right) VALUES(:selection_test_question, :description, :is_right)";
        $stmt_option = parent::$conn->prepare($sql_option);


        foreach ($test_data['questions'] as $test) {

            $stmt_question->execute([
                ':selection_test' => $test_id,
                ':description' => $test['statement']
            ]);

            $selection_test_id = parent::$conn->lastInsertId();
            $options = $test['options'];
            $right_option = $test['rightOption'];

            foreach ($options as $index => $option) {
                $stmt_option->execute([
                    ':selection_test_question' => $selection_test_id,
                    ':description' => $option,
                    ':is_right' => intval($right_option) == $index
                ]);
            }
        }

        return [
            'type' => 'OK',
            'result' => ''
        ];
    }
}
