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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$reception_id = (int)($_GET['reception_id'] ?? 0);

if ($reception_id <= 0) {
    exit("<div class='alert alert-danger'>Réception invalide</div>");
}

$stmt = $conn->prepare("
SELECT rf.*, cf.fournisseur_id, f.nom AS fournisseur
FROM receptions_fournisseurs rf
JOIN commandes_fournisseurs cf ON cf.id = rf.commande_id
JOIN fournisseurs f ON f.id = cf.fournisseur_id
WHERE rf.id = ?
");
$stmt->execute([$reception_id]);
$reception = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$reception) {
    exit("<div class='alert alert-danger'>Réception introuvable</div>");
}

$stmt = $conn->prepare("SELECT id FROM achats WHERE reception_id = ?");
$stmt->execute([$reception_id]);
if ($stmt->fetch()) {
    exit("<div class='alert alert-success'>Achat déjà généré</div>");
}

$stmt = $conn->prepare("
SELECT rfd.*, p.nom
FROM receptions_fournisseurs_details rfd
JOIN produits p ON p.id = rfd.produit_id
WHERE rfd.reception_id = ?
");
$stmt->execute([$reception_id]);
$details = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$details) {
    exit("<div class='alert alert-warning'>Aucun produit trouvé</div>");
}

$total = 0;
foreach ($details as $d) {
    $total += $d['quantite_livree'] * $d['prix_achat'];
}

$_SESSION['csrf_token_reception'] = bin2hex(random_bytes(32));

$modes = $conn->query("SELECT id, libelle FROM modes_paiement ORDER BY id")
              ->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="modal fade" id="modalValiderReception" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">

      <form id="formValiderReception" method="POST"
            action="/eagle_client_istanbulcups/api/achats/valider_reception_save.php">

        <div class="modal-header bg-warning">
          <h5 class="modal-title">
            Validation Réception #<?= $reception_id ?>
          </h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>

        <div class="modal-body">

          <p><strong>Fournisseur :</strong> <?= htmlspecialchars($reception['fournisseur']) ?></p>
          <p><strong>Total :</strong> <?= number_format($total,0,'',' ') ?> FCFA</p>

          <input type="hidden" name="csrf_token"
                 value="<?= $_SESSION['csrf_token_reception'] ?>">
          <input type="hidden" name="reception_id"
                 value="<?= $reception_id ?>">

          <div class="mb-3">
              <label>Mode de paiement</label>
              <select name="mode_paiement_id" class="form-control" required>
                  <option value="">-- Choisir --</option>
                  <?php foreach($modes as $m): ?>
                      <option value="<?= $m['id'] ?>">
                          <?= htmlspecialchars($m['libelle']) ?>
                      </option>
                  <?php endforeach; ?>
              </select>
          </div>

          <div class="mb-3">
              <label>Montant versé</label>
              <input type="number" step="0.01"
                     name="montant_verse"
                     class="form-control"
                     value="0"
                     min="0">
          </div>

        </div>

        <div class="modal-footer">
          <button type="submit"
                  class="btn btn-primary"
                  id="btnSubmitReception">
              Valider et créer achat
          </button>
        </div>

      </form>

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