Files
Menage/api/admin.php
T
2026-11-11 09:35:51 +01:00

188 lines
11 KiB
PHP

<?php
require_once __DIR__ . '/config.php';
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
$acc = require_admin(true);
$action = $_GET['action'] ?? '';
$body = json_decode(file_get_contents('php://input'), true) ?? [];
try {
$db = getDB();
switch ($action) {
// ── GET ALL ──────────────────────────────────────────
case 'get_all':
$accounts = $db->query("
SELECT a.id, a.username, a.role, a.display_name, a.color, a.avatar,
a.email, a.profile_id, a.last_login,
p.name as profile_name
FROM accounts a
LEFT JOIN profiles p ON p.id = a.profile_id
ORDER BY a.id
")->fetchAll();
$profiles = $db->query("SELECT * FROM profiles ORDER BY name")->fetchAll();
$categories = $db->query("SELECT * FROM categories ORDER BY sort_order")->fetchAll();
$tasks = $db->query("
SELECT t.*, c.name as category_name, c.icon as category_icon
FROM tasks t JOIN categories c ON c.id = t.category_id
ORDER BY c.sort_order, t.sort_order
")->fetchAll();
$pca = $db->query("SELECT * FROM profile_category_assignments")->fetchAll();
$pta = $db->query("SELECT * FROM profile_task_assignments")->fetchAll();
json_response(compact('accounts','profiles','categories','tasks','pca','pta'));
// ── PROFILES ─────────────────────────────────────────
case 'save_profile':
$id = (int)($body['id'] ?? 0);
$name = trim($body['name'] ?? '');
$desc = trim($body['description'] ?? '');
if (!$name) json_response(['error' => 'Nom requis'], 400);
if ($id) {
$db->prepare("UPDATE profiles SET name=:n, description=:d WHERE id=:id")
->execute([':n'=>$name, ':d'=>$desc, ':id'=>$id]);
} else {
$db->prepare("INSERT INTO profiles (name, description) VALUES (:n, :d)")
->execute([':n'=>$name, ':d'=>$desc]);
$id = (int)$db->lastInsertId();
}
json_response(['success' => true, 'id' => $id]);
case 'delete_profile':
$id = (int)($body['id'] ?? 0);
if (!$id) json_response(['error' => 'ID requis'], 400);
// Vérifier qu'aucun compte ne l'utilise
$used = $db->prepare("SELECT COUNT(*) FROM accounts WHERE profile_id=:id");
$used->execute([':id' => $id]);
if ((int)$used->fetchColumn() > 0)
json_response(['error' => 'Ce profil est encore utilisé par un ou plusieurs comptes.'], 409);
$db->prepare("DELETE FROM profiles WHERE id=:id")->execute([':id' => $id]);
json_response(['success' => true]);
// Sauvegarder les assignations d'un profil (pièces + tâches)
case 'save_profile_assignments':
$pid = (int)($body['profile_id'] ?? 0);
$cat_ids = array_map('intval', $body['category_ids'] ?? []);
$task_ids = array_map('intval', $body['task_ids'] ?? []);
if (!$pid) json_response(['error' => 'profile_id requis'], 400);
$db->beginTransaction();
$db->prepare("DELETE FROM profile_category_assignments WHERE profile_id=:p")->execute([':p'=>$pid]);
$db->prepare("DELETE FROM profile_task_assignments WHERE profile_id=:p")->execute([':p'=>$pid]);
if ($cat_ids) {
$ins = $db->prepare("INSERT IGNORE INTO profile_category_assignments(profile_id,category_id) VALUES(:p,:c)");
foreach ($cat_ids as $cid) $ins->execute([':p'=>$pid, ':c'=>$cid]);
}
if ($task_ids) {
$ins = $db->prepare("INSERT IGNORE INTO profile_task_assignments(profile_id,task_id) VALUES(:p,:t)");
foreach ($task_ids as $tid) $ins->execute([':p'=>$pid, ':t'=>$tid]);
}
$db->commit();
json_response(['success' => true]);
// ── ACCOUNTS ─────────────────────────────────────────
case 'save_account':
$id = (int)($body['id'] ?? 0);
$username = trim($body['username'] ?? '');
$role = in_array($body['role']??'', ['admin','user']) ? $body['role'] : 'user';
$display_name = trim($body['display_name'] ?? '');
$color = preg_match('/^#[0-9a-fA-F]{6}$/', $body['color']??'') ? $body['color'] : '#6366f1';
$avatar = strtoupper(mb_substr(trim($body['avatar'] ?? mb_substr($display_name,0,1)), 0, 2));
$email = filter_var($body['email']??'', FILTER_VALIDATE_EMAIL) ?: '';
$profile_id = ($body['profile_id']??'') !== '' ? (int)$body['profile_id'] : null;
$password = $body['password'] ?? '';
if (!$username) json_response(['error' => 'Identifiant requis'], 400);
if (!$display_name) json_response(['error' => 'Prénom requis'], 400);
if ($id) {
if ($password !== '') {
if (strlen($password) < 8) json_response(['error' => 'Mot de passe trop court (8 car. min)'], 400);
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost'=>12]);
$db->prepare("UPDATE accounts SET username=:u,role=:r,display_name=:dn,color=:c,avatar=:a,email=:e,profile_id=:p,password=:pw WHERE id=:id")
->execute([':u'=>$username,':r'=>$role,':dn'=>$display_name,':c'=>$color,':a'=>$avatar,':e'=>$email,':p'=>$profile_id,':pw'=>$hash,':id'=>$id]);
} else {
$db->prepare("UPDATE accounts SET username=:u,role=:r,display_name=:dn,color=:c,avatar=:a,email=:e,profile_id=:p WHERE id=:id")
->execute([':u'=>$username,':r'=>$role,':dn'=>$display_name,':c'=>$color,':a'=>$avatar,':e'=>$email,':p'=>$profile_id,':id'=>$id]);
}
} else {
if (strlen($password) < 8) json_response(['error' => 'Mot de passe requis (8 car. min)'], 400);
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost'=>12]);
$db->prepare("INSERT INTO accounts (username,password,role,display_name,color,avatar,email,profile_id) VALUES(:u,:pw,:r,:dn,:c,:a,:e,:p)")
->execute([':u'=>$username,':pw'=>$hash,':r'=>$role,':dn'=>$display_name,':c'=>$color,':a'=>$avatar,':e'=>$email,':p'=>$profile_id]);
$id = (int)$db->lastInsertId();
}
json_response(['success' => true, 'id' => $id]);
case 'delete_account':
$id = (int)($body['id'] ?? 0);
if (!$id) json_response(['error' => 'ID requis'], 400);
if ($id === (int)$acc['id']) json_response(['error' => 'Impossible de supprimer son propre compte'], 400);
$db->prepare("DELETE FROM accounts WHERE id=:id")->execute([':id' => $id]);
json_response(['success' => true]);
// ── CATEGORIES ───────────────────────────────────────
case 'save_category':
$id = (int)($body['id'] ?? 0);
$name = trim($body['name'] ?? '');
$icon = trim($body['icon'] ?? '🏠');
$sort = (int)($body['sort_order'] ?? 99);
if (!$name) json_response(['error' => 'Nom requis'], 400);
if ($id) {
$db->prepare("UPDATE categories SET name=:n,icon=:i,sort_order=:s WHERE id=:id")
->execute([':n'=>$name,':i'=>$icon,':s'=>$sort,':id'=>$id]);
} else {
$db->prepare("INSERT INTO categories(name,icon,sort_order) VALUES(:n,:i,:s)")
->execute([':n'=>$name,':i'=>$icon,':s'=>$sort]);
$id = (int)$db->lastInsertId();
}
json_response(['success' => true, 'id' => $id]);
case 'delete_category':
$id = (int)($body['id'] ?? 0);
if (!$id) json_response(['error' => 'ID requis'], 400);
$db->prepare("DELETE FROM categories WHERE id=:id")->execute([':id' => $id]);
json_response(['success' => true]);
// ── TASKS ────────────────────────────────────────────
case 'save_task':
$id = (int)($body['id'] ?? 0);
$cat = (int)($body['category_id'] ?? 0);
$label = trim($body['label'] ?? '');
$freq = $body['frequency'] ?? 'hebdomadaire';
$sort = (int)($body['sort_order'] ?? 99);
$valid = ['quotidien','hebdomadaire','mensuel','trimestriel','saisonnier','biannuel','annuel'];
// Valider et nettoyer les saisons
$valid_saisons = ['printemps','ete','automne','hiver'];
$saisons_raw = $body['saisons'] ?? null;
$saisons = null;
if ($freq === 'saisonnier' && $saisons_raw) {
$parts = array_filter(explode(',', $saisons_raw), fn($s) => in_array(trim($s), $valid_saisons));
$saisons = !empty($parts) ? implode(',', $parts) : null;
}
if (!$label || !$cat) json_response(['error' => 'Champs requis'], 400);
if (!in_array($freq, $valid)) json_response(['error' => 'Fréquence invalide'], 400);
if ($freq === 'saisonnier' && !$saisons) json_response(['error' => 'Cochez au moins une saison'], 400);
if ($id) {
$db->prepare("UPDATE tasks SET category_id=:c,label=:l,frequency=:f,saisons=:s,sort_order=:so WHERE id=:id")
->execute([':c'=>$cat,':l'=>$label,':f'=>$freq,':s'=>$saisons,':so'=>$sort,':id'=>$id]);
} else {
$db->prepare("INSERT INTO tasks(category_id,label,frequency,saisons,sort_order) VALUES(:c,:l,:f,:s,:so)")
->execute([':c'=>$cat,':l'=>$label,':f'=>$freq,':s'=>$saisons,':so'=>$sort]);
$id = (int)$db->lastInsertId();
}
json_response(['success' => true, 'id' => $id]);
case 'delete_task':
$id = (int)($body['id'] ?? 0);
if (!$id) json_response(['error' => 'ID requis'], 400);
$db->prepare("DELETE FROM tasks WHERE id=:id")->execute([':id' => $id]);
json_response(['success' => true]);
default:
json_response(['error' => 'Action inconnue'], 404);
}
} catch (PDOException $e) {
json_response(['error' => 'DB: ' . $e->getMessage()], 500);
}