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

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

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

    $conn->beginTransaction();

    // 1. Insertion article (matière première)
    $stmt = $conn->prepare("
        INSERT INTO articles
        (code, nom, unite_id, cout_achat, seuil_alerte, created_at)
        VALUES (?, ?, ?, ?, ?, NOW())
    ");
    $stmt->execute([
        $code ?: null,
        $nom,
        $unite_id,
        $cout_achat ?: 0,
        $seuil_alerte
    ]);

    $article_id = $conn->lastInsertId();

    $stmt = $conn->prepare("
        INSERT INTO stock_articles (article_id, quantite)
        VALUES (?, ?)
    ");
    $stmt->execute([$article_id, max(0, $quantite)]);

    // 2. Mouvement de stock (entrée)
    if ($quantite > 0) {
        $stmt = $conn->prepare("
            INSERT INTO mouvements_stock_production
            (article_id, type, quantite, reference_table, reference_id, created_at)
            VALUES (?, 'entree', ?, 'articles', ?, NOW())
        ");
        $stmt->execute([$article_id, $quantite, $article_id]);
    }

    $conn->commit();

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

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