<?php
include_once __dir__ .  '/../core/LogEvent.php';
class SelectionTest extends Core
{

    function list()
    {

        if(!isset($_GET['companyId']))
            return [];

        $white_lb_id = $this->config['WHITE_LABEL_ID'] ?? null;
        $process_list = $_GET['processListId'] ?? null;
        $company_id = $_GET['companyId'] ?? null;        
        $cond = $process_list ? " AND EXISTS(SELECT process_list FROM process_list_test WHERE process_list_test.selection_test = selection_tests.id AND process_list = :process_list)" : '';
        $sql = "SELECT * FROM selection_tests WHERE company = :company AND active = 1 $cond AND white_label_id = :white_lb_id ORDER BY name";

        $stmt = parent::$conn->prepare($sql);

        if ($process_list)
            $stmt->bindParam(':process_list', $process_list);
        $stmt->bindParam(':white_lb_id', $white_lb_id);
        $stmt->bindParam(':company', $company_id);
        $stmt->execute();

        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        return ['type' => 'OK', 'data' => $result];
     
    }

    function store()
    {

        $white_lb_id = $this->config['WHITE_LABEL_ID'] ?? null;
        $user_id = $_POST['userId'];
        $name = $_POST['name'];
        $description = $_POST['description'];
        $time_resolution = $_POST['timeResolution'] ?? 0;
        $questions = $_POST['questions'];
        $company_id = $_POST['companyId'];

        try {

            parent::$conn->beginTransaction();

            $sql = "INSERT INTO selection_tests(name, description, time_resolution, company, white_label_id) VALUES(?, ?, ?, ?, ?)";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$name, $description, $time_resolution, $company_id, $white_lb_id]);
            $test_id = parent::$conn->lastInsertId();

            $questions = json_decode($questions, true);

            foreach ($questions as $question) {

                $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,
                    $test_id
                ]);
                $question_id = parent::$conn->lastInsertId();

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

                    foreach ($question['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
                        ]);
                    }
                }
            }

            $url = '';
            $title = "Teste \"$name\" criado";
            LogEvent::log($user_id, $test_id, $url, $title, LogEvent::CREATE_TEST);

            parent::$conn->commit();

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

        } catch(\Exception $err) {
            throw $err;
            parent::$conn->rollback();
        }
    }

    function remove()
    {

        $id = $_GET['id'];

        $sql = "SELECT * FROM process_list_test WHERE selection_test = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$id]);


        if ($stmt->rowCount() > 0) {

            $sql = "UPDATE selection_tests SET active = 0 WHERE id = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$id]);

            return ['type' => 'FAIL'];
        }

        $sql = "DELETE FROM selection_tests WHERE id = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$id]);

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

    function get()
    {

        $id = $_GET['id'];
        $sql = "SELECT * FROM selection_tests WHERE id = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$id]);
        $test = $stmt->fetch(PDO::FETCH_ASSOC);

        $sql = "SELECT * FROM selection_test_questions WHERE selection_test = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$id]);
        $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);


        foreach ($questions as $index => $question) {

            $sql = "SELECT * FROM selection_test_question_options WHERE selection_test_question = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$question['id']]);
            $questions[$index]['options'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }

        $test['questions'] = $questions;

        $sql = "SELECT * FROM process_list_test WHERE selection_test = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$id]);
        $test['inUse'] = $stmt->rowCount() > 0;

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

    function update()
    {

        $id = $_POST['id'];
        $name = $_POST['name'];
        $description = $_POST['description'];
        $time_resolution = $_POST['timeResolution'];
        $questions = $_POST['questions'];
        
        $sql = "UPDATE selection_tests SET name = ?, description = ?, time_resolution = ? WHERE id = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$name, $description, $time_resolution, $id]);
        $test_id = $id;

        $sql = "DELETE FROM selection_test_questions WHERE selection_test = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$id]);

        $questions = json_decode($questions, true);

        foreach ($questions as $question) {

            $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,
                $test_id
            ]);
            $question_id = parent::$conn->lastInsertId();

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

                foreach ($question['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'];
    }
}
