<?php
/* -----------------------------------------------------------
   BALDMART EXPRESS — Single-file landing + COD checkout
   - Posts to Google Apps Script (Sheets)
   - Sends a Telegram DM with the order
   - Redirects to thank2.html
   ----------------------------------------------------------- */

/* ---------- Preview/dev helpers ---------- */
if (isset($_GET['clear_ordered'])) {
    setcookie('ordered', '', time() - 3600, '/');
    header('Location: index.php?preview=1');
    exit;
}
$preview = isset($_GET['preview']);

/* ---------- If already ordered (except preview mode) ---------- */
if (!$preview && isset($_COOKIE['ordered'])) {
    header('Location: thank2.html');
    exit;
}

/* ---------- CONFIG (edit if needed) ---------- */
$GAS_URL = 'https://script.google.com/macros/s/AKfycbxPs1DxxQtgvzOJHEyGNzU_bOq0hAYJ3hfMLb4eqSH9KAKMDiZyCLBqpSZj4-UpmZeSNw/exec';

$TELEGRAM_BOT_TOKEN = '8342446046:AAHYv65ojS9iZMX1rrMoTdXAupxps_ul56w';
$TELEGRAM_CHAT_ID   = '6582655787'; // your user/chat id

$CODIA_KEY    = 'kfq2tdaxqvquioii6aiqnts5ajhhg2npoglnsbvp';
$CODIA_SECRET = 'pvipa5hdombjymmkxts8santdcrgyrh8gpsijnu0';
$CODIA_SOURCE = 'LANDING';

/* ---------- small utilities ---------- */
function fmt_money($n) {
    return number_format((float)$n, 0, ',', ' ') . ' F';
}

/* Robust HTTP POST: try cURL → stream context */
function http_post(string $url, array $data, int &$status, string &$body, string &$err): bool {
    $status = 0; $body = ''; $err = '';

    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => http_build_query($data),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_TIMEOUT        => 20,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ]);
        $body   = curl_exec($ch);
        $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err    = curl_error($ch);
        curl_close($ch);

        if ($body !== false && ($status >= 200 && $status < 400)) return true;
        if (is_string($body) && stripos($body, 'ok') !== false)   return true;
    }

    if (ini_get('allow_url_fopen')) {
        $opts = [
            'http' => [
                'method'  => 'POST',
                'header'  => "Content-Type: application/x-www-form-urlencoded\r\n",
                'content' => http_build_query($data),
                'timeout' => 20
            ],
            'ssl'  => [
                'verify_peer'      => false,
                'verify_peer_name' => false
            ]
        ];
        $ctx  = stream_context_create($opts);
        $body = @file_get_contents($url, false, $ctx);
        if (isset($http_response_header[0]) &&
            preg_match('#\s(\d{3})\s#', $http_response_header[0], $m)) {
            $status = (int)$m[1];
        }
        if ($body !== false && ($status >= 200 && $status < 400)) return true;
        if (is_string($body) && stripos($body, 'ok') !== false)   return true;

        $err = 'stream error';
    } else {
        $err = 'No cURL and allow_url_fopen=0';
    }
    return false;
}


/* JSON POST (for CodInAfrica) */
/* JSON POST (for CodInAfrica) */
function http_post_json(string $url, array $data, int &$status=0, string &$body='', string &$err=''): bool {
  $status = 0; $body = ''; $err = '';
  $payload = json_encode($data, JSON_UNESCAPED_UNICODE);

  if (function_exists('curl_init')) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
      CURLOPT_POST           => true,
      CURLOPT_POSTFIELDS     => $payload,
      CURLOPT_HTTPHEADER     => ['Content-Type: application/json','User-Agent: Baldmart/1.0'],
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_TIMEOUT        => 20,
      CURLOPT_SSL_VERIFYPEER => false,
      CURLOPT_SSL_VERIFYHOST => false,
    ]);
    $body   = curl_exec($ch);
    $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err    = curl_error($ch);
    curl_close($ch);
    return ($body !== false && $status >= 200 && $status < 400);
  }

  if (ini_get('allow_url_fopen')) {
    $opts = [
      'http' => [
        'method'  => 'POST',
        'header'  => "Content-Type: application/json\r\nUser-Agent: Baldmart/1.0\r\n",
        'content' => $payload,
        'timeout' => 20
      ],
      'ssl'  => ['verify_peer'=>false,'verify_peer_name'=>false]
    ];
    $ctx  = stream_context_create($opts);
    $body = @file_get_contents($url, false, $ctx);
    if (isset($http_response_header[0]) && preg_match('#\s(\d{3})\s#',$http_response_header[0],$m)) {
      $status = (int)$m[1];
    }
    return ($body !== false && $status >= 200 && $status < 400);
  }

  $err = 'No cURL and allow_url_fopen=0';
  return false;
}


