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

$commandes = $conn->query("
    SELECT 
        c.id,
        c.numero,
        c.date_commande,
        cl.nom as client_nom,

        SUM(d.quantite_livree - d.quantite_facturee) as reste_a_facturer

    FROM commandes_clients c
    JOIN clients cl ON cl.idClient = c.client_id
    JOIN commandes_clients_details d ON d.commande_id = c.id

    WHERE c.statut IN ('livree','partiellement_livree')

    GROUP BY c.id

    HAVING reste_a_facturer > 0

    ORDER BY c.id DESC
")->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container-fluid">

<h1 class="mt-4">Créer une facture</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">Factures </li>
    </ol>

<div class="card">
<div class="card-body">

<table class="table table-bordered">

<thead class="table-dark">
<tr>
    <th>N°</th>
    <th>Date</th>
    <th>Client</th>
    <th>Reste à facturer</th>
    <th>Action</th>
</tr>
</thead>

<tbody>

<?php foreach($commandes as $c): ?>
<tr>

<td><?= $c['numero'] ?></td>

<td><?= date('d/m/Y', strtotime($c['date_commande'])) ?></td>

<td><?= htmlspecialchars($c['client_nom']) ?></td>

<td class="text-danger">
    <?= number_format($c['reste_a_facturer'],2,',',' ') ?>
</td>

<td>
    <button class="btn btn-primary btnChargerCommande"
            data-id="<?= $c['id'] ?>">
        Sélectionner
    </button>
</td>

</tr>
<?php endforeach; ?>

</tbody>
</table>

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

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

<script>
document.querySelectorAll(".btnChargerCommande").forEach(btn => {

    btn.onclick = function(){

        const id = this.dataset.id;

        fetch("/eagle_client_istanbulcups/api/factures/get_commande_facturable.php?id="+id)
        .then(res => res.json())
        .then(data => {

            afficherFormFacture(data);

        });

    };

});
</script>

<script>
    function afficherFormFacture(data){

    let html = `
    <div class="card mt-3">
    <div class="card-body">

    <h5>Commande ${data.commande.numero}</h5>
    <p>Client : ${data.commande.client}</p>

    <form method="POST" action="/eagle_client_istanbulcups/api/devis/facturer.php">

    <input type="hidden" name="commande_id" value="${data.commande.id}">

    <table class="table table-bordered">
    <thead>
        <tr>
            <th>Produit</th>
            <th>Livré</th>
            <th>Déjà facturé</th>
            <th>Reste</th>
            <th>Facturer</th>
        </tr>
    </thead>
    <tbody>
    `;

    data.details.forEach(d => {

        html += `
        <tr>
            <td>${d.produit}</td>
            <td>${d.quantite_livree}</td>
            <td>${d.quantite_facturee}</td>
            <td>${d.reste}</td>

            <td>
                <input type="number"
                       name="factures[${d.id}]"
                       max="${d.reste}"
                       value="${d.reste}"
                       class="form-control">
            </td>
        </tr>
        `;
    });

    html += `
    </tbody>
    </table>

    <button class="btn btn-success">Créer facture</button>

    </form>
    </div>
    </div>
    `;

    document.querySelector(".container-fluid").insertAdjacentHTML("beforeend", html);
}
</script>