prepare("SELECT settings FROM integrations WHERE user_id = ? AND provider = 'OUTLOOK'"); $stmt->execute([$user['id']]); $row = $stmt->fetch(); $savedSettings = json_decode($row['settings'] ?? '{}', true) ?: []; $clientId = !empty($savedSettings['client_id']) ? $savedSettings['client_id'] : fociz_env('MICROSOFT_CLIENT_ID', ''); $clientSecret = !empty($savedSettings['client_secret']) ? $savedSettings['client_secret'] : fociz_env('MICROSOFT_CLIENT_SECRET', ''); $tenantId = !empty($savedSettings['tenant_id']) ? $savedSettings['tenant_id'] : fociz_env('MICROSOFT_TENANT_ID', 'common'); if (empty($clientId) || empty($clientSecret)) { header('Location: /integrations.php?error=' . urlencode('Client ID of Client Secret ontbreekt in Fociz. Vul deze eerst in bij de Outlook instellingen.')); exit; } $redirectUri = rtrim(APP_URL, '/') . '/auth/callback_microsoft.php'; // 5. Code omwisselen voor access & refresh tokens $tokenResult = microsoft_exchange_code($code, $clientId, $clientSecret, $redirectUri, $tenantId); if (!$tokenResult['success']) { header('Location: /integrations.php?error=' . urlencode('Token uitwisseling mislukt: ' . $tokenResult['error'])); exit; } $accessToken = $tokenResult['access_token']; $refreshToken = $tokenResult['refresh_token']; $expiresIn = $tokenResult['expires_in']; $expiresAt = time() + $expiresIn; // 6. Microsoft gebruikersprofiel ophalen $profile = microsoft_get_user_profile($accessToken); $accountEmail = $profile['mail'] ?? ($profile['userPrincipalName'] ?? $user['email']); $accountName = $profile['displayName'] ?? 'Microsoft 365 Account'; // 7. Opslaan in MariaDB $newSettings = array_merge($savedSettings, [ 'client_id' => $clientId, 'client_secret' => $clientSecret, 'tenant_id' => $tenantId, 'expires_at' => $expiresAt, 'account_email' => $accountEmail, 'account_name' => $accountName, ]); $saveStmt = $db->prepare(" INSERT INTO integrations (user_id, provider, is_enabled, is_demo_mode, access_token, refresh_token, settings, last_sync_at) VALUES (?, 'OUTLOOK', 1, 0, ?, ?, ?, NOW()) ON DUPLICATE KEY UPDATE is_enabled = 1, is_demo_mode = 0, access_token = VALUES(access_token), refresh_token = VALUES(refresh_token), settings = VALUES(settings), last_sync_at = NOW() "); $saveStmt->execute([$user['id'], $accessToken, $refreshToken, json_encode($newSettings)]); // 8. Succesvol terugkeren naar de Integraties Hub header('Location: /integrations.php?success=' . urlencode("Microsoft Outlook succesvol gekoppeld als {$accountEmail}!")); exit;