<?php
if (!defined('ABSPATH')) exit;

class ASSI_History {

    public static function createEntry($requestId = '', $isSystem = true, $templateId = 0, $type = '', $category = '', $createDate = '', $data = array()) {
        if (empty($requestId) || $templateId <= 0 || empty($type) || empty($category) || empty($data)) {
            return false;
        }
        if (empty($createDate)) {
            $createDate = gmdate('Y-m-d H:i:s');
        }
        if (isset($data['request_data']['blog_user_token'])) {
            unset($data['request_data']['blog_user_token']);
        }
        if (isset($data['request_data']['request_id'])) {
            unset($data['request_data']['request_id']);
        }
        if (isset($data['request_data']['template_id'])) {
            unset($data['request_data']['template_id']);
        }

        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query($wpdb->prepare(
            "INSERT INTO `{$wpdb->prefix}assi_user_history` (`request_id`, `blog_user_id`, `is_system`, `template_id`, `type`, `category`, `create_date`, `data`) VALUES (%s, %d, %d, %d, %s, %s, %s, %s)",
            sanitize_text_field(wp_unslash($requestId)),
            (int) (defined('ASSI_PLUGIN_BLOG_USER_ID') ? ASSI_PLUGIN_BLOG_USER_ID : 0),
            ($isSystem ? 1 : 0),
            (int) $templateId,
            sanitize_text_field(wp_unslash($type)),
            sanitize_text_field(wp_unslash($category)),
            sanitize_text_field(wp_unslash($createDate)),
            wp_json_encode($data)
        ));
    }

    public static function convertNotificationToEntry($requestId = '') {
        if (empty($requestId)) {
            return false;
        }
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $dbResult = $wpdb->get_row($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}assi_user_notifications` WHERE `request_id` = %s AND `blog_user_id` = %d", sanitize_text_field(wp_unslash($requestId)), (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0)));
        if (isset($dbResult) && !empty($dbResult) && isset($dbResult->notification_data) && !empty($dbResult->notification_data)) {
            $dbResult = ASSI_Tools::sanitizeArrayOrObject($dbResult);
            $isSystem = (isset($dbResult->notification_data->request_data->is_system) && (bool) $dbResult->notification_data->request_data->is_system == false ? false : true);
            $templateId = (isset($dbResult->notification_data->request_data->template_id) ? (int) $dbResult->notification_data->request_data->template_id : 0);
            $historyData = array(
                'request_data' => (array) $dbResult->notification_data->request_data,
                'result_data' => (array) $dbResult->notification_data->ai_response->content
            );
            self::createEntry($requestId, $isSystem, $templateId, $dbResult->type, $dbResult->category, $dbResult->create_date, $historyData);
        }
        return false;
    }
    public static function updateEntryUrl($requestId = '', $url = '', $type = 'image') {
        if (empty($requestId) || empty($url) || ($type != 'image' && $type != 'audio')) {
            return false;
        }
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $entry = $wpdb->get_row($wpdb->prepare(
            "SELECT `data` FROM `{$wpdb->prefix}assi_user_history` WHERE `blog_user_id` = %d AND `request_id` = %s",
            (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0),
            $requestId
        ));
        if (!isset($entry->data) || empty($entry->data)) {
            return false;
        }
        $historyData = json_decode($entry->data, true);
        if (!is_array($historyData) || empty($historyData)) {
            return false;
        }
        if ($type == 'image') {
            if (isset($historyData['result_data']) && isset($historyData['result_data'][0]) && isset($historyData['result_data'][0]['image'])) {
                $historyData['result_data'][0]['image'] = $url;
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->update($wpdb->prefix . 'assi_user_history', array('data' => json_encode($historyData)), array('request_id' => $requestId));
                return true;
            }
        } else if ($type == 'audio') {
            if (isset($historyData['result_data']) && isset($historyData['result_data'][0]) && isset($historyData['result_data'][0]['audio'])) {
                $historyData['result_data'][0]['audio'] = $url;
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->update($wpdb->prefix . 'assi_user_history', array('data' => json_encode($historyData)), array('request_id' => $requestId));
                return true;
            }
        }
        return false;
    }
}