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

/*
 * Sécurité minimale
 */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: /eagle_client_istanbulcups/index.php?page=inventaire");
    exit;
}

if (empty($_SESSION['user']['id'])) {
    $_SESSION['flash_error'] = "Utilisateur non authentifié.";
    header("Location: /eagle_client_istanbulcups/index.php?page=inventaire");
    exit;
}

/*
 * Données POST
 */
$produit_id   = (int)($_POST['produit_id'] ?? 0);
$qty_physique = (int)($_POST['qty_physique'] ?? -1);
$note         = trim($_POST['note'] ?? '');

$depot_id_raw = $_POST['depot_id'] ?? null;
$depot_id     = ($depot_id_raw !== null && (int)$depot_id_raw > 0)
                ? (int)$depot_id_raw
                : null; // 👈 MODE SANS DÉPÔT

if ($produit_id <= 0 || $qty_physique < 0) {
    $_SESSION['flash_error'] = "Données inventaire invalides.";
    header("Location: /eagle_client_istanbulcups/index.php?page=inventaire");
    exit;
}

try {
    $conn->beginTransaction();

    require_once __DIR__ . "/../../includes/check_cloture_stock.php";

    $date_mouvement = date('Y-m-d H:i:s');

    verifierClotureStock($conn, $date_mouvement, $depot_id);


    /*
     * 1. Récupérer stock ERP (verrouillé)
     */
    if ($depot_id === null) {
        // STOCK GLOBAL (sans dépôt)
        $stmt = $conn->prepare("
            SELECT id, quantite
            FROM stock_depot
            WHERE produit_id = ? AND depot_id IS NULL
            FOR UPDATE
        ");
        $stmt->execute([$produit_id]);
    } else {
        // STOCK PAR DÉPÔT
        $stmt = $conn->prepare("
            SELECT id, quantite
            FROM stock_depot
            WHERE produit_id = ? AND depot_id = ?
            FOR UPDATE
        ");
        $stmt->execute([$produit_id, $depot_id]);
    }

    $stock = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($stock) {
        $stockId = (int)$stock['id'];
        $old_qty = (int)$stock['quantite'];
    } else {
        // créer la ligne stock
        $stmt = $conn->prepare("
            INSERT INTO stock_depot (produit_id, depot_id, quantite)
            VALUES (?, ?, 0)
        ");
        $stmt->execute([$produit_id, $depot_id]);
        $stockId = (int)$conn->lastInsertId();
        $old_qty = 0;
    }

    /*
     * 2. Calcul écart
     */
    $delta = $qty_physique - $old_qty;

    if ($delta !== 0) {

        $type = $delta > 0 ? 'inventaire_entree' : 'inventaire_sortie';

        /*
         * 3. Mouvement stock (audit)
         */
        $stmt = $conn->prepare("
            INSERT INTO mouvements_stock
            (produit_id, depot_source_id, depot_dest_id, quantite, type,
             reference_table, reference_id, utilisateur_id, note, date_mouvement)
            VALUES (?, ?, ?, ?, ?, 'inventaire', ?, ?, ?, NOW())
        ");

        $stmt->execute([
            $produit_id,
            $delta < 0 ? $depot_id : null,
            $delta > 0 ? $depot_id : null,
            abs($delta),
            $type,
            $stockId,
            $_SESSION['user']['id'],
            $note
        ]);

        /*
         * 4. Mise à jour stock_depot par DELTA
         */
        $stmt = $conn->prepare("
            UPDATE stock_depot
            SET quantite = quantite + ?
            WHERE id = ?
        ");
        $stmt->execute([$delta, $stockId]);
    }

    $conn->commit();

    $_SESSION['flash_success'] =
        $delta === 0
        ? "Aucun écart constaté (stock conforme)."
        : "Inventaire validé. Écart : {$delta}";

} catch (Exception $e) {
    $conn->rollBack();
    $_SESSION['flash_error'] = $e->getMessage();
    header("Location: /eagle_client_istanbulcups/index.php?page=inventaire");
    exit;
}

/* header("Location: /eagle_client_istanbulcups/index.php?page=inventaire");
exit; */
