<?php
require_once 'includes/auth.php';
require_once 'config/database.php';
require_once 'includes/functions.php';

header('Content-Type: application/json');

if (!in_array($_SESSION['user_role'], ['superadmin','admin'])) {
    echo json_encode(['success' => false, 'error' => 'Droits insuffisants.']);
    exit;
}

$ids = $_POST['ids'] ?? [];
if (empty($ids) || !is_array($ids)) {
    echo json_encode(['success' => false, 'error' => 'Aucune fiche sélectionnée.']);
    exit;
}

$pdo = getPDO();
$success_count = 0;
$error_count = 0;

$pdo->beginTransaction();
try {
    foreach ($ids as $id) {
        $id = intval($id);
        // Vérifier que la fiche existe et n'est pas déjà supprimée
        $stmt = $pdo->prepare("SELECT id FROM fiches WHERE id = ? AND deleted_at IS NULL");
        $stmt->execute([$id]);
        if ($stmt->fetch()) {
            $stmt2 = $pdo->prepare("UPDATE fiches SET deleted_at = NOW(), deleted_by = ? WHERE id = ?");
            if ($stmt2->execute([$_SESSION['user_id'], $id])) {
                $success_count++;
                logAction($pdo, $_SESSION['user_id'], 'soft_delete_fiche_multiple', "Fiche ID $id");
            } else {
                $error_count++;
            }
        } else {
            $error_count++;
        }
    }
    $pdo->commit();
    echo json_encode(['success' => true, 'deleted' => $success_count, 'errors' => $error_count]);
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}