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

// Récupérer les ventes (sans joindre ventes_details)
$devis = $conn->query("
    SELECT d.*, c.nom AS client_nom
    FROM devis d
    JOIN clients c ON d.client_id = c.idClient
    ORDER BY d.id DESC;

")->fetchAll(PDO::FETCH_ASSOC);

$title = "Devis";
//include __DIR__ . '/../../includes/layout.php';
?>

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

    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span><i class="fa fa-file-signature"></i> Liste des devis</span>
            <?php if(checkPermission('devis.create')): ?>
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#ajouterDevisModal">
                <i class="fas fa-plus"></i> Ajouter
            </button>
            <?php endif; ?>
        </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="Payé">Payé</option>
                <option value="Impayé">Impayé</option>
                <option value="Annulée">Annulée</option>
            </select>
            </div>
         <div class="table-responsive">
            <table id="devisTable" class="table table-bordered table-striped datatable">
                <thead class="table-dark">
                    <tr>
                        <th>N°</th>
                        <th>Client</th>
                        <th>Date</th>
                        <th>Total</th>
                        <th>Statut</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($devis as $d): ?>
                        <tr>
                            <td><?= $d['numero'] ?></td>
                            <td><?= htmlspecialchars($d['client_nom']) ?></td>
                            <td><?= $d['date_devis'] ?></td>
                            <td><?= number_format($d['total_ttc'], 2, ',', ' ') ?>  F CFA</td>
                            <td>
                                <?php switch ($d['statut']):

                                case 'brouillon': ?>
                                    <span class="badge bg-secondary">En cours</span>
                                <?php break;

                                case 'valide': ?>
                                    <span class="badge bg-success">Validé</span>
                                <?php break;

                                case 'refuse': ?>
                                    <span class="badge bg-danger">Refusé</span>
                                <?php break;

                                case 'transforme': ?>
                                    <span class="badge bg-primary">Transformé</span>
                                <?php break;

                                endswitch; ?>
                                </td>
                            <td>
                                <?php if ($d['statut'] == "brouillon"): ?>

                                <button class="btn btn-success btn-sm btnValiderDevis"
                                    data-id="<?= $d['id'] ?>">
                                    <i class="fa fa-check"></i>
                                </button>

                                <button class="btn btn-danger btn-sm btnRefuserDevis"
                                    data-id="<?= $d['id'] ?>">
                                    <i class="fa fa-times"></i>
                                </button>

                            <?php endif; ?>

                            <?php if ($d['statut'] == "valide"): ?>
                            <button  type = "button" class="btn btn-warning btn-sm btnConvertirDevis"
                                data-id="<?= $d['id'] ?>">
                                <i class="fa fa-random"></i>
                            </button>

                            <button type = "button" class="btn btn-danger btn-sm btnAnnulerDevis"
                                data-id="<?= $d['id'] ?>">
                                <i class="fa fa-ban"></i>
                            </button>

                             <?php elseif ($d['statut'] == "refuse"): ?>
                                <!-- <span class="badge bg-danger">Refusé</span> -->

                             <?php elseif ($d['statut'] == "transforme"): ?>
                                    <span class="badge bg-primary">Converti</span>
                              
                           
                            <?php elseif(checkPermission('devis.view')): ?>
                                <button class="btn btn-info btn-sm" 
                                        data-bs-toggle="modal" 
                                        data-bs-target="#visualiserDevisModal<?= $d['id'] ?>">
                                    <i class="fa fa-eye"></i>
                                </button>

                                <a href="pages/rapports/utils/impression.php?cat=ventes&type=facture_client&ticket=a4&id=<?= $d['id'] ?>" 
                                   target="_blank" 
                                   class="btn btn-success btn-sm">
                                    <i class="fa fa-print"></i>
                                </a>

                                <?php endif; ?>

                               

                                
                                

                                
                               
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div> 
      </div>
    </div> 
</div> 

<?php include __DIR__ . "/modal_ajouter_devis.php"; ?>
<?php foreach ($devis as $d): ?>
    <?php
    // Charger les détails de l’achat (produits, dépôts, etc.)
    $details = $conn->query("
    SELECT 
        dd.quantite,
        dd.prix,
        p.nom AS produit
    FROM devis_details dd
    JOIN produits p ON p.id = dd.produit_id
    WHERE dd.devis_id= " . intval($d['id'])
    )->fetchAll(PDO::FETCH_ASSOC);
    ?>
<?php include __DIR__ . "/modal_visualiser_devis.php"; ?>
<?php include __DIR__ . "/modal_annuler_devis.php"; ?>
<?php endforeach; ?>


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


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

    // Filtre statut
    $('#filtreStatut').on('change', function() {
        var value = $(this).val();
        if (value) {
            table.column(4).search('^' + value + '$', true, false).draw(); 
            // ⚠️ Ici "4" = index de la colonne Statut (à ajuster selon ton tableau)
        } else {
            table.column(4).search('').draw();
        }
    });
});
</script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const produitSelect = document.getElementById("produit_id");
    const depotSelect = document.getElementById("depot_id");
    const stockLabel = document.getElementById("stockActuel");

    function chargerStock() {
        let produit_id = produitSelect.value;
        let depot_id = depotSelect.value;

        if (produit_id && depot_id) {
            fetch(`api/get_stock.php?produit_id=${produit_id}&depot_id=${depot_id}`)
                .then(res => res.json())
                .then(data => {
                    stockLabel.textContent = data.message; // "Stock actuel : X"
                })
                .catch(() => {
                    stockLabel.textContent = "Erreur de récupération du stock";
                });
        } else {
            stockLabel.textContent = "Stock actuel : -";
        }
    }

    produitSelect.addEventListener("change", chargerStock);
    depotSelect.addEventListener("change", chargerStock);
});
</script>

<script>
document.addEventListener("DOMContentLoaded", function() {
    const annulerButtons = document.querySelectorAll(".btnAnnulerVente");
    const inputId = document.getElementById("annulerAchatId");

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

<script>
document.addEventListener("DOMContentLoaded", function () {

    //  VALIDER
    document.querySelectorAll(".btnValiderDevis").forEach(btn => {
        btn.addEventListener("click", function () {

            if (!confirm("Valider ce devis ?")) return;

            fetch("/eagle_client_istanbulcups/api/devis/valider.php", {
                method: "POST",
                headers: {"Content-Type": "application/x-www-form-urlencoded"},
                body: "id=" + this.dataset.id
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert("Erreur");
                }
            });
        });
    });

    //  REFUSER
    document.querySelectorAll(".btnRefuserDevis").forEach(btn => {
        btn.addEventListener("click", function () {

            if (!confirm("Refuser ce devis ?")) return;

            fetch("/eagle_client_istanbulcups/api/devis/refuser.php", {
                method: "POST",
                headers: {"Content-Type": "application/x-www-form-urlencoded"},
                body: "id=" + this.dataset.id
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert("Erreur");
                }
            });
        });
    });

});
</script>

<script>
document.querySelectorAll(".btnConvertirDevis").forEach(btn => {
    btn.addEventListener("click", function () {

        if (!confirm("Convertir ce devis en commande ?")) return;

        fetch("/eagle_client_istanbulcups/api/devis/convertir.php", {
            method: "POST",
            headers: {"Content-Type": "application/x-www-form-urlencoded"},
            body: "id=" + this.dataset.id
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                alert("Commande créée !");
                location.reload();
            } else {
                alert(data.message);
            }
        });

    });
});
</script>