<?php

require __DIR__ . '/../core/Core.php';
include_once __DIR__ .'/../connection.php';

class QuizzScheduleProcessList extends Core {

    public function start() {

        $sql = "SELECT id, quiz_id, process_list_id, page_index FROM quiz_cron_process_lists WHERE end_at IS NULL";
        $stmt = parent::$conn->query($sql);

        while($cron = $stmt->fetch(PDO::FETCH_ASSOC)) {

            $quiz_id = $cron['quiz_id'];
            $process_list_id = $cron['process_list_id'];
            $page = $cron['page_index'];
            try {                
                file_put_contents('cron_logs.log', date('Y-m-d H:i:s') . " - Processing quiz_id: $quiz_id, process_list_id: $process_list_id, page: $page\n", FILE_APPEND);
                $result = $this->sendCandidateQuizz($quiz_id, $process_list_id, $page);
                
                if($result) {
                    $update_cron = "UPDATE quiz_cron_process_lists SET page_index = page_index + 1 WHERE id = :id";
                    $stmt_update = parent::$conn->prepare($update_cron);
                    $stmt_update->execute(['id' => $cron['id']]);
                } else {
                    $update_cron = "UPDATE quiz_cron_process_lists SET end_at = NOW() WHERE id = :id";
                    $stmt_update = parent::$conn->prepare($update_cron);
                    $stmt_update->execute(['id' => $cron['id']]);
                }

            } catch (Exception $e) {
                continue;
                file_put_contents('cron_errors.log', date('Y-m-d H:i:s') . " - Error processing quiz_id: $quiz_id, page: $page - " . $e->getMessage() . "\n", FILE_APPEND);
            }

        }

    }    

    private function sendCandidateQuizz($quiz_id, $process_list_id, $page) {        

        $sql = "SELECT * FROM process_list_lead WHERE process_list = :process_list_id ORDER BY id LIMIT 20 OFFSET :offset";
        $stmt = parent::$conn->prepare($sql);
        $stmt->bindValue(':process_list_id', $process_list_id, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $page * 20, PDO::PARAM_INT);
        $stmt->execute();
        $candidates = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    
        foreach ($candidates as $candidate) {           

            $sql_delete_quiz_answer = "DELETE FROM quiz_answer WHERE quiz_id = :quiz_id AND candidate_id = :candidate_id";
            $stmt_delete = parent::$conn->prepare($sql_delete_quiz_answer);
            $stmt_delete->bindValue(':quiz_id', $quiz_id, PDO::PARAM_INT);
            $stmt_delete->bindValue(':candidate_id', $candidate['lead'], PDO::PARAM_INT);
            $stmt_delete->execute();

            $sql_delete_quiz_sent = "DELETE FROM quiz_question_sent WHERE quiz_id = :quiz_id AND candidate_id = :candidate_id";
            $stmt_delete_sent = parent::$conn->prepare($sql_delete_quiz_sent);
            $stmt_delete_sent->bindValue(':quiz_id', $quiz_id, PDO::PARAM_INT);
            $stmt_delete_sent->bindValue(':candidate_id', $candidate['lead'], PDO::PARAM_INT);
            $stmt_delete_sent->execute();

            file_put_contents('cron_logs.log', date('Y-m-d H:i:s') . " - candidate_id: " . $candidate['lead'] . "\n", FILE_APPEND);

            $this->sendRequest($quiz_id, $candidate['lead']);
        }

        return $stmt->rowCount() > 0;

    }

    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)
        ];
    }

}

$schedule = new QuizzScheduleProcessList(new Connection());
$schedule->start();