/* Telegram sender (doesn't block the checkout) */
function telegram_notify(string $token, string $chat_id, string $text): void {
    if (!$token || !$chat_id) return;
    $url = "https://api.telegram.org/bot{$token}/sendMessage";
    $payload = [
        'chat_id' => $chat_id,
        'text'    => $text,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true
    ];
    $st = 0; $bd = ''; $er = '';
    http_post($url, $payload, $st, $bd, $er);
}

/* ---------- Handle POST (the actual order) ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['Phone'])) {

  /* --------- READ + NORMALIZE --------- */
  $name    = trim($_POST['Name']    ?? '');
  $phone   = trim($_POST['Phone']   ?? '');
  $address = trim($_POST['Address'] ?? '');
  $product = trim($_POST['Product'] ?? 'Tensiomètre Blanc');
  $sku     = trim($_POST['SKU']     ?? 'TM-Gu');

  $qty     = max(1, (int)($_POST['Offer'] ?? 1));
  $total   = (float)($_POST['Price'] ?? 0.0);
  $unit    = (int)round($total / $qty);

  // Country: use GN for Guinea (often people send "GU" by mistake)
  $country = strtoupper($_POST['Country'] ?? 'GN');
  if ($country === 'GU') { $country = 'GN'; }

  // Create an order id for external systems (Sheet + CodInAfrica)
  $orderId = $_POST['OrderId'] ?? ('COD' . date('ymdHis') . mt_rand(100,999));
  $_POST['OrderId'] = $orderId; // include in the payload you send to your Sheet

  /* --------- COD IN AFRICA API --------- */
  // (put these in your config section if you prefer)
  $CODIA_KEY    = 'kfq2tdaxqvquioii6aiqnts5ajhhg2npoglnsbvp';
  $CODIA_SECRET = 'pvipa5hdombjymmkxts8santdcrgyrh8gpsijnu0';
  $CODIA_SOURCE = 'LANDING'; // or SHEET / SHOPIFY — just a label

  $codiaPayload = [
    'orderId'   => $orderId,
    'fullName'  => $name,
    'phone'     => $phone,
    'country'   => $country,
    'city'      => $address,     // you only collect one field; reuse it
    'address'   => $address,
    'total'     => (int)round($total),
    'storeName' => 'BALDMART EXPRESS',
    'items'     => [[
      'name'     => $product,
      'code'     => $sku ?: $product,
      'quantity' => (int)$qty,
      'price'    => $unit        // unit price
    ]]
  ];

  $codiaUrl = "https://api.codinafrica.com/api/orders/apicreate"
            . "?key={$CODIA_KEY}&secret={$CODIA_SECRET}&source={$CODIA_SOURCE}";

  $codiaStatus=0; $codiaBody=''; $codiaErr='';
  $codiaOK = http_post_json($codiaUrl, $codiaPayload, $codiaStatus, $codiaBody, $codiaErr);
  if (!$codiaOK) {
    // optional: alert yourself if their API fails
    telegram_notify($TELEGRAM_BOT_TOKEN, $TELEGRAM_CHAT_ID,
      "⚠️ CodInAfrica API failed for {$orderId} (HTTP {$codiaStatus}). Resp: {$codiaBody}");
  }

  /* --------- TELEGRAM MESSAGE (for your records) --------- */
  $msg = "✅ <b>Nouvelle commande</b>\n"
       . "🧾 ID: {$orderId}\n"
       . "📦 Produit: {$product} (SKU {$sku})\n"
       . "🔢 Quantité: {$qty}\n"
       . "💵 Prix unitaire: " . fmt_money($unit) . "\n"
       . "💰 Total: " . fmt_money($total) . "\n"
       . "👤 Nom: {$name}\n"
       . "📞 Tel: {$phone}\n"
       . "📍 Adresse: {$address}\n"
       . "🌍 Pays: {$country}";
  telegram_notify($TELEGRAM_BOT_TOKEN, $TELEGRAM_CHAT_ID, $msg);

  /* --------- SEND TO GOOGLE SHEET --------- */
  $status = 0; $resp = ''; $err = '';
  $ok_to_gas = http_post($GAS_URL, $_POST, $status, $resp, $err);

  /* --------- REDIRECT OR FALLBACK --------- */
  if ($ok_to_gas) {
      setcookie('ordered', 'yep', time() + 86400, '/');
      header('Location: thank2.html');
      exit;
  }

  // Fallback: client will POST to GAS and we still keep the order
  $fd = json_encode($_POST, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
  $tg = ['token'=>$TELEGRAM_BOT_TOKEN,'chatId'=>$TELEGRAM_CHAT_ID,'text'=>$msg];
  $tgJson = json_encode($tg, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);

  echo <<<HTML
<!doctype html><meta charset="utf-8">
<title>Envoi de la commande…</title>
<p style="font-family:system-ui;margin:20px">
Envoi de la commande (mode secours)…<br>
Si cela prend plus de 3 secondes, votre connexion est peut-être lente.
</p>
<script>
(async () => {
try {
  const data = $fd;
  const form = new FormData();
  for (const [k,v] of Object.entries(data)) form.append(k, v);

  await fetch("$GAS_URL", {method: "POST", mode: "no-cors", body: form});

  const tg = $tgJson;
  if (tg.token && tg.chatId) {
    const u = "https://api.telegram.org/bot" + tg.token
            + "/sendMessage?chat_id=" + encodeURIComponent(tg.chatId)
            + "&parse_mode=HTML&disable_web_page_preview=1"
            + "&text=" + encodeURIComponent(tg.text);
    (new Image()).src = u;
  }

  document.cookie = "ordered=yep; max-age=86400; path=/";
  location.replace("thank2.html");
} catch(e){
  alert("Impossible d'envoyer la commande. Réessayez.");
  console.error(e);
  history.back();
}
})();
</script>
HTML;
  exit;
}

