<?php 

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

    class QuizzSchedule extends Core {
        
        public function start() {

            $sql = "SELECT id, quiz_id, page_index FROM quiz_crons WHERE end_at IS NULL AND paused = 0";
            $stmt = parent::$conn->query($sql);
            
            while($cron = $stmt->fetch(PDO::FETCH_ASSOC)) {

                $quiz_id = $cron['quiz_id'];
                $page = $cron['page_index'];
                try {                
                    
                    list($http_status, $response) = $this->sendRequest($quiz_id, $page);
                    
                    if($http_status === 200) {
                        $update_cron = "UPDATE quiz_crons SET page_index = page_index + 1 WHERE id = :id";
                        $stmt_update = parent::$conn->prepare($update_cron);
                        $stmt_update->execute(['id' => $cron['id']]);
                    } else if ($http_status === 404) {
                        $update_cron = "UPDATE quiz_crons 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 sendRequest($quiz_id, $page) {

            $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, 'page' => $page]));
            $response = curl_exec($ch);
            $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

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

    }

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