yogiboook_new/public/userarea/api/api_user_settings.php

81 lines
2.4 KiB
PHP

<?php
declare(strict_types=1);
require_once __DIR__ . '/_bootstrap.php'; // $pdo, $iduserlogin
try {
$user_id = (int)$iduserlogin;
if ($user_id <= 0) {
http_response_code(401);
echo json_encode(['success' => false, 'message' => 'Unauthorized']);
exit;
}
$defaults = [
'notify_email' => 1,
'notify_whatsapp' => 0,
'notify_push' => 0,
'notify_booking_confirm' => 1,
'notify_booking_cancel' => 1,
'notify_session_cancel' => 1,
'notify_payment_receipt' => 1,
'notify_expiration_reminder' => 1,
'newsletter_opt_in' => 0,
'marketing_opt_in' => 0,
'locale' => 'it',
'timezone' => 'Europe/Rome',
];
$stmt = $pdo->prepare("
SELECT *
FROM user_settings
WHERE user_id = ?
LIMIT 1
");
$stmt->execute([$user_id]);
$settings = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$settings) {
// Create row with defaults (user_id only required by your schema)
$ins = $pdo->prepare("INSERT INTO user_settings (user_id) VALUES (?)");
$ins->execute([$user_id]);
// Reload
$stmt = $pdo->prepare("SELECT * FROM user_settings WHERE user_id = ? LIMIT 1");
$stmt->execute([$user_id]);
$settings = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
}
$userSettings = array_merge($defaults, $settings);
// Cast numeric flags to int for Flutter
foreach (
[
'notify_email',
'notify_whatsapp',
'notify_push',
'notify_booking_confirm',
'notify_booking_cancel',
'notify_session_cancel',
'notify_payment_receipt',
'notify_expiration_reminder',
'newsletter_opt_in',
'marketing_opt_in',
] as $k
) {
if (isset($userSettings[$k])) {
$userSettings[$k] = is_numeric($userSettings[$k]) ? (int)$userSettings[$k] : $userSettings[$k];
}
}
echo json_encode([
'success' => true,
'user_id' => $user_id,
'settings' => $userSettings
], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Server error.', 'error' => $e->getMessage()]);
}