Jake Vanderwerf
2026-03-29 275c0d74cd68677622a5431505c5c870c473063d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
<?php
namespace JVBase\rest\routes;
 
use JVBase\JVB;
use JVBase\rest\PermissionHandler;
use JVBase\rest\Rest;
use JVBase\managers\Cache;
use JVBase\meta\Meta;
use JVBase\meta\Sanitizer;
use JVBase\rest\Route;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use Exception;
 
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
class SettingsRoutes extends Rest
{
    protected int $count;
    public function __construct()
    {
        $this->cacheName = 'user_settings';
        parent::__construct();
//        $this->action = 'dash-';
//        $this->operation_type = 'user_settings';
        $this->count = 1;
        add_filter(BASE.'handle_bulk_operation', [$this, 'processOperation'], 10, 3);
    }
 
    /**
     * Registers Settings Routes
     * @return void
     */
    public function registerRoutes():void
    {
        Route::for('settings')
            ->post([$this, 'saveSettings'])
            ->auth(PermissionHandler::combine(['admin', ['actionNonce' => 'dash-']]))
            ->rateLimit(20)
            ->register();
    }
 
    /**
     * @param WP_REST_Request $request
     *
     * @return WP_REST_Response
     */
    public function saveSettings(WP_REST_Request $request):WP_REST_Response
    {
 
        $data = $request->get_params();
        error_log('User: '.print_r($data['user'], true));
        error_log('Settings routes data: '.print_r($data, true));
        $user_id = absint($data['user']??0);
        if ($user_id === 0) {
            return $this->unauthorized();
        }
 
 
        $fields = JVB()->getFields('user');
        $meta = new Sanitizer();
        $add = [];
        global $types;
        foreach ($data as $name => $value) {
            if (!array_key_exists($name, $fields)) {
                if ($name === 'notification_preferences') {
                    foreach ($value as $type => $options) {
                        if (array_key_exists(BASE.$type, $types)) {
                            $add[$type] = $options;
                        }
                    }
                }
                unset($data[$name]);
            } else {
                //Sanitize values
                $data[$name] = $meta->sanitize($value, $fields[$name]);
                if ($name === 'notify') {
                    Cache::for('usernames')->forget($user_id);
                }
            }
        }
        if (!empty($add)) {
            $data['notification_preferences'] = $add;
        }
 
        JVB()->queue()->queueOperation(
            'user_settings',
            $user_id,
            $data,
            [
                'count'   => 1,
            ]
        );
 
        return $this->success([
            'message' => 'Request received and queued',
            'status' => 'queued'
        ]);
    }
 
    /**
     * @param WP_Error|array $result
     * @param object $operation
     * @param array $data
     *
     * @return WP_Error|array
     */
    public function processOperation(WP_Error|array $result, object $operation, array $data):array|WP_Error
    {
        if ($operation->type !== 'user_settings') {
            return $result;
        }
 
 
        $user_id = $operation->user_id;
        $meta = Meta::forUser($user_id);
        $results = [];
        $tempMeta = Meta::forOptions('options');
        foreach ($data as $name => $value) {
            if ($name == 'notification_preferences') {
                return $this->saveNotificationPreferences($user_id, $value);
            }
 
            $temp = (is_array($value)) ? $value : json_decode($value);
 
            if (is_array($temp)) {
                $value = [];
                foreach ($temp as $t) {
                    if (is_object($t)) {
                        $t = (array)$t;
                    }
                    $value[] = $t;
                }
            }
 
            if ($name !== 'digest_override') { // digest_override should always reset to 'off'
                if(array_key_exists($name, JVB_OPTIONS)) {
                    $results[] = $tempMeta->set($name, $value);
                } else {
                    $results[] = $meta->set($name, $value);
                }
 
            }
            $this->cache->flush();
        }
 
        return [
            'success'   => true,
            'result'   => $results,
        ];
    }
 
    /**
     * @param int $user_id
     * @param array $data
     *
     * @return WP_Error|array
     */
    protected function saveNotificationPreferences(int $user_id, array $data):array|WP_Error
    {
        //TODO: This should be in with Notifications.php manager
        //TODO: Check what cache we are using to store user's preferences for the daily/weekly/monthly sendouts
        global $wpdb;
        $table = $wpdb->prefix . BASE . 'notification_preferences';
 
        if (!$this->checkUser($user_id)) {
            return [
                'success' => false,
                'result' =>  'User must be logged in to save preferences',
            ];
        }
        error_log('User Preferences: '.print_r($data, true));
        $wpdb->query('START TRANSACTION');
 
        try {
            // Get global email digest setting (if provided)
            $email_digest = get_user_meta($user_id, BASE . 'email_digest', true) ?: 'never';
 
            // Process notification preferences by type
            foreach ($data as $type => $items) {
                if (!is_array($items)) {
                    continue;
                }
 
                foreach ($items as $item_id => $frequency) {
                    // Validate frequency
                    $valid_frequencies = ['never', 'daily', 'weekly', 'monthly'];
                    if (!in_array($frequency, $valid_frequencies)) {
                        continue;
                    }
 
                    // Replace or insert preference
                    $result = $wpdb->replace(
                        $table,
                        [
                            'user_id' => $user_id,
                            'notification_type' => $type,
                            'item_id' => $item_id,
                            'frequency' => $frequency,
                            'created_at' => current_time('mysql'),
                            'updated_at' => current_time('mysql')
                        ],
                        ['%d', '%s', '%d', '%s', '%s', '%s']
                    );
 
                    if ($wpdb->last_error) {
                        throw new Exception($wpdb->last_error);
                    }
                }
            }
 
            // Success - commit transaction
            $wpdb->query('COMMIT');
 
            $this->cache->flush();
            return [
                'success' => true,
                'result' => 'Notification preferences updated successfully'
            ];
 
        } catch (Exception $e) {
            // Failure - rollback transaction
            $wpdb->query('ROLLBACK');
            error_log('Error saving notification preferences: ' . $e->getMessage());
 
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
}