refonte socle
This commit is contained in:
@@ -2,3 +2,4 @@ househub_db_data
|
||||
.env
|
||||
data/.hh_app_secret
|
||||
extract_source.php
|
||||
.htaccess
|
||||
+69
-52
@@ -8,11 +8,33 @@ require_login();
|
||||
require __DIR__ . '/includes/db.php';
|
||||
require_once __DIR__ . '/includes/i18n.php';
|
||||
|
||||
$stmtPeople = $pdo->query("SELECT id, name, user_id, role FROM pf_people ORDER BY id ASC");
|
||||
// 1. Récupération de toutes les personnes avec leurs modes de garde
|
||||
$stmtPeople = $pdo->query("SELECT id, name, user_id, role, care_modes FROM pf_people ORDER BY id ASC");
|
||||
$familyPeople = $stmtPeople->fetchAll(PDO::FETCH_ASSOC);
|
||||
$parents = array_values(array_filter($familyPeople, function($p) {
|
||||
return strtolower($p['role'] ?? '') === 'parent';
|
||||
}));
|
||||
|
||||
$parents = [];
|
||||
$kids = [];
|
||||
|
||||
// Liste de tous les modes de garde actifs dans le foyer
|
||||
$activeCareModes = [];
|
||||
|
||||
foreach ($familyPeople as $p) {
|
||||
$role = strtolower($p['role'] ?? '');
|
||||
if ($role === 'parent') {
|
||||
$parents[] = $p;
|
||||
} elseif ($role === 'enfant') {
|
||||
// Décodage sécurisé des modes de garde
|
||||
$modes = json_decode($p['care_modes'] ?? '[]', true);
|
||||
if (!is_array($modes)) $modes = [];
|
||||
$p['modes'] = $modes;
|
||||
$kids[] = $p;
|
||||
|
||||
foreach ($modes as $m) {
|
||||
$activeCareModes[$m] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
$activeCareModes = array_keys($activeCareModes); // On récupère uniquement les noms uniques
|
||||
|
||||
$pageTitle = tr('fc_page_title');
|
||||
$activePage = "family-calendar";
|
||||
@@ -114,22 +136,17 @@ require __DIR__ . '/header.php';
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section class="pf-section">
|
||||
<div class="fc-month-calendar-wrapper">
|
||||
|
||||
<div class="fc-month-header">
|
||||
|
||||
<div class="fc-month-nav-row">
|
||||
<button id="fc-prev-month" class="fc-nav-button">‹</button>
|
||||
|
||||
<div id="fc-smart-date-selector" style="display:flex; align-items:center; justify-content:center; flex-grow:1; gap:6px;">
|
||||
<select id="fc-select-month" class="fc-smart-select"></select>
|
||||
<select id="fc-select-year" class="fc-smart-select"></select>
|
||||
<span id="fc-multi-month-suffix" style="display:none; font-size:1.3rem; font-weight:800; color:#0f172a; margin-left:4px;"></span>
|
||||
</div>
|
||||
|
||||
<button id="fc-next-month" class="fc-nav-button">›</button>
|
||||
</div>
|
||||
|
||||
@@ -139,7 +156,6 @@ require __DIR__ . '/header.php';
|
||||
<button class="fc-view-button" data-view="2months"><?= tr('fc_view_2m') ?></button>
|
||||
<button class="fc-view-button" data-view="3months"><?= tr('fc_view_3m') ?></button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="fc-calendar-container">
|
||||
@@ -148,7 +164,6 @@ require __DIR__ . '/header.php';
|
||||
</div>
|
||||
|
||||
<div id="fc-month-balances" class="fc-month-balances"></div>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -173,18 +188,29 @@ require __DIR__ . '/header.php';
|
||||
<th rowspan="3" class="col-day"><?= tr('day_wed') ?></th>
|
||||
<th rowspan="3" class="col-day"><?= tr('day_thu') ?></th>
|
||||
<th rowspan="3" class="col-day"><?= tr('day_fri') ?></th>
|
||||
<th rowspan="3" class="col-total rotated-text"><span><?= tr('leg_off_carole') ?></span></th>
|
||||
<th rowspan="3" class="col-total rotated-text"><span><?= tr('leg_extra_off') ?></span></th>
|
||||
<th rowspan="3" class="col-total rotated-text"><span><?= tr('leg_centre') ?></span></th>
|
||||
<th rowspan="3" class="col-total rotated-text"><span><?= tr('leg_avis') ?></span></th>
|
||||
<th rowspan="3" class="col-total rotated-text"><span><?= tr('leg_pep_sick') ?></span></th>
|
||||
<th rowspan="3" class="col-total rotated-text"><span><?= tr('leg_presence') ?></span></th>
|
||||
<th colspan="6" class="col-alex header-group"><?= htmlspecialchars(strtoupper($parents[0]['name'] ?? 'PARENT 1')) ?></th>
|
||||
<th colspan="6" class="col-laia header-group"><?= htmlspecialchars(strtoupper($parents[1]['name'] ?? 'PARENT 2')) ?></th>
|
||||
|
||||
<?php foreach ($activeCareModes as $mode): ?>
|
||||
<th rowspan="3" class="col-total rotated-text"><span><?= htmlspecialchars($mode) ?></span></th>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<?php foreach ($kids as $kid): ?>
|
||||
<th rowspan="3" class="col-total rotated-text"><span>Maladie <?= htmlspecialchars($kid['name']) ?></span></th>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<?php foreach ($parents as $index => $parent):
|
||||
$parentClass = ($index % 2 === 0) ? 'col-alex' : 'col-laia';
|
||||
?>
|
||||
<th colspan="6" class="<?= $parentClass ?> header-group"><?= htmlspecialchars(strtoupper($parent['name'])) ?></th>
|
||||
<?php endforeach; ?>
|
||||
</tr>
|
||||
<tr>
|
||||
<th colspan="2" class="col-alex-sub">CP</th><th colspan="2" class="col-alex-sub">JRA</th><th colspan="2" class="col-alex-sub">JA</th>
|
||||
<th colspan="2" class="col-laia-sub">CP</th><th colspan="2" class="col-laia-sub">JRA</th><th colspan="2" class="col-laia-sub">JA</th>
|
||||
<?php foreach ($parents as $index => $parent):
|
||||
$parentClass = ($index % 2 === 0) ? 'col-alex' : 'col-laia';
|
||||
?>
|
||||
<th colspan="2" class="<?= $parentClass ?>-sub">CP</th>
|
||||
<th colspan="2" class="<?= $parentClass ?>-sub">JRA</th>
|
||||
<th colspan="2" class="<?= $parentClass ?>-sub">JA</th>
|
||||
<?php endforeach; ?>
|
||||
</tr>
|
||||
<tr>
|
||||
<?php foreach ($parents as $index => $parent):
|
||||
@@ -230,11 +256,23 @@ require __DIR__ . '/header.php';
|
||||
<div class="pf-legend-grid">
|
||||
<div class="pf-legend-item"><div class="pf-legend-color fc-legend-school-holiday"></div><span><?= tr('leg_school_holidays') ?></span></div>
|
||||
<div class="pf-legend-item"><div class="pf-legend-color fc-legend-public-holiday"></div><span><?= tr('leg_public_holiday') ?></span></div>
|
||||
<div class="pf-legend-item"><div class="pf-legend-color fc-legend-off-carole"></div><span><?= tr('leg_off_carole') ?></span></div>
|
||||
<div class="pf-legend-item"><div class="pf-legend-color fc-legend-extra-off-carole"></div><span><?= tr('leg_extra_off') ?></span></div>
|
||||
<div class="pf-legend-item"><div class="pf-legend-color fc-legend-centre"></div><span><?= tr('leg_centre') ?></span></div>
|
||||
<div class="pf-legend-item"><div class="pf-legend-color fc-legend-avis"></div><span><?= tr('leg_avis') ?></span></div>
|
||||
<div class="pf-legend-item"><div class="pf-legend-color fc-legend-pep-sick"></div><span><?= tr('leg_pep_sick') ?></span></div>
|
||||
|
||||
<?php foreach ($activeCareModes as $index => $mode):
|
||||
// Génération d'une couleur pseudo-aléatoire mais fixe par mode
|
||||
$hue = ($index * 137) % 360;
|
||||
?>
|
||||
<div class="pf-legend-item">
|
||||
<div class="pf-legend-color" style="background: hsl(<?= $hue ?>, 70%, 50%);"></div>
|
||||
<span><?= htmlspecialchars($mode) ?></span>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<?php foreach ($kids as $kid): ?>
|
||||
<div class="pf-legend-item">
|
||||
<div class="pf-legend-color" style="background: var(--pf-danger, #ef4444); opacity: 0.8;"></div>
|
||||
<span>Maladie <?= htmlspecialchars($kid['name']) ?></span>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -243,32 +281,11 @@ require __DIR__ . '/header.php';
|
||||
</div>
|
||||
|
||||
<script>
|
||||
window.I18N = {
|
||||
...(window.I18N || {}),
|
||||
'fc_menu_carole': "<?= tr('fc_menu_carole') ?>",
|
||||
'btn_off': "<?= tr('btn_off') ?>",
|
||||
'btn_extra': "<?= tr('btn_extra') ?>",
|
||||
'leg_centre': "<?= tr('leg_centre') ?>",
|
||||
'leg_avis': "<?= tr('leg_avis') ?>",
|
||||
'leg_pep_sick': "<?= tr('leg_pep_sick') ?>",
|
||||
'leg_off_carole': "<?= tr('leg_off_carole') ?>",
|
||||
'leg_extra_off': "<?= tr('leg_extra_off') ?>",
|
||||
'leg_presence': "<?= tr('leg_presence') ?>",
|
||||
'fc_menu_kids_leaves': "<?= tr('fc_menu_kids_leaves') ?>",
|
||||
'fc_clear': "<?= tr('fc_clear') ?>",
|
||||
'fc_unit_days': "<?= tr('fc_unit_days') ?>",
|
||||
'vac_toussaint': "<?= tr('vac_toussaint') ?>",
|
||||
'vac_noel': "<?= tr('vac_noel') ?>",
|
||||
'vac_hiver': "<?= tr('vac_hiver') ?>",
|
||||
'vac_printemps': "<?= tr('vac_printemps') ?>",
|
||||
'vac_ascension': "<?= tr('vac_ascension') ?>",
|
||||
'vac_ete': "<?= tr('vac_ete') ?>",
|
||||
'leg_school_holidays': "<?= tr('leg_school_holidays') ?>",
|
||||
'fc_school_year': "<?= tr('fc_school_year') ?>",
|
||||
'fc_modal_holidays_title': "<?= tr('fc_modal_holidays_title') ?>",
|
||||
'fc_alert_burn_days': "<?= tr('fc_alert_burn_days') ?>",
|
||||
'fc_alert_burn_jra': "<?= tr('fc_alert_burn_jra') ?>",
|
||||
'ANNIV': "<?= tr('ANNIV') ?>"
|
||||
// 🟢 OBJET DE CONFIGURATION GLOBAL POUR LE JAVASCRIPT
|
||||
window.FAMILY_CONFIG = {
|
||||
parents: <?= json_encode($parents) ?>,
|
||||
kids: <?= json_encode($kids) ?>,
|
||||
activeCareModes: <?= json_encode($activeCareModes) ?>
|
||||
};
|
||||
</script>
|
||||
<script src="/modules/family-calendar/family-calendar.js"></script>
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* HouseHub - CSS Auditor 🦙
|
||||
* Génère un rapport complet de tous les styles (fichiers, balises, inline)
|
||||
*/
|
||||
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
|
||||
$root = __DIR__;
|
||||
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root));
|
||||
$report = "=== 🦙 RAPPORT CSS COMPLET HOUSEHUB ===\n";
|
||||
$report .= "Généré le : " . date('Y-m-d H:i:s') . "\n\n";
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
if ($file->isDir()) continue;
|
||||
|
||||
$filePath = $file->getPathname();
|
||||
$relativePath = str_replace($root, '', $filePath);
|
||||
$ext = pathinfo($filePath, PATHINFO_EXTENSION);
|
||||
|
||||
// 1. EXTRACTION DES FICHIERS .css
|
||||
if ($ext === 'css') {
|
||||
$report .= "/* 📄 FICHIER SOURCE : $relativePath */\n";
|
||||
$report .= file_get_contents($filePath) . "\n";
|
||||
$report .= str_repeat("-", 40) . "\n\n";
|
||||
}
|
||||
|
||||
// 2. EXTRACTION DES BALISES <style> ET ATTRIBUTS style="" DANS LES .php
|
||||
if ($ext === 'php') {
|
||||
$content = file_get_contents($filePath);
|
||||
$foundInFile = false;
|
||||
|
||||
// Extraction des blocs <style>
|
||||
if (preg_match_all('/<style[^>]*>(.*?)<\/style>/is', $content, $matches)) {
|
||||
if (!$foundInFile) { $report .= "/* 📄 FICHIER SOURCE : $relativePath */\n"; $foundInFile = true; }
|
||||
foreach ($matches[1] as $idx => $styleBlock) {
|
||||
$report .= "/* Bloc <style> #$idx */\n";
|
||||
$report .= trim($styleBlock) . "\n";
|
||||
}
|
||||
}
|
||||
|
||||
// Extraction des styles inline style="..."
|
||||
// On capture le tag pour donner du contexte au style inline
|
||||
if (preg_match_all('/<([a-z0-9]+)[^>]*?\sstyle=["\']([^"]*?)["\'][^>]*>/i', $content, $matches)) {
|
||||
if (!$foundInFile) { $report .= "/* 📄 FICHIER SOURCE : $relativePath */\n"; $foundInFile = true; }
|
||||
foreach ($matches[0] as $idx => $fullTag) {
|
||||
// On nettoie un peu pour ne garder que l'essentiel du tag et son style
|
||||
$report .= "/* Style Inline #$idx */\n";
|
||||
$report .= trim($fullTag) . "\n";
|
||||
}
|
||||
}
|
||||
|
||||
if ($foundInFile) {
|
||||
$report .= str_repeat("-", 40) . "\n\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
echo $report;
|
||||
@@ -1,72 +0,0 @@
|
||||
<?php
|
||||
// generate_prompt.php - Script pour extraire le code de HouseHub
|
||||
// À lancer via le navigateur (http://localhost:8082/generate_prompt.php) ou en ligne de commande.
|
||||
|
||||
$rootDir = __DIR__;
|
||||
$outputFile = $rootDir . '/househub_source.md';
|
||||
|
||||
// Dossiers à ignorer (pour ne pas polluer le cerveau de l'IA avec des choses inutiles)
|
||||
$ignoredDirs = ['.git', '.devtools', '.gitea', 'assets'];
|
||||
|
||||
// Extensions autorisées (on ne veut que du code, pas d'images)
|
||||
$allowedExtensions = ['php', 'css', 'js', 'html', 'sh'];
|
||||
|
||||
$output = "# 🦙 Source Code HouseHub\n\n";
|
||||
$output .= "> *Généré le " . date('Y-m-d H:i:s') . "*\n\n";
|
||||
|
||||
$iterator = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($rootDir, RecursiveDirectoryIterator::SKIP_DOTS),
|
||||
RecursiveIteratorIterator::SELF_FIRST
|
||||
);
|
||||
|
||||
$fileCount = 0;
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
if ($file->isFile()) {
|
||||
// Chemin relatif propre
|
||||
$relativePath = str_replace($rootDir . DIRECTORY_SEPARATOR, '', $file->getPathname());
|
||||
$relativePath = str_replace('\\', '/', $relativePath); // Uniformiser pour Windows
|
||||
|
||||
// Vérification des dossiers ignorés
|
||||
$skip = false;
|
||||
foreach ($ignoredDirs as $ignored) {
|
||||
if (strpos($relativePath, $ignored) === 0) {
|
||||
$skip = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($skip) continue;
|
||||
|
||||
// Vérification de l'extension
|
||||
$ext = strtolower($file->getExtension());
|
||||
if (!in_array($ext, $allowedExtensions)) continue;
|
||||
|
||||
// On ignore ce script lui-même
|
||||
if ($file->getFilename() === 'generate_prompt.php') continue;
|
||||
|
||||
// Lecture du contenu
|
||||
$content = file_get_contents($file->getPathname());
|
||||
|
||||
// Détermination du langage pour le bloc Markdown
|
||||
$lang = $ext === 'php' ? 'php' : ($ext === 'js' ? 'javascript' : $ext);
|
||||
|
||||
// Formatage pour l'IA
|
||||
$output .= "### 📄 Fichier : `" . $relativePath . "`\n";
|
||||
$output .= "```" . $lang . "\n";
|
||||
$output .= $content . "\n";
|
||||
$output .= "```\n\n";
|
||||
$output .= "---\n\n";
|
||||
|
||||
$fileCount++;
|
||||
}
|
||||
}
|
||||
|
||||
file_put_contents($outputFile, $output);
|
||||
|
||||
echo "<div style='font-family:sans-serif; padding:20px; background:#f0fdf4; color:#16a34a; border-radius:8px; border:1px solid #bbf7d0;'>";
|
||||
echo "<h2>✅ Succès !</h2>";
|
||||
echo "<p>Le fichier <strong>househub_source.md</strong> a été généré à la racine de ton projet.</p>";
|
||||
echo "<p><strong>$fileCount fichiers</strong> de code ont été fusionnés.</p>";
|
||||
echo "<p><em>Tu peux maintenant donner ce fichier à ta Gem HouseHub !</em></p>";
|
||||
echo "</div>";
|
||||
?>
|
||||
+53
@@ -1250,3 +1250,56 @@ p {
|
||||
[data-theme="dark"] .ts-thumb {
|
||||
transform: translateX(16px);
|
||||
}
|
||||
|
||||
/* === ACCORDÉONS NATIFS (DETAILS/SUMMARY) === */
|
||||
.pf-accordion {
|
||||
background: var(--bg-page);
|
||||
border: 1px solid var(--border-light);
|
||||
border-radius: 8px;
|
||||
margin-bottom: 12px;
|
||||
overflow: hidden;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
.pf-accordion-summary {
|
||||
padding: 14px 16px;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
list-style: none; /* Masque la flèche native Firefox/Chrome */
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
background: var(--bg-page);
|
||||
transition:
|
||||
background 0.2s,
|
||||
color 0.2s;
|
||||
}
|
||||
.pf-accordion-summary::-webkit-details-marker {
|
||||
display: none; /* Masque la flèche native Safari */
|
||||
}
|
||||
.pf-accordion-summary:hover {
|
||||
background: var(--bg-subtle);
|
||||
color: var(--text-main);
|
||||
}
|
||||
.pf-accordion-summary::after {
|
||||
content: "▼";
|
||||
font-size: 0.7rem;
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
details[open].pf-accordion > .pf-accordion-summary {
|
||||
border-bottom: 1px solid var(--border-light);
|
||||
color: var(--primary);
|
||||
}
|
||||
details[open].pf-accordion > .pf-accordion-summary::after {
|
||||
transform: rotate(-180deg);
|
||||
}
|
||||
.pf-accordion-content {
|
||||
padding: 16px;
|
||||
background: var(--bg-panel);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
@@ -164,6 +164,11 @@ return [
|
||||
'set_err_kid_name' => 'El nom és obligatori.',
|
||||
'set_confirm_del_kid' => 'Vols eliminar aquest nen? (El seu historial financer es conservarà als arxius).',
|
||||
'set_no_kids' => 'Cap nen configurat per a aquesta llar.',
|
||||
'set_family_config' => 'Configuració de la llar',
|
||||
'set_global_params' => 'Paràmetres globals',
|
||||
'set_care_modes' => 'Modalitats de cura habituals',
|
||||
'set_add_care_mode' => 'Afegir una modalitat',
|
||||
'btn_save' => 'Desar',
|
||||
|
||||
// ==========================================
|
||||
// FAMILY CALENDAR
|
||||
@@ -217,6 +222,9 @@ return [
|
||||
'leg_centre' => 'Casal',
|
||||
'leg_avis' => 'Avís',
|
||||
'leg_pep_sick' => 'Pep Malalt',
|
||||
'care_nounou' => 'Kangur',
|
||||
'care_centre' => 'Casal',
|
||||
'care_avis' => 'Avis',
|
||||
|
||||
'vac_toussaint' => 'Vacances de Tots Sants',
|
||||
'vac_noel' => 'Vacances de Nadal',
|
||||
|
||||
@@ -165,6 +165,11 @@ return [
|
||||
'set_err_kid_name' => 'The first name is required.',
|
||||
'set_confirm_del_kid' => 'Delete this kid? (Their financial history will remain visible in the archives).',
|
||||
'set_no_kids' => 'No kids configured for this household.',
|
||||
'set_family_config' => 'Family Structure',
|
||||
'set_global_params' => 'Global settings',
|
||||
'set_care_modes' => 'Common childcare arrangements',
|
||||
'set_add_care_mode' => 'Ajouter un modeAdd a mode',
|
||||
'btn_save' => 'Save',
|
||||
|
||||
// ==========================================
|
||||
// FAMILY CALENDAR
|
||||
@@ -218,6 +223,9 @@ return [
|
||||
'leg_centre' => 'Centre',
|
||||
'leg_avis' => 'Notice',
|
||||
'leg_pep_sick' => 'Pep sick',
|
||||
'care_nounou' => 'Nanny',
|
||||
'care_centre' => 'Daycare',
|
||||
'care_avis' => 'Grandparents',
|
||||
|
||||
'vac_toussaint' => 'All Saints\' holidays',
|
||||
'vac_noel' => 'Christmas holidays',
|
||||
|
||||
@@ -164,6 +164,11 @@ return [
|
||||
'set_err_kid_name' => 'Le prénom est requis.',
|
||||
'set_confirm_del_kid' => 'Supprimer cet enfant ? (Son historique financier restera visible dans les archives).',
|
||||
'set_no_kids' => 'Aucun enfant configuré pour ce foyer.',
|
||||
'set_family_config' => 'Configuration du foyer',
|
||||
'set_global_params' => 'Paramètres globaux',
|
||||
'set_care_modes' => 'Modes de garde usuels',
|
||||
'set_add_care_mode' => 'Ajouter un mode',
|
||||
'btn_save_config' => 'Enregistrer',
|
||||
|
||||
// ==========================================
|
||||
// FAMILY CALENDAR
|
||||
@@ -208,6 +213,9 @@ return [
|
||||
'fc_err_action' => 'Erreur lors de l\'action : ',
|
||||
'fc_today_short' => 'Auj.',
|
||||
'fc_today_title' => "Aujourd'hui",
|
||||
'care_nounou' => 'Nounou',
|
||||
'care_centre' => 'Centre de loisirs',
|
||||
'care_avis' => 'Avis',
|
||||
|
||||
'leg_presence' => 'Présence Pep',
|
||||
'leg_school_holidays' => 'Vacances Scolaires',
|
||||
|
||||
+430
-350
@@ -31,7 +31,6 @@ CREATE TABLE IF NOT EXISTS user_calendar_integrations (
|
||||
// ─── Actions ──────────────────────────────────────────────────────────────────
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
if (!verify_csrf($_POST['csrf_token'] ?? null)) {
|
||||
// Fallback JSON pour les requêtes AJAX qui échouent au CSRF
|
||||
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
|
||||
header('Content-Type: application/json');
|
||||
echo json_encode(['success' => false, 'error' => 'Session invalide (CSRF). Rechargez la page.']);
|
||||
@@ -39,256 +38,256 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
}
|
||||
$error = "Session invalide (CSRF). Rechargez la page.";
|
||||
} else {
|
||||
$action = $_POST['action'] ?? '';
|
||||
$action = $_POST['action'] ?? '';
|
||||
|
||||
// 🟢 GESTION AJAX : ENFANTS DU FOYER
|
||||
if ($action === 'add_child') {
|
||||
header('Content-Type: application/json');
|
||||
try {
|
||||
$name = trim($_POST['child_name'] ?? '');
|
||||
if (empty($name)) throw new Exception(tr('set_err_kid_name'));
|
||||
|
||||
require_once __DIR__ . '/includes/db.php';
|
||||
$stmt = $pdo->prepare("INSERT INTO pf_people (name, role) VALUES (?, 'enfant')");
|
||||
$stmt->execute([$name]);
|
||||
|
||||
echo json_encode(['success' => true]);
|
||||
} catch (Exception $e) {
|
||||
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
|
||||
}
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($action === 'delete_child') {
|
||||
header('Content-Type: application/json');
|
||||
try {
|
||||
$id = (int)($_POST['child_id'] ?? 0);
|
||||
if ($id > 0) {
|
||||
// 🟢 SAUVEGARDE GLOBALE : CONFIGURATION DU FOYER (Unifiée)
|
||||
if ($action === 'update_family_info') {
|
||||
header('Content-Type: application/json');
|
||||
try {
|
||||
require_once __DIR__ . '/includes/db.php';
|
||||
$stmt = $pdo->prepare("DELETE FROM pf_people WHERE id = ? AND role = 'enfant'");
|
||||
$stmt->execute([$id]);
|
||||
}
|
||||
echo json_encode(['success' => true]);
|
||||
} catch (Exception $e) {
|
||||
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
|
||||
}
|
||||
exit;
|
||||
}
|
||||
$pdo->beginTransaction();
|
||||
|
||||
if ($action === 'update_family_info') {
|
||||
require_once __DIR__ . '/includes/db.php';
|
||||
// 1. Sauvegarde des paramètres globaux
|
||||
$currency = trim($_POST['currency'] ?? '€');
|
||||
$zone = trim($_POST['zone_scolaire'] ?? 'C');
|
||||
$careModesJson = $_POST['custom_care_modes'] ?? '[]';
|
||||
|
||||
$foyer = $pdo->query("SELECT currency, zone_scolaire FROM pf_foyer_settings WHERE id = 1")->fetch();
|
||||
$currency = isset($_POST['currency']) ? trim($_POST['currency']) : ($foyer['currency'] ?? '€');
|
||||
$zone = isset($_POST['zone_scolaire']) ? trim($_POST['zone_scolaire']) : ($foyer['zone_scolaire'] ?? 'C');
|
||||
$stmtSave = $pdo->prepare("UPDATE pf_foyer_settings SET currency = ?, zone_scolaire = ? WHERE id = 1");
|
||||
$stmtSave->execute([$currency, $zone]);
|
||||
$success = "Paramètres du foyer mis à jour avec succès.";
|
||||
}
|
||||
$stmtSave = $pdo->prepare("UPDATE pf_foyer_settings SET currency = ?, zone_scolaire = ?, care_modes = ? WHERE id = 1");
|
||||
$stmtSave->execute([$currency, $zone, $careModesJson]);
|
||||
|
||||
if ($action === 'set_modules' && $family_id) {
|
||||
$all = ['calendar', 'budget', 'holidays', 'gifts', 'garage', 'memo', 'todo', 'liste', 'calendar_ios', 'printvault', 'planka'];
|
||||
$enabled = array_values(array_filter($all, fn($m) => isset($_POST['mod_' . $m])));
|
||||
if (empty($enabled)) {
|
||||
$error = "Vous devez garder au moins un module actif.";
|
||||
} else {
|
||||
$meta_pdo->prepare("UPDATE families SET enabled_modules = ? WHERE id = ?")
|
||||
->execute([json_encode($enabled), $family_id]);
|
||||
$_SESSION['enabled_modules'] = $enabled;
|
||||
$success = "Modules mis à jour.";
|
||||
}
|
||||
}
|
||||
// 2. Gestion des enfants
|
||||
$kids = $_POST['kids'] ?? [];
|
||||
$deleted = json_decode($_POST['deleted_kids'] ?? '[]', true);
|
||||
|
||||
if ($action === 'set_lang') {
|
||||
$lang = $_POST['lang'] ?? 'fr';
|
||||
if (in_array($lang, ['fr', 'ca', 'en'])) {
|
||||
$_SESSION['app_lang'] = $lang;
|
||||
$meta_pdo->prepare("UPDATE users SET lang = ? WHERE id = ?")
|
||||
->execute([$lang, $user_id]);
|
||||
$success = "Language updated.";
|
||||
}
|
||||
}
|
||||
|
||||
// 🟢 ENRICHISSEMENT : Prise en compte de la couleur du profil
|
||||
if ($action === 'update_profile') {
|
||||
$display_name = trim($_POST['display_name'] ?? '');
|
||||
$color = trim($_POST['color'] ?? '#0891b2');
|
||||
|
||||
if (!$display_name) {
|
||||
$error = "Le prénom ne peut pas être vide.";
|
||||
} else {
|
||||
// MÀJ dans la base Meta (users)
|
||||
$meta_pdo->prepare("UPDATE users SET display_name = ? WHERE id = ?")
|
||||
->execute([$display_name, $user_id]);
|
||||
|
||||
// MÀJ dans la base locale Foyer (pf_people) via le user_id mappé
|
||||
require_once __DIR__ . '/includes/db.php';
|
||||
if (isset($pdo)) {
|
||||
$stmtPeopleColor = $pdo->prepare("UPDATE pf_people SET color = ? WHERE user_id = ?");
|
||||
$stmtPeopleColor->execute([$color, $user_id]);
|
||||
}
|
||||
|
||||
$_SESSION['user']['display_name'] = $display_name;
|
||||
$success = "Profil mis à jour.";
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'change_password') {
|
||||
$current = $_POST['current_password'] ?? '';
|
||||
$new = $_POST['new_password'] ?? '';
|
||||
$confirm = $_POST['confirm_password'] ?? '';
|
||||
|
||||
$row = $meta_pdo->prepare("SELECT password_hash FROM users WHERE id = ?");
|
||||
$row->execute([$user_id]);
|
||||
$row = $row->fetch();
|
||||
|
||||
if (!password_verify($current, $row['password_hash'])) {
|
||||
$error = "Mot de passe actuel incorrect.";
|
||||
} elseif (strlen($new) < 6) {
|
||||
$error = "Le nouveau mot de passe doit faire au moins 6 caractères.";
|
||||
} elseif ($new !== $confirm) {
|
||||
$error = "Les mots de passe ne correspondent pas.";
|
||||
} else {
|
||||
$meta_pdo->prepare("UPDATE users SET password_hash = ? WHERE id = ?")
|
||||
->execute([password_hash($new, PASSWORD_BCRYPT), $user_id]);
|
||||
$success = "Mot de passe modifié avec succès.";
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'update_family_name' && $family_id) {
|
||||
$name = trim($_POST['family_name'] ?? '');
|
||||
if ($name) {
|
||||
$meta_pdo->prepare("UPDATE families SET name = ? WHERE id = ?")
|
||||
->execute([$name, $family_id]);
|
||||
$success = "Nom de l'espace mis à jour.";
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'regen_invite' && $family_id) {
|
||||
$new_code = bin2hex(random_bytes(8));
|
||||
$meta_pdo->prepare("UPDATE families SET invite_code = ? WHERE id = ?")
|
||||
->execute([$new_code, $family_id]);
|
||||
$success = "Nouveau code d'invitation généré.";
|
||||
}
|
||||
|
||||
if ($action === 'upload_home_bg' && $family_id) {
|
||||
$upload_dir = '/uploads/';
|
||||
if (!is_dir($upload_dir)) @mkdir($upload_dir, 0755, true);
|
||||
$file = $_FILES['home_bg'] ?? null;
|
||||
if ($file && $file['error'] === 0) {
|
||||
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
|
||||
if (!in_array($ext, ['jpg','jpeg','png','webp'])) {
|
||||
$error = "Format non supporté (jpg, png, webp).";
|
||||
} else {
|
||||
$dest = $upload_dir . 'home_bg_' . $family_id . '.' . $ext;
|
||||
foreach (glob($upload_dir . 'home_bg_' . $family_id . '.*') as $old) @unlink($old);
|
||||
if (move_uploaded_file($file['tmp_name'], $dest)) {
|
||||
$success = "Image d'accueil mise à jour.";
|
||||
} else {
|
||||
$error = "Erreur lors de l'upload.";
|
||||
if (!empty($deleted)) {
|
||||
$in = str_repeat('?,', count($deleted) - 1) . '?';
|
||||
$stmtDel = $pdo->prepare("DELETE FROM pf_people WHERE id IN ($in) AND role = 'enfant'");
|
||||
$stmtDel->execute($deleted);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'reset_home_bg' && $family_id) {
|
||||
foreach (glob('/uploads/home_bg_' . $family_id . '.*') as $old) @unlink($old);
|
||||
$success = "Image d'accueil réinitialisée.";
|
||||
}
|
||||
$stmtInsert = $pdo->prepare("INSERT INTO pf_people (name, role, care_modes) VALUES (?, 'enfant', ?)");
|
||||
$stmtUpdate = $pdo->prepare("UPDATE pf_people SET name = ?, care_modes = ? WHERE id = ? AND role = 'enfant'");
|
||||
|
||||
if ($action === 'grocery_history_max' && $family_id) {
|
||||
require_once __DIR__ . '/includes/db.php';
|
||||
if (!isset($pdo)) {
|
||||
$error = "Base famille indisponible.";
|
||||
} else {
|
||||
$n = (int) ($_POST['history_max'] ?? 20);
|
||||
$n = max(1, min(50, $n));
|
||||
try {
|
||||
$pdo->prepare(
|
||||
"INSERT INTO pf_notes (note_type, reference_id, content) VALUES ('grocery_settings','history_max',?) ON DUPLICATE KEY UPDATE content=VALUES(content)"
|
||||
)->execute([(string) $n]);
|
||||
$success = tr('groceries_settings_saved');
|
||||
} catch (\Throwable $e) {
|
||||
$error = tr('groceries_settings_error') . ' ' . $e->getMessage();
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($kids as $kidId => $kidData) {
|
||||
$name = trim($kidData['name'] ?? '');
|
||||
if (empty($name)) continue;
|
||||
|
||||
if ($action === 'calendar_ios_save') {
|
||||
$username = trim($_POST['icloud_username'] ?? '');
|
||||
$appPassword = hh_normalize_apple_app_password((string) ($_POST['icloud_app_password'] ?? ''));
|
||||
$calendarUrl = trim($_POST['icloud_calendar_url'] ?? '');
|
||||
$modes = $kidData['modes'] ?? [];
|
||||
$modesJson = json_encode(array_values($modes));
|
||||
|
||||
if (!$username || !$appPassword || !$calendarUrl) {
|
||||
$error = "Merci de renseigner identifiant iCloud, mot de passe d'app et URL CalDAV.";
|
||||
} else {
|
||||
try {
|
||||
$resolvedUrl = hh_icloud_resolve_calendar_url_if_needed($username, $appPassword, $calendarUrl);
|
||||
$encrypted = hh_encrypt_secret($appPassword);
|
||||
$meta_pdo->prepare("
|
||||
INSERT INTO user_calendar_integrations (user_id, provider, username, secret_encrypted, calendar_url, status, updated_at)
|
||||
VALUES (?, 'icloud_caldav', ?, ?, ?, 'connected', NOW())
|
||||
ON DUPLICATE KEY UPDATE username=VALUES(username), secret_encrypted=VALUES(secret_encrypted), calendar_url=VALUES(calendar_url), status='connected', updated_at=NOW()
|
||||
")->execute([$user_id, $username, $encrypted, $resolvedUrl]);
|
||||
$msg = "Connexion calendrier iOS enregistrée.";
|
||||
if (rtrim($resolvedUrl, '/') !== rtrim($calendarUrl, '/')) {
|
||||
$msg .= " URL du calendrier détectée automatiquement (tu avais mis la racine iCloud).";
|
||||
}
|
||||
$success = $msg;
|
||||
} catch (\Throwable $e) {
|
||||
$error = "Impossible d'enregistrer la connexion iOS: " . $e->getMessage();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'calendar_ios_test') {
|
||||
$row = $meta_pdo->prepare("SELECT id, username, secret_encrypted, calendar_url FROM user_calendar_integrations WHERE user_id = ? AND provider='icloud_caldav'");
|
||||
$row->execute([$user_id]);
|
||||
$integration = $row->fetch();
|
||||
if (!$integration) {
|
||||
$error = "Aucune connexion iOS configurée.";
|
||||
} else {
|
||||
try {
|
||||
$pwd = hh_normalize_apple_app_password(hh_decrypt_secret($integration['secret_encrypted']));
|
||||
$calendarUrl = trim($integration['calendar_url']);
|
||||
$resolvedUrl = hh_icloud_resolve_calendar_url_if_needed($integration['username'], $pwd, $calendarUrl);
|
||||
$code = hh_caldav_test_calendar_collection($integration['username'], $pwd, $resolvedUrl);
|
||||
if (in_array($code, [200, 207], true)) {
|
||||
if (rtrim($resolvedUrl, '/') !== rtrim($calendarUrl, '/')) {
|
||||
$meta_pdo->prepare("UPDATE user_calendar_integrations SET calendar_url = ? WHERE id = ?")
|
||||
->execute([$resolvedUrl, $integration['id']]);
|
||||
if (strpos($kidId, 'new_') === 0) {
|
||||
$stmtInsert->execute([$name, $modesJson]);
|
||||
} else {
|
||||
$stmtUpdate->execute([$name, $modesJson, (int)$kidId]);
|
||||
}
|
||||
$success = "Connexion iCloud CalDAV valide (HTTP $code).";
|
||||
} else {
|
||||
$error = "Test connexion échoué (HTTP $code). Vérifie identifiant Apple, mot de passe d’app (16 caractères) et que le compte iCloud a le Calendrier activé.";
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$error = "Test connexion impossible: " . $e->getMessage();
|
||||
|
||||
$pdo->commit();
|
||||
echo json_encode(['success' => true]);
|
||||
} catch (Exception $e) {
|
||||
$pdo->rollBack();
|
||||
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
|
||||
}
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($action === 'set_modules' && $family_id) {
|
||||
$all = ['calendar', 'budget', 'holidays', 'gifts', 'garage', 'memo', 'todo', 'liste', 'calendar_ios', 'printvault', 'planka'];
|
||||
$enabled = array_values(array_filter($all, fn($m) => isset($_POST['mod_' . $m])));
|
||||
if (empty($enabled)) {
|
||||
$error = "Vous devez garder au moins un module actif.";
|
||||
} else {
|
||||
$meta_pdo->prepare("UPDATE families SET enabled_modules = ? WHERE id = ?")
|
||||
->execute([json_encode($enabled), $family_id]);
|
||||
$_SESSION['enabled_modules'] = $enabled;
|
||||
$success = "Modules mis à jour.";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'calendar_ios_disconnect') {
|
||||
$meta_pdo->prepare("DELETE FROM user_calendar_integrations WHERE user_id = ? AND provider='icloud_caldav'")->execute([$user_id]);
|
||||
$success = "Connexion iOS supprimée.";
|
||||
}
|
||||
if ($action === 'set_lang') {
|
||||
$lang = $_POST['lang'] ?? 'fr';
|
||||
if (in_array($lang, ['fr', 'ca', 'en'])) {
|
||||
$_SESSION['app_lang'] = $lang;
|
||||
$meta_pdo->prepare("UPDATE users SET lang = ? WHERE id = ?")
|
||||
->execute([$lang, $user_id]);
|
||||
$success = "Language updated.";
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'update_profile') {
|
||||
$display_name = trim($_POST['display_name'] ?? '');
|
||||
$color = trim($_POST['color'] ?? '#0891b2');
|
||||
|
||||
if (!$display_name) {
|
||||
$error = "Le prénom ne peut pas être vide.";
|
||||
} else {
|
||||
$meta_pdo->prepare("UPDATE users SET display_name = ? WHERE id = ?")
|
||||
->execute([$display_name, $user_id]);
|
||||
|
||||
require_once __DIR__ . '/includes/db.php';
|
||||
if (isset($pdo)) {
|
||||
$stmtPeopleColor = $pdo->prepare("UPDATE pf_people SET color = ? WHERE user_id = ?");
|
||||
$stmtPeopleColor->execute([$color, $user_id]);
|
||||
}
|
||||
|
||||
$_SESSION['user']['display_name'] = $display_name;
|
||||
$success = "Profil mis à jour.";
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'change_password') {
|
||||
$current = $_POST['current_password'] ?? '';
|
||||
$new = $_POST['new_password'] ?? '';
|
||||
$confirm = $_POST['confirm_password'] ?? '';
|
||||
|
||||
$row = $meta_pdo->prepare("SELECT password_hash FROM users WHERE id = ?");
|
||||
$row->execute([$user_id]);
|
||||
$row = $row->fetch();
|
||||
|
||||
if (!password_verify($current, $row['password_hash'])) {
|
||||
$error = "Mot de passe actuel incorrect.";
|
||||
} elseif (strlen($new) < 6) {
|
||||
$error = "Le nouveau mot de passe doit faire au moins 6 caractères.";
|
||||
} elseif ($new !== $confirm) {
|
||||
$error = "Les mots de passe ne correspondent pas.";
|
||||
} else {
|
||||
$meta_pdo->prepare("UPDATE users SET password_hash = ? WHERE id = ?")
|
||||
->execute([password_hash($new, PASSWORD_BCRYPT), $user_id]);
|
||||
$success = "Mot de passe modifié avec succès.";
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'update_family_name' && $family_id) {
|
||||
$name = trim($_POST['family_name'] ?? '');
|
||||
if ($name) {
|
||||
$meta_pdo->prepare("UPDATE families SET name = ? WHERE id = ?")
|
||||
->execute([$name, $family_id]);
|
||||
$success = "Nom de l'espace mis à jour.";
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'regen_invite' && $family_id) {
|
||||
$new_code = bin2hex(random_bytes(8));
|
||||
$meta_pdo->prepare("UPDATE families SET invite_code = ? WHERE id = ?")
|
||||
->execute([$new_code, $family_id]);
|
||||
$success = "Nouveau code d'invitation généré.";
|
||||
}
|
||||
|
||||
if ($action === 'upload_home_bg' && $family_id) {
|
||||
$upload_dir = '/uploads/';
|
||||
if (!is_dir($upload_dir)) @mkdir($upload_dir, 0755, true);
|
||||
$file = $_FILES['home_bg'] ?? null;
|
||||
if ($file && $file['error'] === 0) {
|
||||
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
|
||||
if (!in_array($ext, ['jpg','jpeg','png','webp'])) {
|
||||
$error = "Format non supporté (jpg, png, webp).";
|
||||
} else {
|
||||
$dest = $upload_dir . 'home_bg_' . $family_id . '.' . $ext;
|
||||
foreach (glob($upload_dir . 'home_bg_' . $family_id . '.*') as $old) @unlink($old);
|
||||
if (move_uploaded_file($file['tmp_name'], $dest)) {
|
||||
$success = "Image d'accueil mise à jour.";
|
||||
} else {
|
||||
$error = "Erreur lors de l'upload.";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'reset_home_bg' && $family_id) {
|
||||
foreach (glob('/uploads/home_bg_' . $family_id . '.*') as $old) @unlink($old);
|
||||
$success = "Image d'accueil réinitialisée.";
|
||||
}
|
||||
|
||||
if ($action === 'grocery_history_max' && $family_id) {
|
||||
require_once __DIR__ . '/includes/db.php';
|
||||
if (!isset($pdo)) {
|
||||
$error = "Base famille indisponible.";
|
||||
} else {
|
||||
$n = (int) ($_POST['history_max'] ?? 20);
|
||||
$n = max(1, min(50, $n));
|
||||
try {
|
||||
$pdo->prepare(
|
||||
"INSERT INTO pf_notes (note_type, reference_id, content) VALUES ('grocery_settings','history_max',?) ON DUPLICATE KEY UPDATE content=VALUES(content)"
|
||||
)->execute([(string) $n]);
|
||||
$success = tr('groceries_settings_saved');
|
||||
} catch (\Throwable $e) {
|
||||
$error = tr('groceries_settings_error') . ' ' . $e->getMessage();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'calendar_ios_save') {
|
||||
$username = trim($_POST['icloud_username'] ?? '');
|
||||
$appPassword = hh_normalize_apple_app_password((string) ($_POST['icloud_app_password'] ?? ''));
|
||||
$calendarUrl = trim($_POST['icloud_calendar_url'] ?? '');
|
||||
|
||||
if (!$username || !$appPassword || !$calendarUrl) {
|
||||
$error = "Merci de renseigner identifiant iCloud, mot de passe d'app et URL CalDAV.";
|
||||
} else {
|
||||
try {
|
||||
$resolvedUrl = hh_icloud_resolve_calendar_url_if_needed($username, $appPassword, $calendarUrl);
|
||||
$encrypted = hh_encrypt_secret($appPassword);
|
||||
$meta_pdo->prepare("
|
||||
INSERT INTO user_calendar_integrations (user_id, provider, username, secret_encrypted, calendar_url, status, updated_at)
|
||||
VALUES (?, 'icloud_caldav', ?, ?, ?, 'connected', NOW())
|
||||
ON DUPLICATE KEY UPDATE username=VALUES(username), secret_encrypted=VALUES(secret_encrypted), calendar_url=VALUES(calendar_url), status='connected', updated_at=NOW()
|
||||
")->execute([$user_id, $username, $encrypted, $resolvedUrl]);
|
||||
$msg = "Connexion calendrier iOS enregistrée.";
|
||||
if (rtrim($resolvedUrl, '/') !== rtrim($calendarUrl, '/')) {
|
||||
$msg .= " URL du calendrier détectée automatiquement.";
|
||||
}
|
||||
$success = $msg;
|
||||
} catch (\Throwable $e) {
|
||||
$error = "Impossible d'enregistrer la connexion iOS: " . $e->getMessage();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'calendar_ios_test') {
|
||||
$row = $meta_pdo->prepare("SELECT id, username, secret_encrypted, calendar_url FROM user_calendar_integrations WHERE user_id = ? AND provider='icloud_caldav'");
|
||||
$row->execute([$user_id]);
|
||||
$integration = $row->fetch();
|
||||
if (!$integration) {
|
||||
$error = "Aucune connexion iOS configurée.";
|
||||
} else {
|
||||
try {
|
||||
$pwd = hh_normalize_apple_app_password(hh_decrypt_secret($integration['secret_encrypted']));
|
||||
$calendarUrl = trim($integration['calendar_url']);
|
||||
$resolvedUrl = hh_icloud_resolve_calendar_url_if_needed($integration['username'], $pwd, $calendarUrl);
|
||||
$code = hh_caldav_test_calendar_collection($integration['username'], $pwd, $resolvedUrl);
|
||||
if (in_array($code, [200, 207], true)) {
|
||||
if (rtrim($resolvedUrl, '/') !== rtrim($calendarUrl, '/')) {
|
||||
$meta_pdo->prepare("UPDATE user_calendar_integrations SET calendar_url = ? WHERE id = ?")
|
||||
->execute([$resolvedUrl, $integration['id']]);
|
||||
}
|
||||
$success = "Connexion iCloud CalDAV valide (HTTP $code).";
|
||||
} else {
|
||||
$error = "Test connexion échoué (HTTP $code). Vérifiez vos identifiants.";
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$error = "Test connexion impossible: " . $e->getMessage();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'calendar_ios_disconnect') {
|
||||
$meta_pdo->prepare("DELETE FROM user_calendar_integrations WHERE user_id = ? AND provider='icloud_caldav'")->execute([$user_id]);
|
||||
$success = "Connexion iOS supprimée.";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Chargement données ───────────────────────────────────────────────────────
|
||||
|
||||
// 1. On charge la base locale AVANT pour que son $user n'écrase pas le nôtre
|
||||
if ($family_id) {
|
||||
require_once __DIR__ . '/includes/db.php';
|
||||
}
|
||||
|
||||
// 2. Maintenant on peut charger ton profil en toute sécurité
|
||||
$stmtUser = $meta_pdo->prepare("SELECT * FROM users WHERE id = ?");
|
||||
$stmtUser->execute([$user_id]);
|
||||
$user = $stmtUser->fetch();
|
||||
|
||||
// 3. Récupération de la couleur actuelle depuis pf_people
|
||||
$user_color = '#0891b2'; // Fallback par défaut
|
||||
$user_color = '#0891b2';
|
||||
if ($family_id && isset($pdo)) {
|
||||
$stmtColorFetch = $pdo->prepare("SELECT color FROM pf_people WHERE user_id = ?");
|
||||
$stmtColorFetch->execute([$user_id]);
|
||||
@@ -298,10 +297,24 @@ if ($family_id && isset($pdo)) {
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Récupération de la liste des enfants du foyer
|
||||
// 🟢 Récupération Unifiée : Foyer, Modes de Garde, Enfants
|
||||
$kidsList = [];
|
||||
$familyCareModes = ['Nounou', 'Centre', 'Avis'];
|
||||
$currentCurrency = defined('CURRENCY') ? CURRENCY : '€';
|
||||
$currentZone = defined('ZONE_SCOLAIRE') ? ZONE_SCOLAIRE : 'C';
|
||||
|
||||
if ($family_id && isset($pdo)) {
|
||||
$stmtKids = $pdo->query("SELECT id, name FROM pf_people WHERE role = 'enfant' ORDER BY id ASC");
|
||||
$foyerSettings = $pdo->query("SELECT currency, zone_scolaire, care_modes FROM pf_foyer_settings WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
|
||||
if ($foyerSettings) {
|
||||
if (!empty($foyerSettings['currency'])) $currentCurrency = $foyerSettings['currency'];
|
||||
if (!empty($foyerSettings['zone_scolaire'])) $currentZone = $foyerSettings['zone_scolaire'];
|
||||
if (!empty($foyerSettings['care_modes'])) {
|
||||
$parsed = json_decode($foyerSettings['care_modes'], true);
|
||||
if (is_array($parsed)) $familyCareModes = $parsed;
|
||||
}
|
||||
}
|
||||
|
||||
$stmtKids = $pdo->query("SELECT id, name, care_modes FROM pf_people WHERE role = 'enfant' ORDER BY id ASC");
|
||||
$kidsList = $stmtKids->fetchAll(PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
||||
@@ -322,18 +335,13 @@ $calendarIntegration->execute([$user_id]);
|
||||
$calendarIntegration = $calendarIntegration->fetch();
|
||||
|
||||
$groceryHistoryMaxSetting = 20;
|
||||
if ($family_id) {
|
||||
require_once __DIR__ . '/includes/db.php';
|
||||
if (isset($pdo)) {
|
||||
try {
|
||||
$gv = $pdo->query("SELECT content FROM pf_notes WHERE note_type='grocery_settings' AND reference_id='history_max'")->fetchColumn();
|
||||
if ($gv !== false && $gv !== null && $gv !== '') {
|
||||
$groceryHistoryMaxSetting = max(1, min(50, (int) $gv));
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
// ignore
|
||||
if ($family_id && isset($pdo)) {
|
||||
try {
|
||||
$gv = $pdo->query("SELECT content FROM pf_notes WHERE note_type='grocery_settings' AND reference_id='history_max'")->fetchColumn();
|
||||
if ($gv !== false && $gv !== null && $gv !== '') {
|
||||
$groceryHistoryMaxSetting = max(1, min(50, (int) $gv));
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {}
|
||||
}
|
||||
|
||||
$pageTitle = "Paramètres — HouseHub";
|
||||
@@ -410,7 +418,7 @@ require __DIR__ . '/header.php';
|
||||
</label>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<button type="submit" class="pf-btn">Enregistrer</button>
|
||||
<button type="submit" class="pf-btn"><?= tr('btn_save') ?></button>
|
||||
</form>
|
||||
</section>
|
||||
<?php endif; ?>
|
||||
@@ -432,20 +440,12 @@ require __DIR__ . '/header.php';
|
||||
</div>
|
||||
<button type="submit" class="pf-btn"><?= htmlspecialchars(tr('btn_save')) ?></button>
|
||||
</form>
|
||||
<p class="pf-muted-note" style="margin-top:1rem">
|
||||
<a href="/liste.php" style="color:var(--primary);font-weight:600;"><?= htmlspecialchars(tr('mod_liste_name')) ?></a>
|
||||
</p>
|
||||
</section>
|
||||
<?php endif; ?>
|
||||
|
||||
<section class="pf-panel-card">
|
||||
<h2 class="pf-card-h2 pf-card-h2--tight">📱 Intégration Calendrier iOS (CalDAV)</h2>
|
||||
<p class="pf-muted-note">Configurez ici votre calendrier iCloud pour synchroniser les événements créés dans HouseHub.</p>
|
||||
<p class="pf-muted-note" style="margin-top:8px;">
|
||||
Pour voir et gérer les événements : ouvrez le module
|
||||
<a href="/calendar-ios.php" style="color:var(--primary);font-weight:600;">Calendrier iOS</a>
|
||||
(menu du haut ou burger « Calendrier iOS », ou carte sur l’accueil). Le module doit être coché dans « Modules actifs » ci-dessus.
|
||||
</p>
|
||||
<form method="post" class="pf-stack-md">
|
||||
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token()) ?>">
|
||||
<input type="hidden" name="action" value="calendar_ios_save">
|
||||
@@ -462,7 +462,7 @@ require __DIR__ . '/header.php';
|
||||
<input type="url" name="icloud_calendar_url" class="pf-input" value="<?= htmlspecialchars($calendarIntegration['calendar_url'] ?? '') ?>" placeholder="https://caldav.icloud.com/..." required>
|
||||
</div>
|
||||
<div class="pf-flex-gap-8">
|
||||
<button type="submit" class="pf-btn">Enregistrer</button>
|
||||
<button type="submit" class="pf-btn"><?= tr('btn_save') ?></button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -478,13 +478,6 @@ require __DIR__ . '/header.php';
|
||||
<button type="submit" class="pf-btn btn-secondary">Déconnecter</button>
|
||||
</form>
|
||||
</div>
|
||||
<p class="pf-muted-note" style="margin-top:10px;">
|
||||
Après enregistrement, utilisez « Tester la connexion » : un message vert confirme que l’URL CalDAV répond avec tes identifiants.
|
||||
Sur la page Calendrier iOS, le bouton « Synchroniser » envoie les événements vers iCloud et récupère ceux créés sur l’iPhone.
|
||||
</p>
|
||||
<?php if (!empty($calendarIntegration['last_sync_at'])): ?>
|
||||
<p class="pf-muted-note">Dernière synchro: <?= htmlspecialchars($calendarIntegration['last_sync_at']) ?></p>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
|
||||
<?php if ($family_id):
|
||||
@@ -526,74 +519,90 @@ require __DIR__ . '/header.php';
|
||||
|
||||
|
||||
<?php
|
||||
$enabledMods = $_SESSION['enabled_modules'] ?? [];
|
||||
|
||||
$showCurrency = count(array_intersect(['budget', 'holidays', 'gifts', 'garage'], $enabledMods)) > 0;
|
||||
$showZone = in_array('calendar', $enabledMods);
|
||||
$showCurrency = count(array_intersect(['budget', 'holidays', 'gifts', 'garage'], $_SESSION['enabled_modules'] ?? [])) > 0;
|
||||
$showZone = in_array('calendar', $_SESSION['enabled_modules'] ?? []);
|
||||
|
||||
if ($family_id):
|
||||
$currentCurrency = defined('CURRENCY') ? CURRENCY : '€';
|
||||
$currentZone = defined('ZONE_SCOLAIRE') ? ZONE_SCOLAIRE : 'C';
|
||||
?>
|
||||
<section class="pf-panel-card">
|
||||
<h2 class="pf-card-h2">👪 Configuration du foyer</h2>
|
||||
<h2 class="pf-card-h2" style="font-size: 1.25rem;">👪 <?= tr('set_family_config') ?></h2>
|
||||
<p class="pf-muted-note">Configurez les indicateurs et les membres partagés par votre foyer.</p>
|
||||
|
||||
<?php if ($showCurrency || $showZone): ?>
|
||||
<form method="post" class="pf-stack-md" style="margin-bottom: 24px;">
|
||||
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token()) ?>">
|
||||
<form id="unifiedFamilyForm" style="margin-top: 20px; display: flex; flex-direction: column;">
|
||||
<input type="hidden" name="action" value="update_family_info">
|
||||
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token()) ?>">
|
||||
<input type="hidden" name="custom_care_modes" id="customCareModes" value="<?= htmlspecialchars(json_encode($familyCareModes)) ?>">
|
||||
<input type="hidden" name="deleted_kids" id="deletedKids" value="[]">
|
||||
|
||||
<div class="form-row">
|
||||
<!-- ACCORDÉON 1 : PARAMÈTRES GLOBAUX -->
|
||||
<?php if ($showCurrency || $showZone): ?>
|
||||
<details class="pf-accordion">
|
||||
<summary class="pf-accordion-summary">🌍 <?= tr('set_global_params') ?></summary>
|
||||
<div class="pf-accordion-content">
|
||||
<div class="form-row" style="margin-bottom: 0;">
|
||||
<?php if ($showCurrency): ?>
|
||||
<div class="pf-form-group" style="margin-bottom: 0;">
|
||||
<label class="pf-label">Devise monétaire</label>
|
||||
<input type="text" name="currency" class="pf-input" value="<?= htmlspecialchars($currentCurrency) ?>" placeholder="ex: €, $, CHF" required maxlength="10">
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($showCurrency): ?>
|
||||
<div class="pf-form-group">
|
||||
<label class="pf-label">Devise monétaire</label>
|
||||
<input type="text" name="currency" class="pf-input" value="<?= htmlspecialchars($currentCurrency) ?>" placeholder="ex: €, $, CHF" required maxlength="10">
|
||||
<?php if ($showZone): ?>
|
||||
<div class="pf-form-group" style="margin-bottom: 0;">
|
||||
<label class="pf-label">Zone de vacances scolaires (France)</label>
|
||||
<select name="zone_scolaire" class="pf-input" style="background:var(--bg-panel);">
|
||||
<option value="A" <?= $currentZone === 'A' ? 'selected' : '' ?>>Zone A</option>
|
||||
<option value="B" <?= $currentZone === 'B' ? 'selected' : '' ?>>Zone B</option>
|
||||
<option value="C" <?= $currentZone === 'C' ? 'selected' : '' ?>>Zone C</option>
|
||||
<option value="Autre" <?= $currentZone === 'Autre' ? 'selected' : '' ?>>Hors France / Autre</option>
|
||||
</select>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</details>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($showZone): ?>
|
||||
<div class="pf-form-group">
|
||||
<label class="pf-label">Zone de vacances scolaires (France)</label>
|
||||
<select name="zone_scolaire" class="pf-input" style="background:var(--bg-panel);">
|
||||
<option value="A" <?= $currentZone === 'A' ? 'selected' : '' ?>>Zone A</option>
|
||||
<option value="B" <?= $currentZone === 'B' ? 'selected' : '' ?>>Zone B</option>
|
||||
<option value="C" <?= $currentZone === 'C' ? 'selected' : '' ?>>Zone C</option>
|
||||
<option value="Autre" <?= $currentZone === 'Autre' ? 'selected' : '' ?>>Hors France / Autre</option>
|
||||
</select>
|
||||
<!-- ACCORDÉON 2 : MODES DE GARDE -->
|
||||
<details class="pf-accordion">
|
||||
<summary class="pf-accordion-summary">🏷️ <?= tr('set_care_modes') ?></summary>
|
||||
<div class="pf-accordion-content">
|
||||
<div id="careModesContainer" style="display: flex; gap: 8px; flex-wrap: wrap;"></div>
|
||||
<!-- Largeur contrainte avec max-content -->
|
||||
<button type="button" class="pf-btn btn-secondary pf-btn-sm-text" onclick="promptNewCareMode()" style="padding: 4px 10px; font-size: 0.8rem; width: max-content;">+ <?= tr('set_add_care_mode') ?></button>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</details>
|
||||
|
||||
</div>
|
||||
<!-- ACCORDÉON 3 : ENFANTS (Ouvert par défaut) -->
|
||||
<details class="pf-accordion">
|
||||
<summary class="pf-accordion-summary">👶 <?= tr('set_kids_title') ?></summary>
|
||||
<div class="pf-accordion-content" style="gap: 10px;">
|
||||
<ul id="kidsListContainer" style="list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px;">
|
||||
<?php foreach ($kidsList as $kid):
|
||||
$kidModes = json_decode($kid['care_modes'] ?? '[]', true);
|
||||
if (!is_array($kidModes)) $kidModes = [];
|
||||
?>
|
||||
<!-- Version compactée -->
|
||||
<li class="kid-row" data-id="<?= $kid['id'] ?>" style="padding: 10px 12px; background: var(--bg-page); border: 1px solid var(--border-light); border-radius: 8px; display: flex; flex-direction: column; gap: 8px;">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; gap: 10px;">
|
||||
<input type="text" name="kids[<?= $kid['id'] ?>][name]" class="pf-input" value="<?= htmlspecialchars($kid['name']) ?>" style="flex: 1; padding: 8px; font-weight: bold;" required>
|
||||
<button type="button" class="btn-icon-action delete" onclick="removeKidRow(this, <?= $kid['id'] ?>)" title="<?= tr('delete') ?>" style="padding: 4px;">🗑️</button>
|
||||
</div>
|
||||
<div class="kid-modes-container" style="font-size: 0.85rem; color: var(--text-muted); display: flex; gap: 12px; flex-wrap: wrap; align-items: center;">
|
||||
<span class="stored-modes" style="display:none;"><?= htmlspecialchars(json_encode($kidModes)) ?></span>
|
||||
</div>
|
||||
</li>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
<!-- Largeur contrainte avec max-content -->
|
||||
<button type="button" class="pf-btn btn-secondary pf-btn-sm-text" onclick="addKidRow()" style="padding: 4px 10px; font-size: 0.8rem; width: max-content;">+ <?= tr('set_btn_add_kid') ?></button>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<button type="submit" class="pf-btn">Enregistrer les paramètres</button>
|
||||
<button type="submit" class="pf-btn"><?= tr('btn_save') ?></button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
|
||||
<div style="border-top: 1px solid var(--border-light); margin: 24px 0;"></div>
|
||||
|
||||
<h3 style="margin-top: 0; font-size: 1.1rem; color: var(--text-main); margin-bottom: 8px;">👶 <?= tr('set_kids_title') ?></h3>
|
||||
<p class="pf-muted-note"><?= tr('set_kids_desc') ?></p>
|
||||
|
||||
<ul class="pf-stack-sm" style="list-style: none; padding: 0; margin-bottom: 20px; margin-top: 15px;">
|
||||
<?php if (empty($kidsList)): ?>
|
||||
<li class="pf-muted-note" style="font-style: italic;"><?= tr('set_no_kids') ?></li>
|
||||
<?php else: ?>
|
||||
<?php foreach ($kidsList as $kid): ?>
|
||||
<li style="display: flex; justify-content: space-between; align-items: center; padding: 10px 14px; background: var(--bg-page); border: 1px solid var(--border-light); border-radius: 8px;">
|
||||
<strong><?= htmlspecialchars($kid['name']) ?></strong>
|
||||
<button type="button" class="btn-icon-action delete" onclick="deleteChild(<?= $kid['id'] ?>)" title="<?= tr('delete') ?>">🗑️</button>
|
||||
</li>
|
||||
<?php endforeach; ?>
|
||||
<?php endif; ?>
|
||||
</ul>
|
||||
|
||||
<form id="formAddChild" style="display: flex; gap: 10px;">
|
||||
<input type="text" id="newChildName" class="pf-input" placeholder="<?= tr('set_add_kid_placeholder') ?>" required autocomplete="off">
|
||||
<button type="submit" class="pf-btn pf-shrink-0">➕ <?= tr('set_btn_add_kid') ?></button>
|
||||
</form>
|
||||
|
||||
</section>
|
||||
<?php endif; ?>
|
||||
|
||||
@@ -620,7 +629,7 @@ require __DIR__ . '/header.php';
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="pf-btn">Enregistrer</button>
|
||||
<button type="submit" class="pf-btn"><?= tr('btn_save') ?></button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
@@ -729,70 +738,141 @@ function copyCode() {
|
||||
});
|
||||
}
|
||||
|
||||
// Injection des traductions dynamiques pour JS
|
||||
window.I18N = {
|
||||
...(window.I18N || {}),
|
||||
'set_confirm_del_kid': "<?= tr('set_confirm_del_kid') ?>",
|
||||
'delete': "<?= tr('delete') ?>",
|
||||
'error_occured': "<?= tr('error_occured') ?>"
|
||||
};
|
||||
// 🟢 LOGIQUE FRONT-END UNIFIÉE (Vanilla JS) : Configuration Foyer
|
||||
let globalCareModes = <?= json_encode($familyCareModes) ?>;
|
||||
let deletedKidsIds = [];
|
||||
let newKidCounter = 0;
|
||||
|
||||
// Gestion de l'ajout d'enfant
|
||||
const formAddChild = document.getElementById('formAddChild');
|
||||
if (formAddChild) {
|
||||
formAddChild.addEventListener('submit', async (e) => {
|
||||
function renderCareModes() {
|
||||
const container = document.getElementById('careModesContainer');
|
||||
if (!container) return;
|
||||
|
||||
document.getElementById('customCareModes').value = JSON.stringify(globalCareModes);
|
||||
container.innerHTML = '';
|
||||
|
||||
globalCareModes.forEach((mode, index) => {
|
||||
const badge = document.createElement('div');
|
||||
badge.style.cssText = "background: var(--bg-soft); color: var(--primary); padding: 4px 10px; border-radius: 12px; font-size: 0.85rem; font-weight: 600; display: flex; align-items: center; gap: 6px; border: 1px solid rgba(59, 130, 246, 0.2);";
|
||||
badge.innerHTML = `
|
||||
${mode}
|
||||
<span style="cursor: pointer; opacity: 0.6; padding: 2px;" onclick="removeCareMode(${index})">×</span>
|
||||
`;
|
||||
container.appendChild(badge);
|
||||
});
|
||||
|
||||
document.querySelectorAll('.kid-row').forEach(row => renderKidCheckboxes(row));
|
||||
}
|
||||
|
||||
function promptNewCareMode() {
|
||||
const newMode = prompt("Entrez le nom du nouveau mode de garde (ex: Papi/Mamie, Centre aéré...)");
|
||||
if (newMode && newMode.trim() !== '') {
|
||||
if (!globalCareModes.includes(newMode.trim())) {
|
||||
globalCareModes.push(newMode.trim());
|
||||
renderCareModes();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function removeCareMode(index) {
|
||||
if (confirm("Supprimer ce mode de garde pour tous les enfants ?")) {
|
||||
globalCareModes.splice(index, 1);
|
||||
renderCareModes();
|
||||
}
|
||||
}
|
||||
|
||||
function renderKidCheckboxes(row) {
|
||||
const container = row.querySelector('.kid-modes-container');
|
||||
const storedSpan = row.querySelector('.stored-modes');
|
||||
let activeModes = [];
|
||||
|
||||
if (storedSpan) {
|
||||
try { activeModes = JSON.parse(storedSpan.innerText); } catch(e){}
|
||||
storedSpan.remove();
|
||||
} else {
|
||||
const checked = Array.from(container.querySelectorAll('input:checked')).map(i => i.value);
|
||||
if (checked.length > 0) activeModes = checked;
|
||||
}
|
||||
|
||||
const kidId = row.getAttribute('data-id');
|
||||
container.innerHTML = '';
|
||||
|
||||
if (globalCareModes.length === 0) {
|
||||
container.innerHTML = '<span style="font-style: italic;">Aucun mode de garde configuré.</span>';
|
||||
return;
|
||||
}
|
||||
|
||||
globalCareModes.forEach(mode => {
|
||||
const isChecked = activeModes.includes(mode) ? 'checked' : '';
|
||||
const label = document.createElement('label');
|
||||
label.style.cssText = "cursor: pointer; display: flex; align-items: center; gap: 5px;";
|
||||
label.innerHTML = `<input type="checkbox" name="kids[${kidId}][modes][]" value="${mode}" class="pf-checkbox-lg" style="transform: scale(0.8);" ${isChecked}> ${mode}`;
|
||||
container.appendChild(label);
|
||||
});
|
||||
}
|
||||
|
||||
function addKidRow() {
|
||||
newKidCounter++;
|
||||
const kidId = 'new_' + newKidCounter;
|
||||
const ul = document.getElementById('kidsListContainer');
|
||||
|
||||
const li = document.createElement('li');
|
||||
li.className = 'kid-row';
|
||||
li.setAttribute('data-id', kidId);
|
||||
li.style.cssText = "padding: 10px 12px; background: var(--bg-page); border: 1px solid var(--border-light); border-radius: 8px; display: flex; flex-direction: column; gap: 8px;";
|
||||
|
||||
li.innerHTML = `
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; gap: 10px;">
|
||||
<input type="text" name="kids[${kidId}][name]" class="pf-input" placeholder="Prénom" style="flex: 1; padding: 8px; font-weight: bold;" required>
|
||||
<button type="button" class="btn-icon-action delete" onclick="removeKidRow(this)" title="Retirer" style="padding: 4px;">🗑️</button>
|
||||
</div>
|
||||
<div class="kid-modes-container" style="font-size: 0.85rem; color: var(--text-muted); display: flex; gap: 12px; flex-wrap: wrap; align-items: center;"></div>
|
||||
`;
|
||||
ul.appendChild(li);
|
||||
renderKidCheckboxes(li);
|
||||
}
|
||||
|
||||
function removeKidRow(btn, dbId = null) {
|
||||
const row = btn.closest('.kid-row');
|
||||
if (dbId) {
|
||||
deletedKidsIds.push(dbId);
|
||||
document.getElementById('deletedKids').value = JSON.stringify(deletedKidsIds);
|
||||
}
|
||||
row.remove();
|
||||
}
|
||||
|
||||
const unifiedFamilyForm = document.getElementById('unifiedFamilyForm');
|
||||
if (unifiedFamilyForm) {
|
||||
unifiedFamilyForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const input = document.getElementById('newChildName');
|
||||
const name = input.value.trim();
|
||||
if (!name) return;
|
||||
const form = e.target;
|
||||
const btn = form.querySelector('button[type="submit"]');
|
||||
const oldHtml = btn.innerHTML;
|
||||
|
||||
const btn = e.target.querySelector('button[type="submit"]');
|
||||
const originalText = btn.innerHTML;
|
||||
btn.innerHTML = '...';
|
||||
btn.innerHTML = '⏳ Enregistrement...';
|
||||
btn.disabled = true;
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('action', 'add_child');
|
||||
fd.append('child_name', name);
|
||||
fd.append('csrf_token', window.CSRF_TOKEN); // Important: CSRF
|
||||
const fd = new FormData(form);
|
||||
|
||||
try {
|
||||
const res = await pachaFetch('settings.php', { method: 'POST', body: fd });
|
||||
if (res.success) {
|
||||
window.location.reload();
|
||||
showToast("Configuration du foyer enregistrée avec succès.", "success");
|
||||
setTimeout(() => window.location.reload(), 1000);
|
||||
} else {
|
||||
showToast(res.error || window.I18N['error_occured'], 'error');
|
||||
showToast(res.error || "Erreur de sauvegarde.", "error");
|
||||
}
|
||||
} catch (err) {
|
||||
showToast(window.I18N['error_occured'], 'error');
|
||||
showToast("Erreur technique de sauvegarde.", "error");
|
||||
} finally {
|
||||
btn.innerHTML = originalText;
|
||||
btn.innerHTML = oldHtml;
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Gestion de la suppression d'enfant
|
||||
async function deleteChild(id) {
|
||||
const confirmed = await pachaConfirm(window.I18N['delete'], window.I18N['set_confirm_del_kid']);
|
||||
if (!confirmed) return;
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('action', 'delete_child');
|
||||
fd.append('child_id', id);
|
||||
fd.append('csrf_token', window.CSRF_TOKEN); // Important: CSRF
|
||||
|
||||
try {
|
||||
const res = await pachaFetch('settings.php', { method: 'POST', body: fd });
|
||||
if (res.success) {
|
||||
window.location.reload();
|
||||
} else {
|
||||
showToast(res.error || window.I18N['error_occured'], 'error');
|
||||
}
|
||||
} catch (err) {
|
||||
showToast(window.I18N['error_occured'], 'error');
|
||||
}
|
||||
}
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (document.getElementById('careModesContainer')) renderCareModes();
|
||||
});
|
||||
</script>
|
||||
|
||||
<?php require __DIR__ . '/footer.php'; ?>
|
||||
Reference in New Issue
Block a user