?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="icon" type="image/png" href="img/favicon.png" />
  <title>BALDMART EXPRESS</title>

  <link rel="stylesheet" href="css/bootstrap.min.css" />
  <link rel="stylesheet" href="css/style.css" />
  <script>var product_id = "tensiometre";</script>

  <style>
    :root { --accent:#fe4815; --bg:#f7f7fb; --text:#111; --muted:#666; --ok:#00bf2a; }
    body { background:#eef1f4; color:var(--text); }
    .p-main { padding: 10px 0 20px; }
    .rsi-embed .card{ background:#fff; border-radius:14px; box-shadow:0 10px 30px rgba(0,0,0,.06); padding:16px; border:1px solid #ecf0f6; }
    .rsi-embed h1{ margin:0 0 8px; font-size:22px; font-weight:800; text-align:center; }

    .rsi-embed ._rsi-quantity-offers{ display:grid; gap:12px; grid-template-columns:1fr; margin:18px 0 6px; }
    /* Make radios drive the selected style */
    .offers input[type="radio"]{ position:absolute; width:1px; height:1px; margin:-1px; padding:0; opacity:0; pointer-events:none; }
    .rsi-embed ._rsi-quantity-offers-offer-container{
      border:2px solid #e5e7eb; border-radius:12px; background:#fff; transition:.15s; cursor:pointer; padding:12px;
      display:block;
    }
    .rsi-embed ._rsi-quantity-offers-offer-container:hover{ transform:translateY(-2px); box-shadow:0 6px 20px rgba(0,0,0,.06); }
    /* Selected state purely via CSS sibling selector */
    .offers input[type="radio"]:checked + label._rsi-quantity-offers-offer-container{
      border-color:var(--accent)!important; background:#ededfb!important;
    }
    .rsi-embed ._rsi-quantity-offers-offer{ display:flex; align-items:center; justify-content:space-between; gap:12px; }
    .rsi-embed ._rsi-quantity-offers-title{ font-weight:800; }
    .rsi-embed ._rsi-quantity-offers-plaque{ display:inline-block; padding:4px 8px; border-radius:999px; font-size:12px; font-weight:800; color:#fff; margin-top:6px; pointer-events:none; }
    .rsi-embed ._rsi-quantity-offers-prices{ text-align:right; }
    .rsi-embed ._rsi-quantity-offers-old-price{ color:#a1a1aa; text-decoration:line-through; font-size:13px; }
    .rsi-embed ._rsi-quantity-offers-new-price{ font-weight:900; font-size:18px; }

    /* Fields stacked vertically */
    .rsi-embed .grid-2{ display:grid; grid-template-columns:1fr; gap:12px; }
    .rsi-embed ._rsi-modal-fields-item{ margin:10px 0; }
    .rsi-embed ._rsi-modal-fields-item label{ display:block; font-size:13px; color:#555; margin-bottom:6px; }

    /* Inputs with icons */
    .rsi-field { position:relative; }
    .rsi-field input{
      width:100%; padding:12px 14px; padding-left:44px !important;
      border:1px solid #e5e7eb; border-radius:10px; outline:none; font-size:14px; transition:.15s border-color; background:#fff;
    }
    .rsi-field input:focus{ border-color:#9ca3af; }
    .rsi-icon{
      position:absolute; left:12px; top:50%; transform:translateY(-50%);
      width:28px; height:28px; display:flex; align-items:center; justify-content:center;
      border:1.5px solid #000; border-radius:8px; background:#fff;
    }
    .rsi-icon svg{ width:18px; height:18px; stroke:#000; fill:none; stroke-width:2; }

    .rsi-embed ._rsi-modal-submit-button{
      width:100%; margin-top:14px; padding:14px 18px; border:0; border-radius:12px; font-weight:800; font-size:16px; background:var(--accent); color:#fff; box-shadow:0 2px 7px rgba(0,0,0,.2); cursor:pointer;
    }
    .rsi-embed ._rsi-buy-now-button-subtitle{ display:block; font-weight:600; font-size:12px; opacity:.9; }

    .rsi-embed .badge-row{ margin-top:14px; background:#eef1f4; border-radius:14px; padding:10px 12px; }
    .rsi-embed .badge-row img{ display:block; width:100%; height:auto; border-radius:10px; }
    ._rsi-modal-required-label { color:#e11; margin-left:4px; font-weight:700; }

    /* Reviews tidy */
    .avis .row { align-items:flex-start; }
    .dv-avis{ background:#fff; border-radius:12px; box-shadow:0 2px 8px rgba(0,0,0,.08); padding:16px; height:auto; }
    .review-name{ margin:0 0 8px; font-weight:600; }
    .stars{ margin:6px 0 10px; line-height:1; }
    .spn-star{ font-size:22px; }
    .review-desc{ margin:0; }
    @media (max-width: 576px){ .dv-avis{ padding:14px; } }
  </style>
</head>
<body>
	<div class="row m-0 p-0">
		<div class="p-0 col-xl-4 offset-xl-4 col-lg-6 offset-lg-3 col-md-8 offset-md-2 col-sm-12 col-12">
      <div class="top-bar">Livraison gratuite en 30 minutes ⏱️ : BALDMART EXPRESS 🚚 change les règles du jeu 🧩 !</div>
      <div class="header" style="display:flex;justify-content:space-between;align-items:center;padding:10px 6px;">
        <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 50 50"><path d="M 3 9 A 1.0001 1.0001 0 1 0 3 11 L 47 11 A 1.0001 1.0001 0 1 0 47 9 L 3 9 z M 3 24 A 1.0001 1.0001 0 1 0 3 26 L 47 26 A 1.0001 1.0001 0 1 0 47 24 L 3 24 z M 3 39 A 1.0001 1.0001 0 1 0 3 41 L 47 41 A 1.0001 1.0001 0 1 0 47 39 L 3 39 z"></path></svg>
        <img src="img/logo.png" alt="BALDMART EXPRESS" style="height:30px">
        <svg fill="#000000" height="30" width="30" viewBox="0 0 483.1 483.1"><g><path d="M434.55,418.7l-27.8-313.3c-0.5-6.2-5.7-10.9-12-10.9h-58.6c-0.1-52.1-42.5-94.5-94.6-94.5s-94.5,42.4-94.6,94.5h-58.6 c-6.2,0-11.4,4.7-12,10.9l-27.8,313.3c0,0.4,0,0.7,0,1.1c0,34.9,32.1,63.3,71.5,63.3h243c39.4,0,71.5-28.4,71.5-63.3 C434.55,419.4,434.55,419.1,434.55,418.7z M241.55,24c38.9,0,70.5,31.6,70.6,70.5h-141.2C171.05,55.6,202.65,24,241.55,24z M363.05,459h-243c-26,0-47.2-17.3-47.5-38.8l26.8-301.7h47.6v42.1c0,6.6,5.4,12,12,12s12-5.4,12-12v-42.1h141.2v42.1 c0,6.6,5.4,12,12,12s12-5.4,12-12v-42.1h47.6l26.8,301.8C410.25,441.7,389.05,459,363.05,459z"></path></g></svg>
			</div>
		</div>
	</div>

	<div class="container">
		<div class="row">
			<div class="p-0 col-xl-4 offset-xl-4 col-lg-6 offset-lg-3 col-md-8 offset-md-2 col-sm-12 col-12">
				<div class="p-main">
					<img width="100%" class="main-img" src="img/tensionmetre1.webp" id="show-img" onclick="scrollToForm()" alt="Produit">

          <!-- ======================= CHECKOUT ======================= -->
          <div class="dv_checkout" id="orderFormContainer">
            <div class="rsi-embed">
              <div class="card">
                <h1>Choisissez votre offre</h1>

                <form id="_rsi-cod-form-modal-form" method="POST" action="">
                  <!-- Hidden fields sent to the Sheet -->
                  <input type="hidden" name="Product"      value="Tensiomètre">
                  <input type="hidden" name="Offer"        id="offer-hidden"     value="1">
                  <input type="hidden" name="Price"        id="price-hidden"     value="350000">
                  <input type="hidden" name="OldPrice"     id="oldprice-hidden"  value="0">
                  <input type="hidden" name="SKU"          value="COD17300">
                  <input type="hidden" name="ProductLabel" value="Tensiomètre Automatique – Surveillance Facile et Précise">
                  <input type="hidden" name="Country" value="GN">


                  <!-- Offers (radios drive selection) -->
                  <div class="_rsi-quantity-offers offers" role="radiogroup" aria-label="Offres">
                    <!-- Offer 1 -->
                    <input type="radio" name="offerChoice" id="offer1" value="1" data-price="350000" data-old="0" checked>
                    <label class="_rsi-quantity-offers-offer-container" for="offer1">
                      <div class="_rsi-quantity-offers-offer">
                        <div class="_rsi-quantity-offers-info">
                          <div class="_rsi-quantity-offers-title">Achetez 1</div>
                          <div class="_rsi-quantity-offers-plaque" style="background:#ed1515;">-50% Réduction</div>
                        </div>
                        <div class="_rsi-quantity-offers-prices">
                          <div class="_rsi-quantity-offers-new-price">350 000 GNF</div>
                        </div>
                      </div>
                    </label>

                    <!-- Offer 2 -->
                    <input type="radio" name="offerChoice" id="offer2" value="2" data-price="490000" data-old="890000">
                    <label class="_rsi-quantity-offers-offer-container" for="offer2">
                      <div class="_rsi-quantity-offers-offer">
                        <div class="_rsi-quantity-offers-info">
                          <div class="_rsi-quantity-offers-title">Achetez 2</div>
                          <div class="_rsi-quantity-offers-plaque" style="background:var(--ok);">Offre Populaire</div>
                        </div>
                        <div class="_rsi-quantity-offers-prices">
                          <div class="_rsi-quantity-offers-old-price">890 000 GNF</div>
                          <div class="_rsi-quantity-offers-new-price">490 000 GNF</div>
                        </div>
                      </div>
                    </label>

                    <!-- Offer 3 -->
                    <input type="radio" name="offerChoice" id="offer3" value="3" data-price="590000" data-old="990000">
                    <label class="_rsi-quantity-offers-offer-container" for="offer3">
                      <div class="_rsi-quantity-offers-offer">
                        <div class="_rsi-quantity-offers-info">
                          <div class="_rsi-quantity-offers-title">Achetez 3</div>
                          <div class="_rsi-quantity-offers-plaque" style="background:linear-gradient(90deg, rgba(89,87,250,1) 0%, rgba(251,68,150,1) 100%);">Aujourd'hui seulement</div>
                        </div>
                        <div class="_rsi-quantity-offers-prices">
                          <div class="_rsi-quantity-offers-old-price">990 000 GNF</div>
                          <div class="_rsi-quantity-offers-new-price">590 000 GNF</div>
                        </div>
                      </div>
                    </label>
                  </div>

                  <!-- Section title -->
                  <div class="_rsi-build-block _rsi-build-block-custom-text" style="margin-top:10px;">
                    <div class="_rsi-custom-text-field" style="text-align:center;font-weight:700;font-size:18px;">
                      Insérez votre adresse de livraison
                    </div>
                  </div>

                  <!-- Fields (stacked) -->
                  <div class="grid-2">
                    <div class="_rsi-modal-fields-item">
                      <label>Prénom <span class="_rsi-modal-required-label">*</span></label>
                      <div class="rsi-field">
                        <span class="rsi-icon"><svg viewBox="0 0 24 24"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg></span>
                        <input type="text" name="Name" id="_rsi-field-first_name" placeholder="Nom Complet" required maxlength="250">
                      </div>
                    </div>

                    <div class="_rsi-modal-fields-item">
                      <label>Téléphone <span class="_rsi-modal-required-label">*</span></label>
                      <div class="rsi-field">
                        <span class="rsi-icon"><svg viewBox="0 0 24 24"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.08 4.18 2 2 0 0 1 4.06 2h3a2 2 0 0 1 2 1.72c.12.9.32 1.78.6 2.63a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.45-1.12a2 2 0 0 1 2.11-.45c.85.28 1.73.48 2.63.6A2 2 0 0 1 22 16.92z"/></svg></span>
                        <input type="tel" name="Phone" id="_rsi-field-phone" placeholder="Téléphone"
                               autocomplete="tel" inputmode="numeric" pattern="[0-9]*" maxlength="15" required
                               oninput="this.value=this.value.replace(/[^0-9]/g,'')">
                      </div>
                    </div>

                    <div class="_rsi-modal-fields-item">
                      <label>Adresse / Ville <span class="_rsi-modal-required-label">*</span></label>
                      <div class="rsi-field">
                        <span class="rsi-icon"><svg viewBox="0 0 24 24"><path d="M21 10c0 6-9 12-9 12s-9-6-9-12a9 9 0 1 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg></span>
                        <input type="text" name="Address" id="_rsi-field-city" placeholder="Adresse (Quartier)" required maxlength="250">
                      </div>
                    </div>
                  </div>

                  <button type="submit" class="_rsi-modal-submit-button _rsi-buy-now-button _rsi-buy-now-button-with-subtitle" id="btn-buy">
                    <span>Confirmer ma Commande<span class="_rsi-buy-now-button-subtitle">Livraison Gratuite</span></span>
                  </button>

                  <div class="badge-row">
                    <img src="img/client_sati.png" alt="+20 000 Clients · Livraison Gratuite · Paiement à la Livraison">
                  </div>
                </form>
              </div>
            </div>
          </div>
          <!-- ===================== /CHECKOUT ===================== -->

          <!-- Content below unchanged -->
          <div class="blog mt-4">
            <h5 class="bold text-center">Tensiomètre Automatique – Surveillance Facile et Précise 🩺📊</h5>
            <p class="text-center">Prenez soin de votre santé avec ce tensiomètre numérique précis et facile à utiliser. Parfait pour un suivi quotidien de la pression artérielle et du rythme cardiaque à domicile !</p>
            <img src="img/tensionmetre2.webp" class="m-auto d-table" width="100%" onclick="scrollToForm()" alt="photo">
            <p class="text-center"> Pourquoi l’adopter ?
                         Haute précision
                        Mesure fiable avec méthode oscillométrique, affichage numérique clair et précision de.
                         Grande capacité de stockage
                        Jusqu’à 99 mesures enregistrées pour 2 utilisateurs, idéal pour un suivi détaillé.</p>
						<img src="img/tensionmetre3.webp" class="m-auto d-table" width="100%"onclick="scrollToForm()">
						<p class="text-center"> Utilisation simple et intuitive
                         Grand écran LCD pour une lecture facile des données
                         Bouton unique pour démarrer la mesure en toute simplicité
                         Extinction automatique après 1 minute d’inactivité
                         Double alimentation
                         Fonctionne avec 4 piles AAA (non incluses)
                         Compatible avec une alimentation USB (câble non inclus)</p>
						<img src="img/tensionmetre4.webp" class="m-auto d-table" width="100%"onclick="scrollToForm()">
						<p class="text-center"> Adapté aux seniors
                        Conçu pour être pratique et accessible à tous, notamment aux personnes âgées.

                         Caractéristiques techniques :
                        Méthode de mesure : Oscillométrique
                         Plage de mesure :
                        • Pression : 0 – 280 mmHg
                        • Pouls : 40 – 195 battements/min
                         Alimentation : 4 x Piles AAA (non incluses) ou port USB DC 6V
                        Taille : 115mm x 96mm x 59mm
                         Stockage : 99 mesures pour 2 utilisateurs
                         Écran LCD clair et rétroéclairé</p>
						<img src="img/tensionmetre5.webp" class="m-auto d-table" width="100%"onclick="scrollToForm()">
						<p class="text-center">Contenu du pack :
                        x Tensiomètre numérique
                        x Brassard ajustable
                        x Manuel d’utilisation</p>
            <img src="img/tensionmetre6.webp" class="m-auto d-table" width="100%" onclick="scrollToForm()" alt="photo">
            <h5 class="bold text-center mt-2">BALDMART EXPRESS</h5>
            <p class="text-center">📦 BALDMART EXPRESS | Livraison Rapide à Conakry

              💰 Garantie Satisfait ou Remboursé
              Si le produit ne vous convient pas, aucun souci. Il suffit de nous envoyer un message WhatsApp au +224 624 69 57 14 pour demander un remplacement ou un remboursement. C’est simple et sans risque.

              ✉️ Service Client Réactif
              Notre équipe est disponible pour répondre à toutes vos questions dans un délai de 24h, du lundi au samedi.

              💳 Paiement à la Livraison
              Commandez en toute confiance et payez seulement à la réception.

              🚚 Livraison en 24 à 48H
              Nous livrons rapidement à domicile partout à Conakry. Les délais peuvent varier légèrement selon la ville ou les jours fériés.</p>
            <button onclick="scrollToForm()" class="btn m-auto text-white d-table bold btn-sticky">ACHETER MAINTENENT</button>
          </div>

          <div class="avis mt-4">
            <div class="row">
              <h5 class="bold text-center">Avis Client</h5>
              <div class="col-6">
                <div class="dv-avis">
                  <h6 class="review-name">🗣️ Oularé (Conakry)</h6>
                  <div class="stars"><span class="spn-star">★</span><span class="spn-star">★</span><span class="spn-star">★</span><span class="spn-star">★</span><span class="spn-star">★</span></div>
                  <p class="review-desc">Très bon appareil, facile à utiliser même pour les personnes âgées. La livraison a été rapide. Je recommande !</p>
                </div>
              </div>
              <div class="col-6">
                <div class="dv-avis">
                  <h6 class="review-name">🗣️ Mamadou Camara (Matoto)</h6>
                  <div class="stars"><span class="spn-star">★</span><span class="spn-star">★</span><span class="spn-star">★</span><span class="spn-star">★</span><span class="spn-star">★</span></div>
                  <p class="review-desc">Merci pour ce tensiomètre. Ma mère l’utilise tous les jours. L’écran est bien lisible et les mesures sont fiables.</p>
                </div>
              </div>
              <div class="col-6">
                <div class="dv-avis">
                  <h6 class="review-name">🗣️ Cissé Kabinet (Hamdallay)</h6>
                  <div class="stars"><span class="spn-star">★</span><span class="spn-star">★</span><span class="spn-star">★</span><span class="spn-star">★</span><span class="spn-star">★</span></div>
                  <p class="review-desc">J’ai comparé les mesures avec celles d’un hôpital, c’est vraiment précis. Très satisfait du produit.</p>
                </div>
              </div>
              <div class="col-6">
                <div class="dv-avis">
                  <h6 class="review-name">🗣️ Kourouma Aboubacar (Kankan)</h6>
                  <div class="stars"><span class="spn-star">★</span><span class="spn-star">★</span><span class="spn-star">★</span><span class="spn-star">★</span><span class="spn-star">★</span></div>
                  <p class="review-desc">Je pensais que ce serait compliqué à utiliser, mais pas du tout. En quelques secondes, j’ai ma tension. Bravo !</p>
                </div>
              </div>
            </div>
          </div>

          <div class="accordion mt-4 mb-4">
            <h5 class="bold text-center">Quelques questions de nos clients 👇</h5>
            <div class="accordion-item">
              <h2 id="accordion-button-1" aria-expanded="false"><span class="accordion-title">Quand vais-je recevoir le produit ?</span><span class="icon" aria-hidden="true"></span></h2>
              <div class="accordion-content"><p>Une fois le produit commandé, nous vous contacterons pour confirmer la commande et les informations d'expédition, et vous recevrez le produit dans les 24 ou 48 heures.</p></div>
            </div>
            <div class="accordion-item">
              <h2 id="accordion-button-2" aria-expanded="false"><span class="accordion-title">Acceptez-vous le paiement à la livraison ?</span><span class="icon" aria-hidden="true"></span></h2>
              <div class="accordion-content"><p>Oui, vous ne paierez rien tant que vous n’aurez pas reçu le produit et que vous ne l’aurez pas inspecté vous-même.</p></div>
            </div>
            <div class="accordion-item">
              <h2 id="accordion-button-3" aria-expanded="false"><span class="accordion-title">Puis-je retourner le produit s'il ne me plaît pas ?</span><span class="icon" aria-hidden="true"></span></h2>
              <div class="accordion-content"><p>Oui, vous pouvez retourner le produit à l'entreprise s'il ne vous plaît pas, à condition que son contenu ne soit pas détruit.</p></div>
            </div>
            <div class="accordion-item">
              <h2 id="accordion-button-4" aria-expanded="false"><span class="accordion-title">Y a-t-il une garantie sur le produit ?</span><span class="icon" aria-hidden="true"></span></h2>
              <div class="accordion-content"><p>Oui, nous offrons à tous nos clients une garantie de 14 jours sur le produit. </p></div>
            </div>
          </div>

          <footer>© 2025 BALDMART EXPRESS. Tous droits réservés.</footer>

          <!-- Sticky Button -->
          <div id="div-sticky" class="hidden">
            <button onclick="scrollToForm()" class="btn btn-primary m-auto text-white d-table bold btn-sticky btn-animation">
              Commander maintenant
            </button>
          </div>

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

	<script src="js/jquery.min.js"></script>
	<script src="js/main.js"></script>

  <script>
  // Smooth scroll to form
  function scrollToForm(){
    const el = document.getElementById('_rsi-cod-form-modal-form');
    if (el) el.scrollIntoView({behavior:'smooth', block:'start'});
  }

  // Map offers for hidden fields (qty, total price, old price)
  const OFFERS = {
    "1": { qty: 1, price: 350000, old: 0 },
    "2": { qty: 2, price: 490000, old: 890000 },
    "3": { qty: 3, price: 590000, old: 990000 }
  };

  function updateHidden(val){
    const o = OFFERS[val];
    if(!o) return;
    document.getElementById('offer-hidden').value    = o.qty;
    document.getElementById('price-hidden').value    = o.price;
    document.getElementById('oldprice-hidden').value = o.old || 0;
  }

  // Bind radio changes
  document.querySelectorAll('input[name="offerChoice"]').forEach(r => {
    r.addEventListener('change', e => updateHidden(e.target.value));
  });

  // Init hidden values on load
  (function initOffer(){
    const checked = document.querySelector('input[name="offerChoice"]:checked');
    if (checked) updateHidden(checked.value);
  })();

  // Phone: allow digits only (keypress/paste/input)
  const phoneInput = document.getElementById('customer_phone');
  if (phoneInput){
    phoneInput.addEventListener('keypress', function (e) {
      if (!/[0-9]/.test(e.key)) e.preventDefault();
    });
    phoneInput.addEventListener('paste', function (e) {
      const pasted = (e.clipboardData || window.clipboardData).getData('text');
      if (!/^\d+$/.test(pasted)) e.preventDefault();
    });
    phoneInput.addEventListener('input', function () {
      this.value = this.value.replace(/\D/g, '');
    });
  }
  </script>
</body>
</html>
