yogiboook_new/public/userarea/api/api_user_schools.php
2025-12-27 20:48:44 +01:00

89 lines
3.1 KiB
PHP

<?php
// public/userarea/api/api_user_schools.php
// Returns ONLY the schools where the authenticated user is enrolled.
declare(strict_types=1);
require_once __DIR__ . '/_bootstrap.php'; // provides $pdo, $iduserlogin
try {
// Optional user info for greeting
$stmt = $pdo->prepare("SELECT first_name, avatar FROM auth_users WHERE id = ? LIMIT 1");
$stmt->execute([$iduserlogin]);
$user = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
// User schools only
$stmt = $pdo->prepare("
SELECT
s.id,
s.name,
s.logo,
s.address_street,
s.address_postal_code,
s.address_city,
s.address_province,
s.address_country
FROM user_schools us
JOIN schools s ON us.school_id = s.id
WHERE us.user_id = ?
AND us.status = 'active'
AND s.status = 'active'
ORDER BY s.name
");
$stmt->execute([$iduserlogin]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$schools = array_map(function (array $s): array {
$street = trim((string)($s['address_street'] ?? ''));
$zip = trim((string)($s['address_postal_code'] ?? ''));
$city = trim((string)($s['address_city'] ?? ''));
$prov = trim((string)($s['address_province'] ?? ''));
$cntry = trim((string)($s['address_country'] ?? ''));
$line2Parts = [];
if ($zip !== '') $line2Parts[] = $zip;
if ($city !== '') $line2Parts[] = $city;
$line2 = implode(' ', $line2Parts);
if ($prov !== '') $line2 .= ' (' . $prov . ')';
if ($cntry !== '') $line2 .= ' - ' . $cntry;
return [
'id' => (int)$s['id'],
'name' => (string)($s['name'] ?? ''),
'logo' => ($s['logo'] ?? null) !== null && trim((string)$s['logo']) !== '' ? (string)$s['logo'] : null,
'address_street' => $street !== '' ? $street : null,
'address_postal_code' => $zip !== '' ? $zip : null,
'address_city' => $city !== '' ? $city : null,
'address_province' => $prov !== '' ? $prov : null,
'address_country' => $cntry !== '' ? $cntry : null,
'address_full' => trim($street . ($street && $line2 ? ', ' : '') . $line2),
];
}, $rows);
$autoSelect = (count($schools) === 1);
$selectedSchoolId = $autoSelect ? (int)$schools[0]['id'] : null;
echo json_encode([
'success' => true,
'auto_select' => $autoSelect,
'selected_school_id' => $selectedSchoolId,
'user' => [
'id' => $iduserlogin,
'first_name' => $user['first_name'] ?? null,
'avatar' => $user['avatar'] ?? null,
],
'schools' => $schools,
'message' => empty($schools)
? 'No active schools assigned to this user. Please contact your school.'
: null
], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
http_response_code(500);
echo json_encode([
'success' => false,
'message' => 'Server error.',
'error' => $e->getMessage()
]);
}