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

153 lines
5.0 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 'google/config_google.php';
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'praticien') {
die("Accès interdit.");
}
$praticien_id = $_SESSION['reference_id'];
// Récupération du token Google
$stmt = $pdo->prepare("SELECT access_token, refresh_token, expires_at FROM google_tokens WHERE praticien_id = ?");
$stmt->execute([$praticien_id]);
$tokenData = $stmt->fetch();
if (!$tokenData) {
die("⚠️ Connectez-vous à Google d'abord.");
}
// Rafraîchir le token si expiré
$access_token = $tokenData['access_token'];
if (time() >= $tokenData['expires_at']) {
$config = require 'google/config_google.php';
$data = [
'client_id' => $config['client_id'],
'client_secret' => $config['client_secret'],
'refresh_token' => $tokenData['refresh_token'],
'grant_type' => 'refresh_token'
];
$opts = [
'http' => [
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded",
'content' => http_build_query($data)
]
];
$response = file_get_contents('https://oauth2.googleapis.com/token', false, stream_context_create($opts));
$tokens = json_decode($response, true);
if (!isset($tokens['access_token'])) {
die("❌ Erreur lors du rafraîchissement du token Google.");
}
$access_token = $tokens['access_token'];
$refresh_token = $tokens['refresh_token'] ?? $tokenData['refresh_token'];
$expires_at = time() + $tokens['expires_in'];
$stmt = $pdo->prepare("UPDATE google_tokens SET access_token = ?, refresh_token = ?, expires_at = ? WHERE praticien_id = ?");
$stmt->execute([$access_token, $refresh_token, $expires_at, $praticien_id]);
}
// Récupérer les RDV non encore synchronisés
$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.google_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 = [
"summary" => "Rendez-vous avec $nom_patient",
"start" => [
"dateTime" => $start,
"timeZone" => "Europe/Paris"
],
"end" => [
"dateTime" => $end,
"timeZone" => "Europe/Paris"
],
"description" => "RDV Avec : $nom_patient"
];
$ch = curl_init("https://www.googleapis.com/calendar/v3/calendars/primary/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 === 200 && isset($data['id'])) {
$stmtUpdate = $pdo->prepare("UPDATE rendez_vous SET google_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 avec bouton au milieu
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">Синхронизация с Google Календарём завершена</h2>
<p class="mb-3">
Успешно синхронизировано <strong>{$success} {$successLabel}</strong> с Google Календарём.
</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;
?>