<?php
// Page de gestion du captcha Google pour l'admin
$current_page = 'captcha-admin';
$page_title = 'Gestion du Captcha Google';
ob_start();
?>
<div class="container-xxl flex-grow-1 container-p-y">
  <div class="row justify-content-center">
    <div class="col-lg-8">
      <div class="card shadow-sm">
        <div class="card-header bg-primary text-white">
          <h2 class="mb-0"><i class="fa fa-shield-alt me-2"></i> Gestion du Captcha Google</h2>
        </div>
        <div class="card-body">
          <form method="post" action="captcha-admin.php">
            <div class="mb-3">
              <label for="target_page" class="form-label">Page cible (ex: contact.php)</label>
              <input type="text" class="form-control" id="target_page" name="target_page" required>
            </div>
            <div class="mb-3">
              <label for="captcha_version" class="form-label">Version du Captcha Google</label>
              <select class="form-select" id="captcha_version" name="captcha_version" required>
                <option value="v2">reCAPTCHA v2</option>
                <option value="v3">reCAPTCHA v3</option>
              </select>
            </div>
            <div class="mb-3">
              <label for="site_key" class="form-label">Site Key</label>
              <input type="text" class="form-control" id="site_key" name="site_key" required>
            </div>
            <div class="mb-3">
              <label for="secret_key" class="form-label">Secret Key</label>
              <input type="text" class="form-control" id="secret_key" name="secret_key" required>
            </div>
            <button type="submit" class="btn btn-primary">Insérer le Captcha</button>
          </form>
          <?php
          // Traitement du formulaire
          if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['target_page'], $_POST['captcha_version'], $_POST['site_key'], $_POST['secret_key'])) {
            $target = trim($_POST['target_page']);
            $version = $_POST['captcha_version'];
            $siteKey = trim($_POST['site_key']);
            $secretKey = trim($_POST['secret_key']);
            $captchaCode = '';
            if ($version === 'v2') {
              $captchaCode = "<div class='g-recaptcha' data-sitekey='$siteKey'></div>\n<script src='https://www.google.com/recaptcha/api.js'></script>";
            } else {
              $captchaCode = "<script src='https://www.google.com/recaptcha/api.js?render=$siteKey'></script>\n<script>grecaptcha.ready(function() { grecaptcha.execute('$siteKey', {action: 'submit'}).then(function(token) { document.getElementById('g-recaptcha-response').value = token; }); });</script>\n<input type='hidden' id='g-recaptcha-response' name='g-recaptcha-response'>";
            }
            // Insérer le captcha dans la page cible (avant </form>)
            $filePath = '../' . $target;
            if (file_exists($filePath)) {
              $content = file_get_contents($filePath);
              // Supprimer l'ancien code captcha (v2/v3)
              // Supprime div.g-recaptcha
              $content = preg_replace("#<div[^>]*class=['\"]g-recaptcha['\"][^>]*>.*?</div>\s*<script[^>]*src=['\"]https://www\.google\.com/recaptcha/api\.js[^>]*></script>#is", '', $content);
              // Supprime script reCAPTCHA v3 et input hidden
              $content = preg_replace("#<script[^>]*src=['\"]https://www\.google\.com/recaptcha/api\.js\?render=[^'\"]+['\"][^>]*></script>.*?<script>grecaptcha\.ready\(function\(\)\s*\{.*?grecaptcha\.execute\(.*?\);.*?document\.getElementById\('g-recaptcha-response'\)\.value\s*=\s*token;.*?\}\);\s*\}\);</script>\s*<input[^>]*id=['\"]g-recaptcha-response['\"][^>]*>#is", '', $content);
              // Supprime input hidden g-recaptcha-response seul
              $content = preg_replace("#<input[^>]*id=['\"]g-recaptcha-response['\"][^>]*>#is", '', $content);
              if (strpos($content, '</form>') !== false) {
                $newContent = str_replace('</form>', "$captchaCode\n</form>", $content);
                file_put_contents($filePath, $newContent);
                echo "<div class='alert alert-success mt-4'>Captcha insérée (ancienne supprimée) dans <strong>$target</strong>.</div>";
              } else {
                echo "<div class='alert alert-danger mt-4'>Aucun formulaire &lt;form&gt; trouvé dans la page cible.</div>";
              }
            } else {
              echo "<div class='alert alert-danger mt-4'>Page cible introuvable.</div>";
            }
          }
          ?>
        </div>
      </div>
    </div>
  </div>
</div>
<?php
$page_content = ob_get_clean();
include 'template.php';
?>
