<?php

class WebinarSysteemWebinarMessages
{
    /**
     * Process a pending webinar message
     * @param WebinarSysteemWebinar $webinar
     * @param object $message
     **/

    private static function process_message($webinar, $message)
    {
        global $wpdb;
        $data = $message->data;
        $attendee = isset($message->attendee)
            ? $message->attendee
            : null;

        switch ($message->type) {
            case 'send-chat':
                // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
                $timestamp = date('Y-m-d H:i:s', $webinar->get_now_in_timezone($data->createdAt / 1000));
                $chat_table = WebinarSysteemTables::get_chats();

                if (isset($data->is_simulated_chat) && $data->is_simulated_chat == '1') {
                    $simulated_chat_username = isset($data->simulated_chat_username) ? $data->simulated_chat_username : '';
                    $simulated_chat_id = isset($data->simulated_chat_id) ? $data->simulated_chat_id : '';

                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $chatRecords = $wpdb->get_results(
                        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                        $wpdb->prepare("SELECT * FROM {$chat_table} WHERE webinar_id=%d and simulated_chat_id=%s AND is_simulated_chat = 1 ORDER BY id DESC", $webinar->id, $simulated_chat_id)
                    );

                    if (count($chatRecords) == 0) {
                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                        $wpdb->replace(
                            $chat_table,
                            [
                                'id' => $data->id,
                                'webinar_id' => $webinar->id,
                                'admin' => false,
                                'private' => false,
                                'attendee_id' => 0,
                                'content' => str_replace('\\', '', sanitize_textarea_field($data->content)),
                                'timestamp' => $timestamp,
                                'is_simulated_chat' => $data->is_simulated_chat,
                                'simulated_chat_username' => $simulated_chat_username,
                                'simulated_chat_id' => $simulated_chat_id,
                            ]
                        );
                    }
                } else {
                    $vote_table = WebinarSysteemTables::get_poll_votes();
                    $tableName = WebinarSysteemTables::get_questions();

                    $attendee = WebinarSysteemAttendees::get_attendee_by_id($data->attendeeId);

                    if ($attendee === null) {
                        wp_send_json_error(null, 422);
                        return;
                    }

                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $vote_records = $wpdb->get_results(
                        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                        $wpdb->prepare("SELECT * FROM {$vote_table} WHERE webinar_id=%d and attendee_id=%d ORDER BY id DESC",
                            $attendee->webinar_id,
                            $attendee->id,
                        )
                    );
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $questionsRecords = $wpdb->get_results(
                        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                        $wpdb->prepare("SELECT * FROM {$tableName} WHERE webinar_id=%d and asked_by=%d ORDER BY id DESC",
                            $attendee->webinar_id,
                            $attendee->id,
                        )
                    );
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $chatRecords = $wpdb->get_results(
                        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                        $wpdb->prepare("SELECT * FROM {$chat_table} WHERE webinar_id=%d and attendee_id=%d AND is_simulated_chat = 0 ORDER BY id DESC",
                            $attendee->webinar_id,
                            $attendee->id,
                        )
                    );

                    //file_put_contents('custom-log.txt', json_encode($data), FILE_APPEND);
                    if (count($vote_records) == 0 && count($questionsRecords) == 0 && count($chatRecords) == 0) {
                        WebinarSysteemSubscribe::custom_subscribe($attendee->webinar_id, $attendee->email, $attendee->name, 'Interacted (Questions, Polls)');
                    }

                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->replace(
                        $chat_table,
                        [
                            'id' => $data->id,
                            'webinar_id' => $webinar->id,
                            'admin' => $data->isTeamMember,
                            'private' => false,
                            'attendee_id' => $data->attendeeId,
                            'content' => str_replace('\\', '', sanitize_textarea_field($data->content)),
                            'timestamp' => $timestamp,
                        ]
                    );
                }
                break;

            case 'delete-chat':
                // team members can delete anyone's chats
                if ($attendee->isTeamMember) {
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->delete(
                        WebinarSysteemTables::get_chats(),
                        ['id' => $data->id],
                        ['%d']
                    );
                    return;
                }

                // make sure that this attendee sent the message or they are a team member
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->delete(
                    WebinarSysteemTables::get_chats(),
                    ['id' => $data->id, 'attendee_id' => $attendee->id],
                    ['%d', '%d']
                );
                break;

            case 'send-question':
                // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
                $timestamp = date('Y-m-d H:i:s', $webinar->get_now_in_timezone($data->createdAt / 1000));

                $asking_attendee = WebinarSysteemAttendees::get_attendee_by_id($data->askedBy);

                $vote_table = WebinarSysteemTables::get_poll_votes();
                $tableName = WebinarSysteemTables::get_questions();
                $chat_table = WebinarSysteemTables::get_chats();

                if ($asking_attendee === null) {
                    wp_send_json_error(null, 422);
                    return;
                }

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $vote_records = $wpdb->get_results(
                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                    $wpdb->prepare("SELECT * FROM {$vote_table} WHERE webinar_id=%d and attendee_id=%d ORDER BY id DESC",
                        $asking_attendee->webinar_id,
                        $asking_attendee->id,
                    )
                );
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $questionsRecords = $wpdb->get_results(
                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                    $wpdb->prepare("SELECT * FROM {$tableName} WHERE webinar_id=%d and asked_by=%d ORDER BY id DESC",
                        $asking_attendee->webinar_id,
                        $asking_attendee->id,
                    )
                );
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $chatRecords = $wpdb->get_results(
                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                    $wpdb->prepare("SELECT * FROM {$chat_table} WHERE webinar_id=%d and attendee_id=%d AND is_simulated_chat = 0 ORDER BY id DESC",
                        $asking_attendee->webinar_id,
                        $asking_attendee->id,
                    )
                );

                //file_put_contents('custom-log.txt', json_encode($data), FILE_APPEND);
                if (count($vote_records) == 0 && count($questionsRecords) == 0 && count($chatRecords) == 0) {
                    WebinarSysteemSubscribe::custom_subscribe($asking_attendee->webinar_id, $asking_attendee->email, $asking_attendee->name, 'Interacted (Questions, Polls)');
                }

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->replace(
                    WebinarSysteemTables::get_questions(),
                    [
                        'id' => $data->id,
                        'name' => sanitize_text_field($asking_attendee->name),
                        'email' => sanitize_text_field($asking_attendee->email),
                        'question' => str_replace('\\', '', sanitize_textarea_field($data->question)),
                        'time' => $timestamp,
                        'webinar_id' => $webinar->id,
                        'asked_by' => $asking_attendee->id,
                        'is_private' => $data->isPrivate
                    ]
                );

                // email to host if setup
                (new WebinarSysteemEmails())
                    ->send_question_to_host(
                        $webinar->id,
                        $asking_attendee->name,
                        $asking_attendee->email,
                        $data->question
                    );
                break;

            case 'delete-question':
                // team members can delete anyone's chats
                if ($attendee->isTeamMember) {
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->delete(
                        WebinarSysteemTables::get_questions(),
                        ['id' => $data->id],
                        ['%d']
                    );
                    return;
                }

                // make sure that this attendee sent the message or they are a team member
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->delete(
                    WebinarSysteemTables::get_questions(),
                    ['id' => $data->id, 'asked_by' => $attendee->id],
                    ['%d', '%d']
                );
                break;


            case 'set-webinar-answer':
                // only team members can set answers
                if (!$attendee->isTeamMember) {
                    return;
                }

                $asking_attendee = WebinarSysteemAttendees::get_attendee_by_id($attendee->id);

                $vote_table = WebinarSysteemTables::get_poll_votes();
                $tableName = WebinarSysteemTables::get_questions();
                $chat_table = WebinarSysteemTables::get_chats();

                if ($attendee === null) {
                    wp_send_json_error(null, 422);
                    return;
                }

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $vote_records = $wpdb->get_results(
                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                    $wpdb->prepare("SELECT * FROM {$vote_table} WHERE webinar_id=%d and attendee_id=%d ORDER BY id DESC",
                        $asking_attendee->webinar_id,
                        $asking_attendee->id,
                    )
                );
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $questionsRecords = $wpdb->get_results(
                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                    $wpdb->prepare("SELECT * FROM {$tableName} WHERE webinar_id=%d and asked_by=%d ORDER BY id DESC",
                        $asking_attendee->webinar_id,
                        $asking_attendee->id,
                    )
                );
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $chatRecords = $wpdb->get_results(
                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                    $wpdb->prepare("SELECT * FROM {$chat_table} WHERE webinar_id=%d and attendee_id=%d AND is_simulated_chat = 0 ORDER BY id DESC",
                        $asking_attendee->webinar_id,
                        $asking_attendee->id,
                    )
                );

                //file_put_contents('custom-log.txt', json_encode($data), FILE_APPEND);
                if (count($vote_records) == 0 && count($questionsRecords) == 0 && count($chatRecords) == 0) {
                    WebinarSysteemSubscribe::custom_subscribe($asking_attendee->webinar_id, $asking_attendee->email, $asking_attendee->name, 'Interacted (Questions, Polls)');
                }

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->update(
                    WebinarSysteemTables::get_questions(),
                    [
                        'answered_at' => current_time('mysql', 1),
                        'answered_by' => $attendee->id,
                        'answer' => str_replace('\\', '', sanitize_textarea_field($data->answer)),
                    ],
                    [
                        'id' => $data->questionId,
                        'webinar_id' => $webinar->id
                    ]
                );
                break;

            case 'clear-webinar-answer':
                // only team members can set answers
                if (!$attendee->isTeamMember) {
                    return;
                }

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->update(
                    WebinarSysteemTables::get_questions(),
                    [
                        'answered_at' => null,
                        'answered_by' => null,
                        'answer' => null,
                    ],
                    [
                        'id' => $data->questionId,
                        'webinar_id' => $webinar->id
                    ]
                );
                break;

            case 'set-question-visibility':
                // only team members can set answers
                if (!$attendee->isTeamMember) {
                    return;
                }

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->update(
                    WebinarSysteemTables::get_questions(),
                    [
                        'is_private' => $data->isPrivate
                    ],
                    [
                        'id' => $data->questionId,
                        'webinar_id' => $webinar->id
                    ]
                );
                break;

            case 'enable-chat':
                // only team members can set answers
                if (!$attendee->isTeamMember) {
                    return;
                }
                $webinar->set_chat_enabled($data->enabled);
                break;

            case 'enable-questions':
                // only team members can set answers
                if (!$attendee->isTeamMember) {
                    return;
                }
                $webinar->set_questions_enabled($data->enabled);
                break;

            case 'enable-attendees-tab':
                // only team members can set answers
                if (!$attendee->isTeamMember) {
                    return;
                }
                $webinar->set_attendees_tab_enabled($data->enabled);
                break;

            case 'enable-hand-raising':
                // only team members can set answers
                if (!$attendee->isTeamMember) {
                    return;
                }
                $webinar->set_hand_raising_enabled($data->enabled);
                break;

            case 'enable-cta':
                // only team members can set answers
                if (!$attendee->isTeamMember) {
                    return;
                }
                $webinar->set_cta_enabled($data->enabled);
                break;

            case 'set-webinar-status':
                // only team members can set answers
                //file_put_contents('custom-log.txt', json_encode($data), FILE_APPEND);
                if (!$attendee->isTeamMember) {
                    return;
                }
                $webinar->set_status($data->status);
                $webinar->set_went_live_at_timestamp($data->wentLiveAt / 1000);

                //Apply action tags
                if (isset($data->manage_tags) && $data->manage_tags == 'true') {
                    $custom_req = new stdClass();
                    $custom_req->manage_tags = $data->manage_tags;
                    $custom_req->webinar_id = $webinar->id;
                    if (!wp_next_scheduled('apply_action_tag_after_complete_webinar_event')) {
                        wp_schedule_single_event(time(), 'apply_action_tag_after_complete_webinar_event', array($custom_req));
                    }
                }

                break;

            case 'update-last-seen':
                // From v2.22.1 updates are handled in js so we can check that
                // the attendee still has a valid session
                break;

            case 'set-media-source':
                if (!$attendee->isTeamMember) {
                    return;
                }
                $webinar->set_live_media_type($data->type);
                $webinar->set_live_media_url($data->url);
                break;

            case 'launch-poll':
                if (!$attendee->isTeamMember) {
                    return;
                }
                $webinar->set_enabled_poll_id($data->poll_id);
                break;

            case 'close-poll':
                if (!$attendee->isTeamMember) {
                    return;
                }
                $webinar->clear_enabled_poll_id();
                break;

            default:
                break;
        }
    }

    /**
     * Process an array of pending webinar messages
     * @param WebinarSysteemWebinar $webinar
     * @param array $messages
     **/

    static function process_messages($webinar, $messages)
    {
        WebinarSysteemLog::log("Processing " . count($messages) . " messages for {$webinar->id}");

        foreach ($messages as $message) {
            self::process_message($webinar, $message);
        }

        // update the cache
        WebinarSysteemWebinarCache::write($webinar->id);
    }
}
