<?php
require_once __DIR__ . "/../../config/db.php";

$title = "Inventaire";

// ============================
// PARAMÈTRES
// ============================
$depot_id = isset($_GET['depot_id']) && $_GET['depot_id'] !== ''
    ? (int)$_GET['depot_id']
    : null;

// ============================
// CHARGEMENT DÉPÔTS
// ============================
$depots = $conn->query("
    SELECT id, nom
    FROM depots
    ORDER BY nom
")->fetchAll(PDO::FETCH_ASSOC);

// ============================
// REQUÊTE INVENTAIRE
// ============================
$sql = "
SELECT
    sd.id            AS stock_id,
    p.id             AS produit_id,
    p.reference      AS produit_ref,
    p.nom            AS produit_nom,
    sd.depot_id,
    COALESCE(sd.quantite,0) AS qty_erp
FROM produits p
LEFT JOIN stock_depot sd
    ON sd.produit_id = p.id
WHERE
    (:depot_id IS NULL AND sd.depot_id IS NULL)
    OR (sd.depot_id = :depot_id)
ORDER BY p.nom
";

$stmt = $conn->prepare($sql);
$stmt->execute(['depot_id' => $depot_id]);
$stocks = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container-fluid">
    <h1 class="mt-4">Inventaire <?= $depot_id ? 'par dépôt' : 'global' ?></h1>

    <ol class="breadcrumb mb-3">
        <li class="breadcrumb-item">
            <a href="/eagle_client_istanbulcups/index.php?page=dashboard">Tableau de bord</a>
        </li>
        <li class="breadcrumb-item active">Inventaire</li>
    </ol>

    <!-- FILTRE -->
    <div class="card mb-3">
        <div class="card-body">
            <form method="get" class="row g-2 align-items-end">
                <input type="hidden" name="page" value="inventaire">
                <div class="col-md-4">
                    <label class="form-label">Dépôt</label>
                    <select name="depot_id" class="form-select">
                        <option value="">Stock global</option>
                        <?php foreach ($depots as $dep): ?>
                            <option value="<?= $dep['id'] ?>"
                                <?= $dep['id']===$depot_id ? 'selected':'' ?>>
                                <?= htmlspecialchars($dep['nom']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-8 text-end">
                    <button class="btn btn-primary"><i class="fa fa-filter"></i> Filtrer</button>
                    <a href="?page=inventaire" class="btn btn-outline-secondary">Réinitialiser</a>
                </div>
            </form>
        </div>
    </div>

    <!-- TABLE -->
    <div class="card">
        <div class="card-header d-flex justify-content-between">
            <span><i class="fa fa-clipboard-list"></i> Situation des stocks</span>
            <div>
                <button class="btn btn-success btn-sm">Export Excel</button>
                <button class="btn btn-danger btn-sm">Export PDF</button>
            </div>
        </div>
        <div class="card-body table-responsive">
            <table id="inventaireTable" class="table table-bordered table-striped datatable">
                <thead class="table-dark">
                <tr>
                    <th>Réf</th>
                    <th>Produit</th>
                    <th>Stock ERP</th>
                    <th>Stock physique</th>
                    <th>Écart</th>
                    <th>Action</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($stocks as $s): ?>
                    <tr
                        data-stock-id="<?= $s['stock_id'] ?>"
                        data-produit-id="<?= $s['produit_id'] ?>"
                        data-qty="<?= (int)$s['qty_erp'] ?>"
                    >
                        <td><?= htmlspecialchars($s['produit_ref']) ?></td>
                        <td><?= htmlspecialchars($s['produit_nom']) ?></td>
                        <td class="text-end fw-bold qty-erp"><?= (int)$s['qty_erp'] ?></td>
                        <td class="text-end qty-physique">–</td>
                        <td class="text-end ecart">–</td>
                        <td class="text-center">
                            <button class="btn btn-sm btn-primary btn-ajuster"
                                data-produit="<?= htmlspecialchars($s['produit_nom']) ?>">
                                <i class="fa fa-edit"></i> Ajuster
                            </button>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- MODAL AJUSTEMENT -->
<div class="modal fade" id="modalAjuster" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form method="post"
              id="formAjuster"
              action="/eagle_client_istanbulcups/pages/stocks/update_stock.php"
              class="modal-content">

            <div class="modal-header">
                <h5 class="modal-title">Ajustement de stock</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <input type="hidden" name="stock_id" id="m_stock_id">
                <input type="hidden" name="produit_id" id="m_produit_id">

                <div class="mb-2">
                    <label class="form-label">Produit</label>
                    <div id="m_produit_nom" class="fw-bold"></div>
                </div>

                <div class="mb-2">
                    <label class="form-label">Stock ERP</label>
                    <input type="number" id="m_qty_erp" class="form-control" readonly>
                </div>

                <div class="mb-2">
                    <label class="form-label">Stock physique</label>
                    <input type="number" name="qty_physique" id="m_qty_physique" class="form-control" required>
                </div>

                <div class="mb-2">
                    <label class="form-label">Motif</label>
                    <textarea name="note" class="form-control" rows="2"></textarea>
                </div>

                <div class="alert alert-info small">
                    Un mouvement d’inventaire sera automatiquement enregistré.
                </div>
            </div>

            <div class="modal-footer">
                <button class="btn btn-outline-secondary" data-bs-dismiss="modal">Annuler</button>
                <button type="submit" class="btn btn-primary">Valider</button>
            </div>
        </form>
    </div>
</div>

<?php include __DIR__ . "/../../includes/layout_end.php"; ?>

<script>
$(function(){

    const table = $('#inventaireTable').DataTable({
        responsive: true,
        language: { url: "/eagle_client_istanbulcups/public/js/fr-FR.json" },
        pageLength: 25,
        columnDefs: [{ orderable:false, targets:[3,5] }]
    });

    // Ouvrir modal
    $('#inventaireTable').on('click','.btn-ajuster',function(){
        const tr = $(this).closest('tr');

        $('#m_stock_id').val(tr.data('stock-id'));
        $('#m_produit_id').val(tr.data('produit-id'));
        $('#m_produit_nom').text($(this).data('produit'));
        $('#m_qty_erp').val(tr.data('qty'));
        $('#m_qty_physique').val(tr.data('qty'));

        new bootstrap.Modal('#modalAjuster').show();
    });

    // Soumission AJAX
    $('#formAjuster').submit(function(e){
        e.preventDefault();
        const form = $(this);

        $.post(form.attr('action'), form.serialize())
            .done(function(){
                $('#modalAjuster').modal('hide');

                const stockId   = $('#m_stock_id').val();
                const produitId = $('#m_produit_id').val();
                const oldQty    = parseInt($('#m_qty_erp').val());
                const newQty    = parseInt($('#m_qty_physique').val());
                const ecart     = newQty - oldQty;

                const tr = $('#inventaireTable').find('tr[data-produit-id="'+produitId+'"]');
                tr.find('.qty-erp').text(newQty);         // stock ERP mis à jour
                tr.find('.qty-physique').text(newQty);    // stock physique
                tr.find('.ecart').text(ecart);            // écart

                tr.data('qty', newQty);                   // mise à jour data-qty
            })
            .fail(function(){
                alert('Erreur lors de l’ajustement du stock. Vérifiez la console.');
            });
    });

});
</script>
