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

// Récupérer les productions (sans joindre détails)
$productions = $conn->query("
    SELECT p.*, dp.nom AS depot
    FROM productions p
    JOIN depots dp ON p.depot_id = dp.id
    ORDER BY p.id DESC
")->fetchAll(PDO::FETCH_ASSOC);

$title = "Production";
?>

<div class="container-fluid">
    <h1 class="mt-4">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">Production</li>
    </ol>

    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span><i class="fa fa-industry"></i> Liste des productions</span>
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#ajouterProductionModal">
                <i class="fas fa-plus"></i> Ajouter
            </button>
        </div>

        <div class="card-body">
            <div class="mb-3">
                <label for="filtreStatut" class="form-label">Filtrer par statut :</label>
                <select id="filtreStatut" class="form-select w-auto d-inline-block">
                    <option value="">-- Tous --</option>
                    <option value="brouillon">Brouillon</option>
                    <option value="valide">Validée</option>
                    <option value="annule">Annulée</option>
                </select>
            </div>

            <table id="productionsTable" class="table table-bordered table-striped datatable">
                <thead class="table-dark">
                    <tr>
                        <th>ID</th>
                        <th>Date</th>
                        <th>Dépôt</th>
                        <th>Statut</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($productions as $prod): ?>
                        <tr>
                            <td><?= $prod['id'] ?></td>
                            <td><?= $prod['date_production'] ?></td>
                            <td><?= htmlspecialchars($prod['depot'], ENT_QUOTES, 'UTF-8') ?></td>
                            <td>
                                <?php if ($prod['statut'] === 'annule'): ?>
                                    <span class="badge bg-danger">Annulée</span>
                                <?php elseif ($prod['statut'] === 'brouillon'): ?>
                                    <span class="badge bg-warning text-dark">Brouillon</span>
                                <?php else: ?>
                                    <span class="badge bg-success">Validée</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($prod['statut'] !== 'annule'): ?>
                                    <button class="btn btn-danger btn-sm btnAnnulerProduction"
                                            data-bs-toggle="modal"
                                            data-bs-target="#modalAnnulerProduction"
                                            data-id="<?= $prod['id'] ?>">
                                        <i class="fa fa-ban"></i>
                                    </button>
                                    <button class="btn btn-info btn-sm" 
                                            data-bs-toggle="modal" 
                                            data-bs-target="#visualiserProductionModal<?= $prod['id'] ?>">
                                        <i class="fa fa-eye"></i>
                                    </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php include __DIR__ . "/modal_ajouter_production.php"; ?>
<?php foreach ($productions as $prod): ?>
    <?php
    // Charger détails production : matières + produits finis
    $detailsMatieres = $conn->query("
        SELECT pm.quantite, p.nom AS produit
        FROM production_matieres pm
        JOIN produits p ON pm.produit_id = p.id
        WHERE pm.production_id = " . intval($prod['id'])
    )->fetchAll(PDO::FETCH_ASSOC);

    $detailsFinis = $conn->query("
        SELECT pf.quantite, p.nom AS produit
        FROM production_finis pf
        JOIN produits p ON pf.produit_id = p.id
        WHERE pf.production_id = " . intval($prod['id'])
    )->fetchAll(PDO::FETCH_ASSOC);
    ?>
<?php include __DIR__ . "/modal_visualiser_production.php"; ?>
<?php include __DIR__ . "/modal_annuler_production.php"; ?>
<?php endforeach; ?>

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

<script>
$(document).ready(function() {
    var table = $('#productionsTable').DataTable({
        responsive: true,
        language: {
            url: "/eagle_client_istanbulcups/public/js/fr-FR.json"
        }
    });

    $('#filtreStatut').on('change', function() {
        var value = $(this).val();
        table.column(3).search('^' + value + '$', true, false).draw(); 
    });
});

document.addEventListener("DOMContentLoaded", function() {
    const annulerButtons = document.querySelectorAll(".btnAnnulerProduction");
    const inputId = document.getElementById("annulerProductionId");

    annulerButtons.forEach(btn => {
        btn.addEventListener("click", function() {
            inputId.value = this.dataset.id;
        });
    });
});
</script>
