<?php 

class Quizzes extends Core {

    function list() {
        $company_id = $_GET['companyId'];
        $white_label_id = $this->config['WHITE_LABEL_ID'];

        $query = "SELECT * FROM quizzes WHERE company_id = :company_id AND white_label_id = :white_label_id";
        $stmt = parent::$conn->prepare($query);
        $stmt->execute(['company_id' => $company_id, 'white_label_id' => $white_label_id]);
        $quizzes = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach($quizzes as &$quiz) {
            $quiz_id = $quiz['id'];

            $question_query = "SELECT COUNT(*) as question_count FROM quiz_questions WHERE quiz_id = :quiz_id";
            $q_stmt = parent::$conn->prepare($question_query);
            $q_stmt->execute(['quiz_id' => $quiz_id]);
            $question_count = $q_stmt->fetch(PDO::FETCH_ASSOC)['question_count'];
            $quiz['question_count'] = $question_count;

            $segments_query = "SELECT count(*) as segment_count FROM quiz_segments WHERE quiz_id = :quiz_id";
            $s_stmt = parent::$conn->prepare($segments_query);
            $s_stmt->execute(['quiz_id' => $quiz_id]);
            $segment_count = $s_stmt->fetch(PDO::FETCH_ASSOC)['segment_count'];
            $quiz['segment_count'] = $segment_count;

            $cron_query = "SELECT * FROM quiz_crons WHERE quiz_id = :quiz_id ORDER BY id DESC LIMIT 1";
            $c_stmt = parent::$conn->prepare($cron_query);
            $c_stmt->execute(['quiz_id' => $quiz_id]);
            $cron = $c_stmt->fetch(PDO::FETCH_ASSOC);
            $quiz['cron_paused'] = $cron['paused'] ?? 1;
            $quiz['cron_id'] = $cron['id'] ?? null;
            $quiz['cron_start_at'] = $cron['start_at'] ?? null;
            $quiz['cron_end_at'] = $cron['end_at'] ?? null;
        }

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

    function save() {
        $data       = $_POST;
        $company_id = $data['companyId'];
        $title = $data['title'] ?? null;
        $description = $data['description'] ?? null;

        if(is_null($title)) {
            http_response_code(400);
            echo json_encode(['error' => 'Title is required']);
            return;
        }

        $white_label_id = $this->config['WHITE_LABEL_ID'];

        $quiz_insert = "INSERT INTO quizzes (company_id, white_label_id, title, description) 
            VALUES (:company_id, :white_label_id, :title, :description)";

        $stmt = parent::$conn->prepare($quiz_insert);
        $stmt->execute([
            'company_id' => $company_id, 
            'white_label_id' => $white_label_id,
            'title' => $title,
            'description' => $description
        ]);
        $quiz_id = parent::$conn->lastInsertId();

        $cron_insert = "INSERT INTO quiz_crons (quiz_id, paused) VALUES (:quiz_id, 1)";
        $stmt = parent::$conn->prepare($cron_insert);
        $stmt->execute(['quiz_id' => $quiz_id]);

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

    function update() {

        $data       = $_POST;
        $id         = $data['id'] ?? null;
        $title      = $data['title'] ?? null;
        $description= $data['description'] ?? null;
        $company_id = $data['companyId'] ?? null;
        $white_label_id = $this->config['WHITE_LABEL_ID'];

        if (is_null($id)) {
            http_response_code(400);
            echo json_encode(['error' => 'Quiz ID is required']);
            return;
        }

        if(is_null($title)) {
            http_response_code(400);
            echo json_encode(['error' => 'Title is required']);
            return;
        }

        $sql_update = "UPDATE quizzes 
            SET title = :title, description = :description
            WHERE id = :id AND company_id = :company_id AND white_label_id = :white_label_id";

        $stmt = parent::$conn->prepare($sql_update);
        $stmt->execute([
            'title' => $title,
            'description' => $description,
            'id' => $id,
            'company_id' => $company_id,
            'white_label_id' => $white_label_id
        ]);

        return ['type' => 'OK', 'data' => ['quizId' => $id]];

    }

    function delete() {

        $id = $_GET['id'] ?? null;
        
        if (is_null($id)) {
            http_response_code(400);
            echo json_encode(['error' => 'Quiz ID is required']);
            return;
        }

        $delete_query = "DELETE FROM quizzes WHERE id = :id";
        $stmt = parent::$conn->prepare($delete_query);
        $stmt->execute(['id' => $id]);

        return ['type' => 'OK', 'data' => 'Quiz deleted successfully'];

    }

    function cronPauseStatus() {

        $quiz_id = $_POST['quizId'] ?? null;

        $select_cron = "SELECT * FROM quiz_crons WHERE quiz_id = :quiz_id AND end_at IS NULL ORDER BY id DESC LIMIT 1";
        $stmt = parent::$conn->prepare($select_cron);
        $stmt->execute(['quiz_id' => $quiz_id]);
        $cron = $stmt->fetch(PDO::FETCH_ASSOC);

        if($cron) {

            $update_cron = "UPDATE quiz_crons SET paused = :paused WHERE id = :id";
            $stmt = parent::$conn->prepare($update_cron);
            $new_status = $cron['paused'] ? false : true;
            $stmt->execute(['paused' => $new_status, 'id' => $cron['id']]);

        } else {
            $insert_cron = "INSERT INTO quiz_crons (quiz_id, paused) VALUES (:quiz_id, 0)";
            $stmt = parent::$conn->prepare($insert_cron);
            $stmt->execute(['quiz_id' => $quiz_id]);

             $cron = [
                'id' => parent::$conn->lastInsertId(),
                'quiz_id' => $quiz_id,
                'paused' => 0,
                'end_at' => null
            ];  
        }

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

    }

    function resetQuizzCron() {

        $quiz_id = $_POST['quizId'] ?? null;

        $sql_delete_sent = "DELETE FROM quiz_question_sent WHERE quiz_id = :quiz_id";
        $stmt = parent::$conn->prepare($sql_delete_sent);
        $stmt->execute(['quiz_id' => $quiz_id]);

        $sql = "DELETE FROM quiz_answer WHERE quiz_id = :quiz_id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute(['quiz_id' => $quiz_id]);

        $insert_cron = "INSERT INTO quiz_crons (quiz_id, paused) VALUES (:quiz_id, 0)";
        $stmt = parent::$conn->prepare($insert_cron);
        $stmt->execute(['quiz_id' => $quiz_id]);
        $cron = [
            'quiz_id' => $quiz_id,
            'paused' => 1,
            'end_at' => null
        ];  

        return ['type' => 'OK', 'message' => 'Quiz cron reset successfully'];

    }

    function sendQuizz() {
        $quiz_id = $_POST['quizId'] ?? null;
        $candidate_id = $_POST['candidateId'] ?? null;

        if(is_null($quiz_id) || is_null($candidate_id)) {
            http_response_code(400);
            echo json_encode(['error' => 'Quiz ID and Candidate ID are required']);
            return;
        }

        $sql_delete_sent = "DELETE FROM quiz_question_sent WHERE quiz_id = :quiz_id AND candidate_id = :candidate_id";
        $stmt = parent::$conn->prepare($sql_delete_sent);
        $stmt->execute(['quiz_id' => $quiz_id, 'candidate_id' => $candidate_id]);

        $sql_delete_answer = "DELETE FROM quiz_answer WHERE quiz_id = :quiz_id AND candidate_id = :candidate_id";
        $stmt = parent::$conn->prepare($sql_delete_answer);
        $stmt->execute(['quiz_id' => $quiz_id, 'candidate_id' => $candidate_id]);

        $this->sendRequest($quiz_id, $candidate_id);

        return ['type' => 'OK', 'message' => 'Quiz sent to candidate successfully'];

    }

    function saveQuizProcessList() {

        $quiz_id = $_POST['quizId'] ?? null;
        $process_list_id = $_POST['processListId'] ?? null;

        if(is_null($quiz_id) || is_null($process_list_id)) {
            http_response_code(400);
            echo json_encode(['error' => 'Quiz ID and Process List ID are required']);
            return;
        }

        $sql = "SELECT * FROM quiz_cron_process_lists WHERE quiz_id = :quiz_id AND process_list_id = :process_list_id AND end_at IS NULL";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute(['quiz_id' => $quiz_id, 'process_list_id' => $process_list_id]);
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);

        if($existing) {
            return ['type' => 'FAIL', 'message' => 'Quiz process list already exists'];
        } 

        $sql_insert = "INSERT INTO quiz_cron_process_lists (quiz_id, process_list_id) VALUES (:quiz_id, :process_list_id)
            ON DUPLICATE KEY UPDATE process_list_id = :process_list_id";
        $stmt = parent::$conn->prepare($sql_insert);
        $stmt->execute(['quiz_id' => $quiz_id, 'process_list_id' => $process_list_id]);

        return ['type' => 'OK', 'message' => 'Quiz process list saved successfully'];

    }

    private function sendRequest($quiz_id, $candidate_id) {

        $url = 'https://chatbots.wayfy.com.br/webhook/quiz_trigger';

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, 
            array(
                'Content-Type: application/json',
                'x-quizz-trigger-token: 4ce7cd16-4f3f-4615-b298-01062016e878'
            )
        );
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['quizId' => $quiz_id, 'candidateId' => $candidate_id]));
        $response = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return [
            $http_status,
            json_decode($response, true)
        ];
    }

}