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

/**
 * Liste des réceptions fournisseurs
 * + info achat lié (s'il existe)
 */
$stmt = $conn->prepare("
 SELECT 
        rf.id,
        rf.commande_id,
        rf.date_reception,
        rf.statut,
        u.nom AS utilisateur,
        COUNT(DISTINCT rfd.id) AS nb_lignes,
        COALESCE(SUM(rfd.quantite_livree), 0) AS total_quantite,
        CASE WHEN a.id IS NOT NULL THEN 1 ELSE 0 END AS achat_genere
    FROM receptions_fournisseurs rf
    LEFT JOIN receptions_fournisseurs_details rfd 
           ON rfd.reception_id = rf.id
    LEFT JOIN utilisateurs u 
           ON u.id = rf.utilisateur_id
    LEFT JOIN achats a 
           ON a.reception_id = rf.id
    GROUP BY rf.id
    ORDER BY rf.date_reception DESC
");
$stmt->execute();
$receptions = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container-fluid px-2">
    <h1 class="mt-4">Réceptions fournisseurs</h1>

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

    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span><i class="fa fa-truck-loading"></i> Liste des réceptions fournisseurs</span>
            <!-- <a href="?page=reception_fournisseur&id=<!?= $c['id'] ?>" class="btn btn-primary btn-sm" title="Réception">
                <i class="fa fa-truck"></i> Ajouter
            </a> -->
        </div>

        <div class="card-body">
            <table class="table table-bordered table-striped datatable" id="receptionsTable">
                <thead class="table-dark">
                    <tr>
                        <th>#</th>
                        <th>Date réception</th>
                        <th>Nb produits</th>
                        <th>Quantité totale</th>
                        <th>Statut</th>
                        <th>Utilisateur</th>
                        <th class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($receptions as $r): ?>
                        <tr>
                            <td><?= (int)$r['id'] ?></td>
                            <td><?= $r['date_reception'] ? date('d/m/Y H:i', strtotime($r['date_reception'])) : '-' ?></td>
                            <td class="text-center"><?= (int)$r['nb_lignes'] ?></td>
                            <td class="text-center"><?= (int)$r['total_quantite'] ?></td>
                            <td class="text-center">
                                <?php if ($r['statut'] === 'complete'): ?>
                                    <span class="badge bg-success">Complète</span>
                                <?php else: ?>
                                    <span class="badge bg-warning text-dark">Partielle</span>
                                <?php endif; ?>
                            </td>
                            <td><?= htmlspecialchars($r['utilisateur'] ?? '-') ?></td>
                            <td class="text-center">

                                <!-- Voir réception -->
                                <a href="/eagle_client_istanbulcups/index.php?page=reception_fournisseur_view&id=<?= (int)$r['id'] ?>"
                                   class="btn btn-info btn-sm" title="Voir la réception">
                                    <i class="fa fa-eye"></i>
                                </a>

                                <!-- Écarts commande / réception -->
                                <?php if ((int)$r['commande_id'] > 0): ?>
                                    <a href="/eagle_client_istanbulcups/index.php?page=ecarts_commande_reception&id=<?= (int)$r['commande_id'] ?>"
                                       class="btn btn-outline-secondary btn-sm" title="Voir les écarts">
                                        <i class="fa fa-balance-scale"></i>
                                    </a>
                                <?php endif; ?>

                                <!-- Achat généré ou à générer -->
                                <?php if (!$r['achat_genere']): ?>
                                    <button 
                                        class="btn btn-warning btn-sm btnValiderReception"
                                        data-id="<?= (int)$r['id'] ?>">
                                        <i class="fa fa-check"></i>
                                    </button>
                                <?php else: ?>
                                    <span class="badge bg-success">Achat généré</span>
                                <?php endif; ?>

                                <!-- Impression -->
                                <a href="print/reception_print.php?id=<?= $reception_id ?>" target="_blank"
                                   class="btn btn-success btn-sm" title="Imprimer la réception">
                                    <i class="fa fa-print"></i>
                                </a>

                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div> <!-- fin card-body -->
    </div> <!-- fin card -->
</div> <!-- fin container -->



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

<script>
$(function () {

    $('#receptionsTable').DataTable({
        responsive: true,
        language: {
            url: "/eagle_client_istanbulcups/public/js/fr-FR.json"
        }
    });

    $(document).on("click", ".btnValiderReception", function (e) {

        e.preventDefault();

        let receptionId = $(this).data("id");

        $.get("pages/achats/modal_valider_reception.php", {
            reception_id: receptionId
        }).done(function (html) {

            $("body").append(html);

            let modal = new bootstrap.Modal(
                document.getElementById("modalValiderReception")
            );

            modal.show();

            $("#modalValiderReception").on("hidden.bs.modal", function () {
                $(this).remove();
            });

        }).fail(function () {
            alert("Erreur chargement modal.");
        });

    });

});

</script>
