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

// Commandes fournisseurs
$commandes = $conn->query("
    SELECT c.*, cl.nom AS client_nom
    FROM commandes_clients c
    JOIN clients cl ON cl.idClient = c.client_id
    
    ORDER BY c.id DESC
")->fetchAll(PDO::FETCH_ASSOC);

?>

<div class="container-fluid px-2">
    <h1 class="mt-4">Commandes Clients</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">Commandes Clients </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"></i> Liste des commandes fournisseurs
            </span> 
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#ajouterCommandeModal">
                <i class="fas fa-plus"></i> Ajouter
            </button>
        </div>

        <div class="card-body">

          <table class="table table-bordered table-striped datatable">
          <thead class="table-dark">
          <tr>
            <th>N°</th>
            <th>Date</th>
            <th>Client</th>
            <th>Total</th>
            <th>Statut</th>
            <th>Actions</th>
          </tr>
          </thead>
          <tbody>

          <?php foreach ($commandes as $c): ?>
          <tr>
            <td><?= htmlspecialchars($c['numero']) ?></td>
            <td><?= date('d/m/Y H:i', strtotime($c['date_commande'])) ?></td>
            <td><?= htmlspecialchars($c['client_nom']) ?></td>
            <td><?= number_format($c['total_ttc'],2,',',' ') ?> FCFA</td>
            <td>
              <?php if($c['statut']=='en_cours'): ?>
                <span class="badge bg-warning">En cours</span>
              <?php elseif($c['statut']=='partiellement_livree'): ?>
                <span class="badge bg-info">Partiellement Livrée</span>
              <?php elseif($c['statut']=='livree'): ?>
                <span class="badge bg-success">Livrée</span>
              <?php elseif($c['statut']=='facturee'): ?>
                <span class="badge bg-success">Facturée</span>
              <?php endif; ?>
           </td>
            <td>
            <!-- Voir -->
            <button class="btn btn-info btn-sm"
              data-bs-toggle="modal"
              data-bs-target="#voirCommande<?= $c['id'] ?>">
              <i class="fa fa-eye"></i>
           </button>

            <!-- Livrer -->
            <?php if(in_array($c['statut'], ['en_cours','partiellement_livree'])): ?>
            <button class="btn btn-primary btn-sm"
                data-bs-toggle="modal"
                data-bs-target="#livrerPartiel<?= $c['id'] ?>">
                <i class="fa fa-truck"></i>
            </button>
            <?php endif; ?>

            <!-- Facturer -->
            <!--?php if($c['statut']=='livree'): ?>
            <button class="btn btn-success btn-sm"
              data-bs-toggle="modal"
              data-bs-target="#facturerCommande<-?= $c['id'] ?>">
              <i class="fa fa-file-invoice"></i>
          </button>
            <-?php endif; ?-->
          </td>

          </tr>
          <?php endforeach ?>

          </tbody>
          </table>
</div>

<?php include __DIR__ . "/modal_ajouter_commande.php"; ?>

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

$details = $conn->query("
    SELECT d.*, p.nom as produit
    FROM commandes_clients_details d
    JOIN produits p ON p.id = d.produit_id
    WHERE d.commande_id = ".intval($c['id'])
)->fetchAll(PDO::FETCH_ASSOC);

?>
<?php include __DIR__ . "/modal_voir_commande.php"; ?>
<?php include __DIR__ . "/modal_livrer_commande.php"; ?>
<?php include __DIR__ . "/modal_facturer_commande.php"; ?>
<?php endforeach; ?>

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

<script>
$(function(){
  $('.datatable').DataTable({
    responsive:true,
    language:{ url:"/eagle_client_istanbulcups/public/js/fr-FR.json" }
  });
});
</script>

<script>
/* document.querySelectorAll(".btnLivrer").forEach(btn=>{
  btn.onclick = function(){
    if(!confirm("Confirmer livraison ?")) return;

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

document.querySelectorAll(".btnFacturer").forEach(btn=>{
  btn.onclick = function(){
    if(!confirm("Créer facture ?")) return;

    fetch("/api/devis/facturer.php",{
      method:"POST",
      headers:{"Content-Type":"application/x-www-form-urlencoded"},
      body:"id="+this.dataset.id
    })
    .then(r=>r.json())
    .then(d=>{ if(d.success) location.reload(); else alert(d.message); });
  }
});
</script>