<?php
if (session_status() === PHP_SESSION_NONE) session_start();
http_response_code(403);

require_once __DIR__ . '/../config/db_master.php';

// récup subdomain = nom du dossier tenant
$sub = basename(dirname(__DIR__));
$sub = str_replace('eagle_client_', '', $sub);

// retrouver l'ID du client
$stmt = $masterPdo->prepare("SELECT id FROM clients_saas WHERE subdomain=? LIMIT 1");
$stmt->execute([$sub]);
$clientId = $stmt->fetchColumn();
// récupérer facture impayée la + récente
$stmt = $masterPdo->prepare("
    SELECT id 
    FROM saas_factures 
    WHERE client_id=? AND statut!='payé'
    ORDER BY date_creation DESC
    LIMIT 1
");
$stmt->execute([$clientId]);
$invoice = intval($stmt->fetchColumn() ?? 0);

/* echo "<pre>";
var_dump($sub, $clientId, $invoice);
echo "</pre>";
die(); */

// ⚠ fallback sécurité
if ($invoice <= 0) {
    $invoice = 0; // ou message : aucune facture
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Accès suspendu</title>
<link rel="stylesheet" href="/eagle_client_istanbulcups/public/vendor/bootstrap/css/bootstrap.min.css">

<style>
body {
    background: #eef1f5;
}

.card-pay {
    max-width: 850px;
    margin: 70px auto;
    padding: 30px;
    border-radius: 16px;
    background: #fff;
    box-shadow: 0 8px 30px rgba(0,0,0,0.08);
}

.pay-buttons {
    display: flex;
    justify-content: center;
    gap: 22px;
    flex-wrap: wrap;
    margin-top: 25px;
    margin-bottom: 20px;
}

.pay-btn {
    width: 200px;
    height: 110px;
    border-radius: 12px;
    border: 1px solid #e3e6ea;
    background: #ffffff;
    cursor: pointer;
    transition: all 0.25s ease;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    box-shadow: 0 6px 18px rgba(0,0,0,0.05);
}

.pay-btn:hover {
    transform: translateY(-4px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.12);
}

.pay-btn img {
    height: 48px;
}

.status-box {
    width: 100%;
    text-align: center;
    margin-top: 18px;
    font-size: 16px;
    font-weight: 500;
    display: none;
}
</style>
</head>

<body>

<div class="card-pay">
    <div class="text-center mb-3">
        <h1 class="text-danger fw-bold">⛔ Accès suspendu</h1>
        <p class="lead">Votre abonnement est expiré ou une facture est impayée.</p>
        <p class="text-muted">Veuillez choisir un mode de paiement pour rétablir immédiatement l'accès.</p>
    </div>

    <div class="pay-buttons">

        <!-- Wave -->
        <button class="pay-btn" onclick="startPay('wave')">
            <img src="/eagle_client_istanbulcups/public/money/wave.png">
            <small class="mt-2">Payer avec Wave</small>
        </button>

        <!-- Orange Money -->
        <button class="pay-btn" onclick="startPay('om')">
            <img src="/eagle_client_istanbulcups/public/money/om.png">
            <small class="mt-2">Orange Money</small>
        </button>

        <!-- Carte Bancaire -->
        <button class="pay-btn" onclick="startPay('card')">
            <img src="/eagle_client_istanbulcups/public/money/card.png">
            <small class="mt-2">Carte bancaire</small>
        </button>

    </div>

    <div id="statusBox" class="status-box alert alert-info"></div>

    <div class="text-center mt-4">
        <a href="/eagle_client_istanbulcups/login.php" class="btn btn-link">Retour à la connexion</a>
    </div>
</div>


<!-- MODAL QR CODE -->
<div class="modal fade" id="modalPayNow" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Payer la facture</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p id="payInfo"></p>
        <div id="qrBox" class="text-center mb-3"></div>
        <div id="manualBox" class="text-center small text-muted"></div>
      </div>
      <div class="modal-footer">
        <button id="btnIpaid" type="button" class="btn btn-primary">J'ai payé</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fermer</button>
      </div>
    </div>
  </div>
</div>

<div class="toast-container position-fixed top-0 end-0 p-3">
    <div id="toastPaid" class="toast align-items-center text-bg-success border-0" role="alert">
        <div class="d-flex">
            <div class="toast-body">
                Paiement confirmé ! Votre accès est maintenant restauré.
            </div>
            <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    </div>
</div>

<script>
function startPay(method){

  const invoice = <?= json_encode($invoice) ?>;
  const statusBox = document.getElementById('statusBox');

  statusBox.style.display = 'block';
  statusBox.className = "status-box alert alert-info";
  statusBox.innerHTML = "⏳ Connexion au serveur de paiement…";

  // -----------------------------
  // APPEL API VALIDÉ ET FIABLE
  // -----------------------------
  fetch(`/eagle_client_istanbulcups/api/pay.php?invoice_id=${invoice}&method=${method}&simulate=1`, {
      method: "GET",
      headers: {
        "Accept": "application/json"
      }
  })
  .then(response => response.json())
  .then(j => {

      // ❌ Erreur API
      if (!j.ok) {
          statusBox.className = "status-box alert alert-danger";
          statusBox.innerHTML = j.error || "Erreur serveur";
          return;
      }

      // ✔ REDIRECTION (paiement carte)
      if (j.checkout_url) {
          statusBox.className = "status-box alert alert-success";
          statusBox.innerHTML = "Redirection vers la page de paiement…";
          window.location = j.checkout_url;
          return;
      }

      // ✔ OUVERTURE DU MODAL (Wave / OM)
      statusBox.style.display = 'none';

      document.getElementById('payInfo').innerHTML =
          `Facture #${invoice}<br>Montant : <b>${j.amount} ${j.currency}</b>`;

      document.getElementById('qrBox').innerHTML =
          j.qr_url ? `<img src="${j.qr_url}" class="img-fluid">` : '';

      document.getElementById('manualBox').innerHTML =
          j.manual_code ? `Code de paiement : <b>${j.manual_code}</b>` : '';

      // sauvegarde pour "J’ai payé"
      window._lastPaymentSim = {
          invoice: invoice,
          method: method,
          amount: j.amount,
          txref: j.manual_code || ("SIMU"+Date.now())
      };

      // afficher modal
      new bootstrap.Modal(document.getElementById('modalPayNow')).show();
  })
  .catch(err => {
      statusBox.className = "status-box alert alert-danger";
      statusBox.innerHTML = "Erreur réseau : " + err.message;
  });
}
</script>

<script>
// Bouton “J’ai payé”
document.getElementById('btnIpaid').addEventListener('click', () => {

    // Données sauvegardées par startPay()
    const pay = window._lastPaymentSim;

    if (!pay) {
        alert("Aucun paiement en cours.");
        return;
    }

    // Envoi simulation webhook → admin/actions.php
    fetch("/eaglesuite/admin/actions.php?action=webhook_payment", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            invoice_id: pay.invoice,
            amount: pay.amount,
            status: "SUCCESS",
            transaction_ref: pay.txref,
            method: pay.method
        })
    })
    .then(r => r.text())
    .then(t => {

        console.log("Réponse webhook:", t);

		if (t.includes("OK_PAID")) {
			let toast = new bootstrap.Toast(document.getElementById('toastPaid'));
			toast.show();

			setTimeout(() => { window.location.reload(); }, 1500);
		} else {
			alert("Réponse inattendue du serveur : " + t);
		}

    })
    .catch(err => {
        alert("Erreur lors de l’envoi du paiement : " + err.message);
    });

});
</script>



<script src="/eagle_client_istanbulcups/public/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

</body>
</html>
