Files
alrahma_sunday_school_api/app/Http/Controllers/Api/SettingsController.php
T
2026-03-05 12:29:37 -05:00

83 lines
2.5 KiB
PHP
Executable File

<?php
namespace App\Http\Controllers\Api;
use App\Models\Preferences;
use App\Models\Settings;
use Symfony\Component\HttpFoundation\Response;
class SettingsController extends BaseApiController
{
protected Preferences $preferences;
protected Settings $settings;
public function __construct()
{
parent::__construct();
$this->preferences = model(Preferences::class);
$this->settings = model(Settings::class);
}
public function preferences()
{
$user = $this->getCurrentUser();
if (!$user) {
return $this->respondError('Authentication required', Response::HTTP_UNAUTHORIZED);
}
$preference = $this->preferences->newQuery()
->where('user_id', $user->id)
->first();
return $this->success($preference ? $preference->toArray() : [], 'Preferences retrieved successfully');
}
public function updatePreferences()
{
$user = $this->getCurrentUser();
if (!$user) {
return $this->respondError('Authentication required', Response::HTTP_UNAUTHORIZED);
}
$data = $this->payloadData();
if (empty($data)) {
return $this->respondError('Invalid request data', Response::HTTP_BAD_REQUEST);
}
$allowedFields = ['timezone', 'language', 'notifications_enabled', 'email_notifications'];
$payload = ['user_id' => $user->id];
foreach ($allowedFields as $field) {
if (array_key_exists($field, $data)) {
$payload[$field] = $data[$field];
}
}
try {
$preference = $this->preferences->newQuery()
->updateOrCreate(['user_id' => $user->id], $payload);
return $this->success($preference->fresh()->toArray(), 'Preferences updated successfully');
} catch (\Throwable $e) {
log_message('error', 'Preferences update error: ' . $e->getMessage());
return $this->respondError('Failed to update preferences', Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
public function system()
{
$settings = $this->settings->newQuery()->get();
$formatted = [];
foreach ($settings as $setting) {
$row = $setting->toArray();
$key = $row['key'] ?? $row['name'] ?? null;
if ($key !== null) {
$formatted[$key] = $row['value'] ?? $row;
}
}
return $this->success($formatted, 'System settings retrieved successfully');
}
}