Files
maria_uslugi/synchroniser_outlook.php
2026-03-05 10:25:39 +01:00

130 lines
4.1 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
require_once __DIR__ . '/public/includes/init_praticien.php';
require_once 'includes/outlook_helper.php';
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'praticien') {
die("Accès interdit.");
}
$praticien_id = $_SESSION['reference_id'];
// Récupération du token Outlook
$stmt = $pdo->prepare("SELECT access_token, refresh_token, expires_at FROM outlook_tokens WHERE praticien_id = ?");
$stmt->execute([$praticien_id]);
$tokenData = $stmt->fetch();
if (!$tokenData) {
die("⚠️ Connectez-vous à Outlook d'abord.");
}
$access_token = $tokenData['access_token'];
if (time() >= $tokenData['expires_at']) {
require_once '../includes/outlook_refresh.php';
$access_token = refreshOutlookToken($pdo, $praticien_id);
if (!$access_token) {
die("❌ Impossible de rafraîchir le token.");
}
}
// Récupérer les RDV non encore synchronisés avec nom/prénom du client
$stmt = $pdo->prepare("
SELECT r.*, c.prenom, c.nom
FROM rendez_vous r
JOIN client c ON c.id = r.client_id
WHERE r.praticien_id = ? AND r.outlook_event_id IS NULL
");
$stmt->execute([$praticien_id]);
$rdvs = $stmt->fetchAll();
$success = 0;
$fail = 0;
foreach ($rdvs as $rdv) {
$nom_patient = $rdv['prenom'] . ' ' . $rdv['nom'];
$start = date('Y-m-d\TH:i:s', strtotime($rdv['date_rdv']));
$end = date('Y-m-d\TH:i:s', strtotime($rdv['date_rdv'] . ' +1 hour'));
$event = [
"subject" => "Rendez-vous avec $nom_patient",
"start" => [
"dateTime" => $start,
"timeZone" => "Europe/Paris"
],
"end" => [
"dateTime" => $end,
"timeZone" => "Europe/Paris"
],
"body" => [
"contentType" => "text",
"content" => "RDV Avec : $nom_patient"
]
];
$ch = curl_init("https://graph.microsoft.com/v1.0/me/events");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer $access_token",
"Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($event));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpcode === 201 && isset($data['id'])) {
$stmtUpdate = $pdo->prepare("UPDATE rendez_vous SET outlook_event_id = ? WHERE id = ?");
$stmtUpdate->execute([$data['id'], $rdv['id']]);
$success++;
} else {
$fail++;
echo "❌ Erreur RDV {$rdv['id']} - Code: $httpcode<br>";
}
}
// Pluriels russes
function ruPlural($n, $one, $few, $many){
$n = abs((int)$n);
$n1 = $n % 10; $n2 = $n % 100;
if ($n1 == 1 && $n2 != 11) return $one;
if ($n1 >= 2 && $n1 <= 4 && ($n2 < 10 || $n2 >= 20)) return $few;
return $many;
}
$successLabel = ruPlural($success, 'запись', 'записи', 'записей');
$failLabel = ruPlural($fail, 'ошибка синхронизации', 'ошибки синхронизации', 'ошибок синхронизации');
// Box centrée (horizontal + vertical)
echo '<link rel="stylesheet" href="/css/bootstrap.min.css">';
echo <<<HTML
<div class="container">
<div class="d-flex justify-content-center align-items-center" style="min-height:48vh;">
<div class="card shadow-lg border-0 text-center" style="max-width:720px; width:100%; border-radius:18px;">
<div class="card-body p-4">
<div class="display-6 mb-2">✅</div>
<h2 class="h4 mb-2">Синхронизация завершена</h2>
<p class="mb-3">
Успешно синхронизировано <strong>{$success} {$successLabel}</strong> с Outlook.
</p>
HTML;
if ((int)$fail > 0) {
echo <<<HTML
<p class="mb-3 text-danger fw-semibold">
Не удалось синхронизировать <strong>{$fail} {$failLabel}</strong>.
</p>
HTML;
}
echo <<<HTML
<a href="/public/praticien/agenda.php" class="btn btn-primary btn-lg rounded-pill">
Открыть календарь
</a>
</div>
</div>
</div>
</div>
HTML;
?>