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

try {
    $user_id = $_SESSION['user']['id'] ?? null;
    if (!$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);
    if ($id <= 0) throw new Exception("ID invalide");

    $stmt = $conn->prepare("SELECT produit_id, quantite FROM matieres_premieres WHERE id = ?");
    $stmt->execute([$id]);
    $matiere = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$matiere) throw new Exception("Matière non trouvée");

    $conn->beginTransaction();

    // Retirer stock
    $conn->prepare("UPDATE stock_depot SET quantite = quantite - ? WHERE produit_id = ?")->execute([$matiere['quantite'], $matiere['produit_id']]);

    // Supprimer matière
    $conn->prepare("DELETE FROM matieres_premieres WHERE id = ?")->execute([$id]);

    $conn->commit();

} catch (Exception $e) {
    if ($conn->inTransaction()) $conn->rollBack();
    die("❌ Erreur Supprimer Matière : " . $e->getMessage());
}

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