<?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()
|
];
|
}
|
}
|
}
|