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

class ASSI_Notification {

    public static function createEditorNotification($requestId = '', $type = '', $category = '', $notificationData = array()) {
        global $wpdb;
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'type' => $type,
            'request_id' => $requestId,
            'notification_data' => array()
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'notification/create', $data);
        if (!isset($result->status) || $result->status != 'success' || !isset($result->notification_id) || (int) $result->notification_id < 1) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }
        $notificationId = (int) $result->notification_id;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        if (!$wpdb->query($wpdb->prepare(
            "INSERT INTO `{$wpdb->prefix}assi_user_notifications` (`notification_id`, `blog_user_id`, `type`, `category`, `request_id`, `status`, `create_date`, `notification_data`) VALUES (%d, %d, %s, %s, %s, %d, %s, %s)",
            $notificationId,
            (int) ASSI_PLUGIN_BLOG_USER_ID,
            $type,
            $category,
            $requestId,
            0,
            gmdate('Y-m-d H:i:s', time()),
            json_encode($notificationData),
        ))) {
            echo wp_json_encode(array('result' => false, 'error' => 'db_error'));
            wp_die();
        }
    }

    public static function createChatNotification($requestId = '', $sessionId = '', $localSessionId = '') {
        if (empty($requestId) || (empty($sessionId) && empty($localSessionId))) {
            return false;
        }
        $data = array(
            'blog_user_token' => ASSI_PLUGIN_BLOG_USER_TOKEN,
            'type' => 'chat',
            'request_id' => $requestId,
            'notification_data' => array(
                'session_id' => $sessionId,
                'local_session_id' => $localSessionId
            )
        );
        $result = ASSI_Request::post(ASSI_PLUGIN_API_WP_ENDPOINT . 'notification/create', $data);
        if (!isset($result->status) || $result->status != 'success' || !isset($result->notification_id) || (int) $result->notification_id < 1) {
            echo wp_json_encode(array('result' => false));
            wp_die();
        }

        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        if (!$wpdb->query($wpdb->prepare(
            "INSERT INTO `{$wpdb->prefix}assi_user_notifications` (`notification_id`, `blog_user_id`, `type`, `request_id`, `status`, `notification_data`) VALUES (%d, %d, %s, %s, %d, %s)",
            (int) $result->notification_id,
            (int) ASSI_PLUGIN_BLOG_USER_ID,
            'chat',
            $requestId,
            0,
            json_encode(array('session_id' => $sessionId, 'local_session_id' => $localSessionId))
        ))) {
            echo wp_json_encode(array('result' => false, 'error' => 'db_error'));
            wp_die();
        }
    }

    public static function getNotificationsHtml() {
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $notifications = $wpdb->get_results($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}assi_user_notifications` WHERE `blog_user_id` = %d", (defined('ASSI_PLUGIN_BLOG_USER_ID') ? (int) ASSI_PLUGIN_BLOG_USER_ID : 0)));
        if (!is_array($notifications) || empty($notifications)) {
            return false;
        }
        usort($notifications, function ($a, $b) {
            return strtotime($b->create_date) - strtotime($a->create_date);
        });
        $html = '';
        $wpDateFormat = get_option('date_format');
        $wpTimeFormat = get_option('time_format');
        foreach ($notifications as $notification) {
            $wpDate = wp_date($wpDateFormat . ' ' . $wpTimeFormat, strtotime($notification->create_date));
            if ($notification->type == 'chat') {
                $notificationData = json_decode($notification->notification_data);
                $html .= '<div class="ass-notification-item" data-id="' . (int)$notification->notification_id . '" data-type="' . esc_attr($notification->type) . '" data-session-id="' . esc_attr($notificationData->session_id) . '">';
                $html .= '<img class="ass-notification-avatar ass-notification-item-clickable mx-4" src="' . esc_url(plugins_url('/assets/images/ass_notification_icon.png', ASSI_PLUGIN_FILE)) . '" />';
                $html .= '<div class="ass-notification-content ass-notification-item-clickable py-4">';
                $html .= __('Your generated content is ready!', 'assistini');
                $html .= '<div class="d-flex flex-column">';
                $html .= '<small class="text-muted">' . $wpDate . '</small>';
                $html .= '</div>';
                $html .= '</div>';
                $html .= '<i class="ass-notification-item-delete bi bi-trash ass-size-18 me-4"></i>';
                $html .= '</div>';
            }
            if ($notification->type == 'payment') {
                $html .= '<div class="ass-notification-item" data-id="' . (int)$notification->notification_id . '" data-type="' . esc_attr($notification->type) . '">';
                $html .= '<img class="ass-notification-avatar ass-notification-item-clickable mx-4" src="' . esc_url(plugins_url('/assets/images/ass_notification_icon.png', ASSI_PLUGIN_FILE)) . '" />';
                $html .= '<div class="ass-notification-content ass-notification-item-clickable py-4">';
                $html .= __('Your plan has upgraded', 'assistini');
                $html .= '<div class="d-flex flex-column">';
                $html .= '<small class="text-muted">' . $wpDate . '</small>';
                $html .= '</div>';
                $html .= '</div>';
                $html .= '<i class="ass-notification-item-delete bi bi-trash ass-size-18 me-4"></i>';
                $html .= '</div>';
            }
        }
        return $html;
    }

    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 notification_data FROM `{$wpdb->prefix}assi_user_notifications` 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->notification_data) || empty($entry->notification_data)) {
            return false;
        }
        $notificationData = json_decode($entry->notification_data, true);
        if (!is_array($notificationData) || empty($notificationData)) {
            return false;
        }
        if ($type == 'image') {
            if (isset($notificationData['ai_response']) && isset($notificationData['ai_response']['content']) && isset($notificationData['ai_response']['content'][0]) && isset($notificationData['ai_response']['content'][0]['image'])) {
                $notificationData['ai_response']['content'][0]['image'] = $url;
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->update($wpdb->prefix . 'assi_user_notifications', array('notification_data' => json_encode($notificationData)), array('request_id' => $requestId));
                return true;
            }
        } else if ($type == 'audio') {
            if (isset($notificationData['ai_response']) && isset($notificationData['ai_response']['content']) && isset($notificationData['ai_response']['content'][0]) && isset($notificationData['ai_response']['content'][0]['audio'])) {
                $notificationData['ai_response']['content'][0]['audio'] = $url;
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->update($wpdb->prefix . 'assi_user_notifications', array('notification_data' => json_encode($notificationData)), array('request_id' => $requestId));
                return true;
            }
        }
        return false;
    }
}
