<?php
session_start();
require_once __DIR__ . "/../../config/db.php";

try {
    if (!isset($_SESSION['user']['id'])) {
        throw new Exception("Utilisateur non authentifié");
    }

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception("Méthode non autorisée");
    }

    $id           = (int)($_POST['id'] ?? 0);
    $code         = trim($_POST['code'] ?? '');
    $nom          = trim($_POST['nom'] ?? '');
    $unite_id     = (int)($_POST['unite_id'] ?? 0);
    $cout_achat   = (float)($_POST['cout_achat'] ?? 0);
    $seuil_alerte = (float)($_POST['seuil_alerte'] ?? 0);

    if ($id <= 0 || $nom === '' || $unite_id <= 0) {
        throw new Exception("Données invalides");
    }

    $stmt = $conn->prepare("
        UPDATE articles
        SET code = ?,
            nom = ?,
            unite_id = ?,
            cout_achat = ?,
            seuil_alerte = ?
        WHERE id = ?
    ");
    $stmt->execute([
        $code,
        $nom,
        $unite_id,
        $cout_achat,
        //$quantite,
        $seuil_alerte,
        $id
    ]);

    header("Location: /eagle_client_istanbulcups/index.php?page=matiere-premiere");
    exit;

} catch (Exception $e) {
    die("❌ Erreur modification article : " . $e->getMessage());
}
