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

$projet_id = filter_input(INPUT_POST, 'projet_id', FILTER_VALIDATE_INT);
if (!$projet_id) {
    echo json_encode(['success' => false, 'error' => 'Projet invalide.']);
    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();

// Mise à jour directe via jointure
$sql = "UPDATE fiches f
        JOIN sous_dossiers sd ON f.sous_dossier_id = sd.id
        JOIN dossiers d ON sd.dossier_id = d.id
        SET f.signature_responsable = ?, f.signature_responsable_date = NOW()
        WHERE d.projet_id = ? AND f.signature_responsable IS NULL AND f.deleted_at IS NULL";

$stmt = $pdo->prepare($sql);
$success = $stmt->execute([$signature_path, $projet_id]);
$count = $stmt->rowCount();

if ($success) {
    logAction($pdo, $_SESSION['user_id'], 'signature_all_fiches', "Projet ID $projet_id, $count fiches signées");
    echo json_encode(['success' => true, 'count' => $count]);
} else {
    echo json_encode(['success' => false, 'error' => 'Erreur lors de la mise à jour.']);
}