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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Méthode non autorisée']);
    exit;
}

$fiche_id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
$field = $_POST['field'] ?? '';
$value = $_POST['value'] ?? '';

$allowed_fields = ['zone', 'observation', 'type_reserve'];
if (!$fiche_id || !in_array($field, $allowed_fields)) {
    echo json_encode(['success' => false, 'error' => 'Paramètres invalides']);
    exit;
}

$pdo = getPDO();
$stmt = $pdo->prepare("SELECT createur_id, deleted_at FROM fiches WHERE id = ?");
$stmt->execute([$fiche_id]);
$fiche = $stmt->fetch();

if (!$fiche || $fiche['deleted_at'] !== null) {
    echo json_encode(['success' => false, 'error' => 'Fiche introuvable ou supprimée']);
    exit;
}

$peut_modifier = ($_SESSION['user_role'] === 'superadmin' || $_SESSION['user_role'] === 'admin' || $_SESSION['user_id'] == $fiche['createur_id']);
if (!$peut_modifier) {
    echo json_encode(['success' => false, 'error' => 'Droits insuffisants']);
    exit;
}

if ($field === 'type_reserve' && !in_array($value, ['sans_reserve','avec_reserve'])) {
    echo json_encode(['success' => false, 'error' => 'Valeur invalide']);
    exit;
}

try {
    $stmt = $pdo->prepare("UPDATE fiches SET $field = ? WHERE id = ?");
    $stmt->execute([$value, $fiche_id]);
    logAction($pdo, $_SESSION['user_id'], "modification_$field", "Fiche $fiche_id");
    echo json_encode(['success' => true]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}