<?php
include __DIR__ . '/../../config/db.php';

$modepaiement = $conn->query("SELECT id, libelle FROM modes_paiement WHERE libelle !='Transfert interne entre caisses' ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);

$modepaiementOptionsHtml = '';
foreach ($modepaiement as $m) {
    $modepaiementOptionsHtml .= '
        <option value="'.$m['id'].'">'.$m['libelle'].'</option>';
}


?>

<div class="modal fade" id="encaisser<?= $f['id'] ?>" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">

      <form method="POST" action="/eagle_client_istanbulcups/api/factures/encaisser.php">

        <div class="modal-header bg-primary text-white">
          <h5>Encaisser - <?= $f['numero'] ?></h5>
          <button class="btn-close" data-bs-dismiss="modal"></button>
        </div>

        <div class="modal-body">

          <?php
          $total_paye = $conn->query("
            SELECT SUM(montant) 
            FROM encaissements 
            WHERE facture_id=".$f['id']
          )->fetchColumn() ?? 0;

          $reste = $f['total_ttc'] - $total_paye;
          ?>

          <input type="hidden" name="facture_id" value="<?= $f['id'] ?>">
          <input type="hidden" name="client_id" value="<?= $f['client_id'] ?>">

          <div class="mb-2">
            <label>Total facture</label>
            <input type="text" class="form-control" value="<?= number_format($f['total_ttc'],2,',',' ') ?>" readonly>
          </div>

          <div class="mb-2">
            <label>Déjà payé</label>
            <input type="text" class="form-control" value="<?= number_format($total_paye,2,',',' ') ?>" readonly>
          </div>

          <div class="mb-2">
            <label>Reste à payer</label>
            <input type="text" class="form-control" value="<?= number_format($reste,2,',',' ') ?>" readonly>
          </div>

          <div class="mb-2">
            <label>Montant à encaisser</label>
            <input type="number" step="0.01" name="montant" class="form-control" required max="<?= $reste ?>">
          </div>

          <div class="mb-2">
            <label>Mode de paiement</label>
            <select name="mode_paiement_id" class="form-control">
                <?= $modepaiementOptionsHtml ?>
              </select>
          </div>

          <div class="mb-2">
            <label>Référence (optionnel)</label>
            <input type="text" name="reference" class="form-control">
          </div>

        </div>

        <div class="modal-footer">
          <button class="btn btn-success">Encaisser</button>
          <button class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
        </div>

      </form>

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