<?php include __DIR__ . '/includes/auth_guard.php'; ?>
<?php 
// Header brings in functions.php + json_utils.php + $db + branding vars ($superusername/$superpassword)
include __DIR__ . '/includes/header.php';

// --- Gate: allow superadmin OR admin ---
if (
    !in_array($_SESSION['name'] ?? '', [$superusername, 'admin']) &&
    (($_SESSION['passwordxyz'] ?? null) !== $superpassword)
) {
    // No header() redirects here (header.php already printed). Use JS for safety.
    echo "<script>location.href='index.php';</script>";
    include __DIR__ . '/includes/footer.php';
    echo '</body></html>';
    exit;
}

// Ensure helpers exist
if (!function_exists('captcha_get') || !function_exists('captcha_save')) {
    echo '<div class="container-fluid pt-4 px-4">
            <div class="row g-4">
              <div class="col-12">
                <div class="bg-secondary rounded h-100 p-4">
                  <div class="alert alert-danger mb-0">
                    Captcha helpers are missing. Make sure <code>includes/functions.php</code> 
                    and <code>includes/table.php</code> include <code>captcha_settings</code>, 
                    <code>captcha_get()</code>, and <code>captcha_save()</code>.
                  </div>
                </div>
              </div>
            </div>
          </div>';
    include __DIR__ . '/includes/footer.php';
    echo '</body></html>';
    exit;
}

// Load current config (auto-seeds id=1 if missing)
$cfg   = captcha_get($db);           // ['enabled'=>0|1, 'site_key'=>..., 'secret_key'=>...]
$saved = false; 
$error = '';

// Handle form submit — NO header() redirects; we render inline messages
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_captcha'])) {
    // Treat checkbox as 1/0
    $wantEnabled = !empty($_POST['enabled']) ? 1 : 0;

    // Transition logic:
    // - If turning OFF (was on, now off): wipe keys + disable
    // - If turning ON (was off, now on): require keys; save + enable
    // - If staying ON: allow toggling only; no need to show fields or change keys
    // - If staying OFF: keep off; keys are irrelevant/empty

    $wasEnabled = !empty($cfg['enabled']);

    if ($wasEnabled && !$wantEnabled) {
        // DISABLE: wipe keys
        if (captcha_save($db, 0, '', '')) {
            $saved = true;
            $cfg = captcha_get($db);
        } else {
            $error = 'Failed to disable and clear keys.';
        }
    } elseif (!$wasEnabled && $wantEnabled) {
        // ENABLE: require keys now
        $siteKey   = trim((string)($_POST['site_key'] ?? ''));
        $secretKey = trim((string)($_POST['secret_key'] ?? ''));
        if ($siteKey === '' || $secretKey === '') {
            $error = 'When enabling reCAPTCHA, both Site Key and Secret Key are required.';
        } else {
            if (captcha_save($db, 1, $siteKey, $secretKey)) {
                $saved = true;
                $cfg = captcha_get($db);
            } else {
                $error = 'Failed to save keys.';
            }
        }
    } else {
        // No state change in enabled flag
        // If staying OFF, optional: allow saving empty keys (keep off)
        if (!$wasEnabled && !$wantEnabled) {
            // Normalize to off + empty keys
            if (captcha_save($db, 0, '', '')) {
                $saved = true;
                $cfg = captcha_get($db);
            } else {
                $error = 'Could not save current settings.';
            }
        } else {
            // Staying ON — do nothing (keys remain as-is and hidden)
            $saved = true;
            // Refresh settings in case other fields are added later
            $cfg = captcha_get($db);
        }
    }
}

// View logic: when enabled -> hide keys; when disabled -> show empty inputs
$enabled = !empty($cfg['enabled']);
?>
<!-- Content -->
<div class="container-fluid pt-4 px-4">
  <div class="row g-4">
    <div class="col-12">
      <div class="bg-secondary rounded h-100 p-4">
        <h2 class="mb-4">Captcha Settings</h2>

        <?php if ($saved && !$error): ?>
          <div class="alert alert-success">Settings saved.</div>
        <?php endif; ?>
        <?php if (!empty($error)): ?>
          <div class="alert alert-danger"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
        <?php endif; ?>

        <form method="post" autocomplete="off">
          <!-- Better aligned switch -->
          <div class="form-check form-switch d-flex align-items-center gap-2 mb-3">
            <input class="form-check-input me-2" type="checkbox" id="enabled" name="enabled" <?= $enabled ? 'checked' : '' ?>>
            <label class="form-check-label mb-0" for="enabled">Enable reCAPTCHA on Login Page</label>
          </div>

          <?php if ($enabled): ?>
            <!-- ENABLED: hide keys completely -->
            <div class="alert alert-info" role="alert">
              reCAPTCHA is <strong>enabled</strong>. Keys are saved and <strong>hidden</strong>.
              To change keys, turn this off and Save, then re-enable with new keys.
            </div>

            <!-- Masked, disabled placeholders (no real values rendered) -->
            <div class="mb-3">
              <label class="form-label">Site Key</label>
              <input type="text" class="form-control" value="••••••••••••••••" disabled>
            </div>

            <div class="mb-3">
              <label class="form-label">Secret Key</label>
              <input type="password" class="form-control" value="••••••••••••••••" disabled>
            </div>
          <?php else: ?>
            <!-- DISABLED: show empty inputs to enter keys if enabling -->
            <div class="mb-3">
              <label class="form-label">Site Key</label>
              <input type="text"
                     class="form-control"
                     name="site_key"
                     value=""
                     placeholder="e.g. 6Lcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                     autocomplete="off">
            </div>

            <div class="mb-3">
              <label class="form-label">Secret Key</label>
              <input type="password"
                     class="form-control"
                     name="secret_key"
                     value=""
                     placeholder="e.g. 6Lcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                     autocomplete="new-password">
            </div>
          <?php endif; ?>

          <button type="submit" name="save_captcha" class="btn btn-warning">Save</button>

          <hr class="border-secondary my-4">

          <p class="mb-2">
            <strong>Notes:</strong><br>
            • Use <em>Google reCAPTCHA v2 (“I’m not a robot”)</em> for the login page.<br>
            • Once enabled here, the captcha widget will appear on the <strong>login page</strong> and be verified server-side.<br>
            • To generate your keys, <a href="https://www.google.com/recaptcha/admin/create" target="_blank" rel="noopener">click here</a>.<br>
            • If you run into a blank page, ensure PHP cURL is installed or the code falls back to <code>file_get_contents</code>.
          </p>
        </form>
      </div>
    </div>
  </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
</body>
</html>
