<?php

require_once __DIR__ . "/../../config/db.php";
require_once __DIR__ . "/../../includes/check_auth.php";

$title = "Simulation de production";

// Produits finis (préparations)
$produits_finis = $conn->query("
    SELECT id, nom
    FROM produits
    WHERE est_preparation = 1
    ORDER BY nom
")->fetchAll(PDO::FETCH_ASSOC);
?>
<?php if (!empty($_SESSION['flash_message'])): ?>
    <div class="alert alert-<?= $_SESSION['flash_type'] ?> alert-dismissible fade show" role="alert">
        <?= $_SESSION['flash_message'] ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php
    unset($_SESSION['flash_message'], $_SESSION['flash_type']);
endif;
?>


<div class="container-fluid">

    <h1 class="mt-4">Simulation de production</h1>

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

    <!-- FORMULAIRE -->
    <div class="card mb-4">
        <div class="card-header"><i class="fa fa-calculator"></i> Paramètres de simulation</div>
        <div class="card-body">
            <form id="formSimulation" method="POST">
                <div class="row g-3 align-items-end">

                    <div class="col-md-5">
                        <label class="form-label">Produit fini</label>
                        <select name="produit_id" class="form-select" required>
                            <option value="">-- Sélectionner --</option>
                            <?php foreach ($produits_finis as $p): ?>
                                <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['nom']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Quantité à produire</label>
                        <input type="number" step="0.01" min="0.01" name="quantite" class="form-control" required>
                    </div>

                    <div class="col-md-4">
                        <button type="submit" class="btn btn-primary w-100"><i class="fa fa-play"></i> Lancer la simulation</button>
                    </div>

                </div>
            </form>
        </div>
    </div>

    <!-- RESULTAT -->
    <div id="resultSimulation" style="display:none;">
        <div class="card mb-4">
            <div class="card-header"><i class="fa fa-list"></i> Détail des matières premières</div>
            <div class="card-body p-0">
                <table class="table table-bordered mb-0">
                    <thead class="table-dark">
                        <tr>
                            <th>Matière</th>
                            <th>Unité</th>
                            <th class="text-end">Stock</th>
                            <th class="text-end">Besoin</th>
                            <th class="text-end">Manquant</th>
                            <th class="text-end">Coût estimé</th>
                            <th class="text-center">État</th>
                        </tr>
                    </thead>
                    <tbody id="simulationTableBody">
                        <!-- Contenu dynamique -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Bloc coûts -->
        <div class="row">
            <div class="col-md-6">
                <div class="alert alert-info"><strong>Coût total estimé :</strong> <span id="coutTotal">0</span> F CFA</div>
            </div>
            <div class="col-md-6">
                <div class="alert alert-success"><strong>Coût unitaire estimé :</strong> <span id="coutUnitaire">0</span> F CFA</div>
            </div>
        </div>

        <!-- Action -->
        <div class="text-end">
            <form method="POST" action="/eagle_client_istanbulcups/api/production/valider_production.php">
                <input type="hidden" name="produit_id" id="produit_id_valider">
                <input type="hidden" name="quantite" id="quantite_valider">
                <button type="submit" id="btnValiderProduction" class="btn btn-success" disabled>
                    <i class="fa fa-check"></i> Valider la production
                </button>
            </form>
        </div>

    </div>
</div>

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

<script>
document.getElementById('formSimulation').addEventListener('submit', function(e){
    e.preventDefault();
    const form = this;
    const formData = new FormData(form);

    fetch('/eagle_client_istanbulcups/api/production/simuler_production.php', {
        method: 'POST',
        body: formData
    })
    .then(r => r.text())
    .then(html => {
        const tbody = document.getElementById('simulationTableBody');
        tbody.innerHTML = html;

        // Récupérer les coûts et possible depuis le TR caché
        const trCouts = document.getElementById('coutsSimulation');
        const coutTotal = parseFloat(trCouts.dataset.coutTotal) || 0;
        const coutUnitaire = parseFloat(trCouts.dataset.coutUnitaire) || 0;
        const possible = trCouts.dataset.possible === '1';

        document.getElementById('coutTotal').textContent = coutTotal.toFixed(2);
        document.getElementById('coutUnitaire').textContent = coutUnitaire.toFixed(2);

        document.getElementById('btnValiderProduction').disabled = !possible;

        // Préparer les champs hidden pour valider
        document.getElementById('produit_id_valider').value = formData.get('produit_id');
        document.getElementById('quantite_valider').value = formData.get('quantite');

        document.getElementById('resultSimulation').style.display = 'block';
    })
    .catch(err => {
        console.error(err);
        alert("Erreur lors de la simulation");
    });
});
</script>
