<?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;
}

$signature_path = $_SESSION['user_signature'] ?? null;
if (!$signature_path || !file_exists($signature_path)) {
    echo json_encode(['success' => false, 'error' => 'Vous n\'avez pas de signature enregistré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 est éligible (non supprimée, non déjà signée)
        $stmt = $pdo->prepare("SELECT id FROM fiches WHERE id = ? AND deleted_at IS NULL AND signature_responsable IS NULL");
        $stmt->execute([$id]);
        if ($stmt->fetch()) {
            $stmt2 = $pdo->prepare("UPDATE fiches SET signature_responsable = ?, signature_responsable_date = NOW() WHERE id = ?");
            if ($stmt2->execute([$signature_path, $id])) {
                $success_count++;
                logAction($pdo, $_SESSION['user_id'], 'signature_fiche_multiple', "Fiche ID $id");
            } else {
                $error_count++;
            }
        } else {
            $error_count++;
        }
    }
    $pdo->commit();
    echo json_encode(['success' => true, 'signed' => $success_count, 'errors' => $error_count]);
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}