<?php
/**
 * Save handler for apropos contacts.
 * Structure: groups[] with role, each having entries[] of {text, url, email}.
 */
require_once __DIR__ . "/../../../bootstrap.php";
require_once __DIR__ . '/../../../src/AdminAuth.php';
AdminAuth::requireLogin();

// CSRF check
if (!isset($_POST['csrf_token']) || !isset($_SESSION['csrf_token']) ||
    !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    die("Erreur de sécurité : token invalide.");
}

$allowedKeys = ['contacts'];
$aproposKey  = $_POST['apropos_key'] ?? '';
if (!in_array($aproposKey, $allowedKeys)) {
    die("Clé invalide.");
}

require_once __DIR__ . '/../../../src/Database.php';
require_once __DIR__ . '/../../../src/AdminLogger.php';
require_once __DIR__ . '/../../../src/ErrorHandler.php';

try {
    $db = new Database();
    $groups = $_POST['groups'] ?? [];
    $cleaned = [];

    foreach ($groups as $group) {
        $role = trim($group['role'] ?? '');
        if ($role === '') continue;
        $entries = [];
        foreach ($group['entries'] ?? [] as $entry) {
            $text = trim($entry['text'] ?? '');
            if ($text === '') continue;
            $e = [
                'text'  => $text,
                'email' => trim($entry['email'] ?? ''),
            ];
            $url = trim($entry['url'] ?? '');
            if ($url !== '') $e['url'] = $url;
            $entries[] = $e;
        }
        if (empty($entries)) continue;
        $cleaned[] = ['role' => $role, 'entries' => $entries];
    }

    if (empty($cleaned)) {
        die("Au moins un groupe avec des entrées est requis.");
    }

    $db->saveAproposContent($aproposKey, $cleaned);
    AdminLogger::make()->logAproposEdit($aproposKey);
    App::flash('success', "Contenu « $aproposKey » mis à jour avec succès.");
} catch (Exception $e) {
    ErrorHandler::log('apropos', $e);
    die('Erreur lors de la sauvegarde : ' . htmlspecialchars(ErrorHandler::userMessage($e)));
}

header('Location: /admin/contenus.php');
exit;
