<?php
require_once __DIR__ . '/../../../bootstrap.php';
require_once __DIR__ . '/../../../src/AdminAuth.php';
AdminAuth::requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST'
    || !isset($_POST['csrf_token'], $_SESSION['csrf_token'])
    || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    http_response_code(403);
    die("Accès refusé.");
}

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

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

    switch ($action) {
        case 'rename':
            $id      = filter_var($_POST['tag_id'] ?? '', FILTER_VALIDATE_INT);
            $newName = trim($_POST['new_name'] ?? '');
            if (!$id || $newName === '') throw new Exception("Paramètres invalides.");
            $db->renameTag($id, $newName);
            break;

        case 'merge':
            $sourceId = filter_var($_POST['source_id'] ?? '', FILTER_VALIDATE_INT);
            $targetId = filter_var($_POST['target_id'] ?? '', FILTER_VALIDATE_INT);
            if (!$sourceId || !$targetId) throw new Exception("Paramètres invalides.");
            $db->mergeTag($sourceId, $targetId);
            break;

        case 'delete':
            $id = filter_var($_POST['tag_id'] ?? '', FILTER_VALIDATE_INT);
            if (!$id) throw new Exception("ID invalide.");
            $db->deleteTag($id);
            break;

        default:
            throw new Exception("Action inconnue.");
    }

    App::flash('success', "Opération effectuée.");
} catch (Exception $e) {
    App::flash('error', $e->getMessage());
}

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