<?php

class WebinarSysteemSimulatedChat
{
    public static function list($id = NULL)
    {
        global $wpdb;

        $simulated_chat_table = WebinarSysteemTables::get_simulated_chat();

        $simulated_chat_filter = $id ? $wpdb->prepare("WHERE sc.id=%d", $id) : '';

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $simulated_chat = $wpdb->get_results("SELECT * FROM {$simulated_chat_table} AS sc {$simulated_chat_filter} ORDER BY sc.id DESC");

        return array_map(function ($row) {
            return (object) [
                'id' => (int) $row->id,
                'name' => $row->name,
                'config' => unserialize($row->config),
                'created_at' => $row->created_at
            ];
        }, $simulated_chat);
    }

    public static function delete($id)
    {
        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->delete(
            WebinarSysteemTables::get_simulated_chat(),
            [
                'id' => (int)$id
            ]
        );
    }

    public static function create_simulated_chat($name, $config)
    {
        global $wpdb;

        // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
        $timestamp = date('Y-m-d H:i:s');
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->insert(
            WebinarSysteemTables::get_simulated_chat(),
            [
                'name' => $name,
                'config' => serialize($config),
                'created_at' => $timestamp,

            ],
            ['%s', '%s', '%s']
        );

        return $wpdb->insert_id;
    }

    public static function update_simulated_chat($id, $name, $config)
    {
        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->update(
            WebinarSysteemTables::get_simulated_chat(),
            [
                'name' => $name,
                'config' => serialize($config)
            ],
            ['id' => $id],
            ['%s', '%s'],
            ['%d']
        );
    }
}
