<?php
/* ============================================================================
   WBMCZ ADMIN — PAYMENT GATEWAY SETTINGS
   ----------------------------------------------------------------------------
   The Razorpay Key ID and Key Secret used by every payment on the site live in
   the settings table. This page is the only place they can be changed.

   Two things guard them:

     1. Only an administrator holding "Manage Settings" can open the page.
     2. Saving asks for a separate pass key, on top of being logged in. So a
        borrowed laptop or a session left open is not enough to move the money
        to somebody else's account.

   The pass key itself is never stored as text — only a bcrypt hash of it, in
   the settings table. Nobody reading this file or the database can work out
   what it is. It can be changed from this page by whoever knows the current
   one.

   The Key Secret is shown masked, always. It is written, never read back.
   ============================================================================ */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/rbac.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }
rbac_guard('manage_settings');

$lang         = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id      = (int)$_SESSION['user_id'];
$company_name = getSetting('site_name', 'WBMCZ');

$me_row = $db->select("SELECT id, name FROM users WHERE id = ?", [$user_id]);
$ME     = !empty($me_row) ? $me_row[0] : ['id' => $user_id, 'name' => 'Admin'];

$flash_ok  = $_SESSION['flash_success'] ?? ''; unset($_SESSION['flash_success']);
$flash_err = $_SESSION['flash_error']   ?? ''; unset($_SESSION['flash_error']);

/* ---------------------------------------------------------------------------
   SCHEMA — built on demand, so the page works before any migration
   --------------------------------------------------------------------------- */
$conn = $db->getConnection();
try {
    $conn->query("CREATE TABLE IF NOT EXISTS gateway_log (
        id INT AUTO_INCREMENT PRIMARY KEY,
        action VARCHAR(40) NOT NULL,
        detail VARCHAR(500) NULL,
        actor_id INT NULL,
        actor_name VARCHAR(150) NULL,
        ip_address VARCHAR(45) NULL,
        created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
        KEY idx_gw_time (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
} catch (\Throwable $e) {}

/** Read / write one settings row. */
function pg_get($db, $key, $default = '') {
    try {
        $r = $db->select("SELECT setting_value FROM settings WHERE setting_key = ?", [$key]);
        return !empty($r) ? (string)$r[0]['setting_value'] : $default;
    } catch (\Throwable $e) { return $default; }
}
function pg_set($db, $key, $val) {
    try {
        $r = $db->select("SELECT id FROM settings WHERE setting_key = ?", [$key]);
        if (!empty($r)) { $db->insert("UPDATE settings SET setting_value = ? WHERE setting_key = ?", [$val, $key]); }
        else { $db->insert("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?)", [$key, $val]); }
        return true;
    } catch (\Throwable $e) { return false; }
}
function pg_ip() {
    foreach (['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'] as $k) {
        if (!empty($_SERVER[$k])) {
            $c = trim(explode(',', $_SERVER[$k])[0]);
            if (filter_var($c, FILTER_VALIDATE_IP)) return $c;
        }
    }
    return '0.0.0.0';
}
function pg_log($db, $action, $detail, $me) {
    try {
        $db->insert("INSERT INTO gateway_log (action, detail, actor_id, actor_name, ip_address) VALUES (?,?,?,?,?)",
            [substr($action, 0, 40), substr((string)$detail, 0, 500), (int)$me['id'], substr((string)$me['name'], 0, 150), pg_ip()]);
    } catch (\Throwable $e) {}
}

/* Show a secret without giving it away: rzp_live_••••••••1234 */
function pg_mask($v) {
    $v = (string)$v;
    $n = strlen($v);
    if ($n === 0) return '';
    if ($n <= 8)  return str_repeat('•', $n);
    return substr($v, 0, 4) . str_repeat('•', max(4, $n - 8)) . substr($v, -4);
}
/* rzp_live_… / rzp_test_… — the mode is readable from the Key ID itself */
function pg_mode($keyId) {
    $k = strtolower(trim((string)$keyId));
    if (strpos($k, 'rzp_live') === 0) return 'live';
    if (strpos($k, 'rzp_test') === 0) return 'test';
    return $k === '' ? 'none' : 'unknown';
}

/* ---------------------------------------------------------------------------
   THE PASS KEY
   ----------------------------------------------------------------------------
   Seeded once with the key the owner chose. Only its bcrypt hash is stored, so
   the plain words appear nowhere — not in this file, not in the database, not
   in a backup.
   --------------------------------------------------------------------------- */
const PG_PASS_SEED = '$2y$12$EUUFW2rHIPrq/Oq1lXLxBuTV3RZ1bErUrAVy9Tg9/mqbA3z5dB5Hm';

$pass_hash = pg_get($db, 'payment_pass_hash', '');
if ($pass_hash === '') { pg_set($db, 'payment_pass_hash', PG_PASS_SEED); $pass_hash = PG_PASS_SEED; }

/** Wrong guesses are counted, and after five the page stops listening for a while. */
function pg_locked() {
    $n    = (int)($_SESSION['pg_fail'] ?? 0);
    $till = (int)($_SESSION['pg_lock_till'] ?? 0);
    if ($till > time()) { return (int)ceil(($till - time()) / 60); }
    if ($till > 0 && $till <= time()) { unset($_SESSION['pg_fail'], $_SESSION['pg_lock_till']); }
    return 0;
}
function pg_fail() {
    $_SESSION['pg_fail'] = (int)($_SESSION['pg_fail'] ?? 0) + 1;
    if ($_SESSION['pg_fail'] >= 5) { $_SESSION['pg_lock_till'] = time() + 900; }   // 15 minutes
}
function pg_pass_ok($given, $hash) {
    $given = (string)$given;
    if ($given === '' || $hash === '') return false;
    return password_verify($given, $hash);
}

/* ---------------------------------------------------------------------------
   ACTIONS
   --------------------------------------------------------------------------- */
$test_result = $_SESSION['pg_test'] ?? null; unset($_SESSION['pg_test']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $locked = pg_locked();
    if ($locked > 0) {
        $_SESSION['flash_error'] = "Too many wrong pass keys. Try again in $locked minute(s).";
        redirect('payment_settings.php');
    }

    /* ---- save the gateway credentials ---- */
    if (isset($_POST['save_gateway'])) {
        if (!pg_pass_ok($_POST['pass_key'] ?? '', $pass_hash)) {
            pg_fail();
            pg_log($db, 'wrong_pass', 'A save was refused — wrong pass key', $ME);
            $_SESSION['flash_error'] = 'That pass key is not right. Nothing was changed.';
            redirect('payment_settings.php');
        }
        unset($_SESSION['pg_fail'], $_SESSION['pg_lock_till']);

        $old_id  = pg_get($db, 'razorpay_key_id', '');
        $old_sec = pg_get($db, 'razorpay_key_secret', '');

        $new_id  = trim((string)($_POST['key_id'] ?? ''));
        $new_sec = trim((string)($_POST['key_secret'] ?? ''));

        /* An empty secret box means "leave the one that is already saved" —
           so the field never has to be refilled just to correct the Key ID. */
        if ($new_sec === '') { $new_sec = $old_sec; }

        if ($new_id === '') {
            $_SESSION['flash_error'] = 'The Key ID cannot be empty.';
            redirect('payment_settings.php');
        }
        if ($new_sec === '') {
            $_SESSION['flash_error'] = 'There is no Key Secret saved yet, so one has to be entered.';
            redirect('payment_settings.php');
        }
        if (strlen($new_id) < 10 || preg_match('~\s~', $new_id)) {
            $_SESSION['flash_error'] = 'That does not look like a Razorpay Key ID. It normally starts with rzp_live_ or rzp_test_.';
            redirect('payment_settings.php');
        }

        /* Key ID and Secret must belong to the same mode, or every payment
           fails verification after the money has already left the customer. */
        $mode = pg_mode($new_id);
        if ($mode === 'unknown' && empty($_POST['force_mode'])) {
            $_SESSION['flash_error'] = 'That Key ID does not start with rzp_live_ or rzp_test_. Tick "save it anyway" if you are sure.';
            redirect('payment_settings.php');
        }

        $changed = [];
        if ($new_id !== $old_id)   { $changed[] = 'Key ID ' . pg_mask($old_id) . ' → ' . pg_mask($new_id); }
        if ($new_sec !== $old_sec) { $changed[] = 'Key Secret replaced'; }

        if (empty($changed)) {
            $_SESSION['flash_success'] = 'Nothing was different, so nothing was saved.';
            redirect('payment_settings.php');
        }

        pg_set($db, 'razorpay_key_id', $new_id);
        pg_set($db, 'razorpay_key_secret', $new_sec);
        pg_set($db, 'razorpay_mode', $mode);
        pg_log($db, 'keys_saved', implode(' · ', $changed) . ' · mode ' . $mode, $ME);

        $_SESSION['flash_success'] = 'Saved. The site is now using the ' . strtoupper($mode) . ' keys. Please run a test payment before you leave it.';
        redirect('payment_settings.php');
    }

    /* ---- change the pass key itself ---- */
    if (isset($_POST['change_pass'])) {
        if (!pg_pass_ok($_POST['old_pass'] ?? '', $pass_hash)) {
            pg_fail();
            pg_log($db, 'wrong_pass', 'A pass key change was refused', $ME);
            $_SESSION['flash_error'] = 'The current pass key is not right.';
            redirect('payment_settings.php');
        }
        unset($_SESSION['pg_fail'], $_SESSION['pg_lock_till']);

        $n1 = (string)($_POST['new_pass'] ?? '');
        $n2 = (string)($_POST['new_pass2'] ?? '');
        if (strlen($n1) < 8)      { $_SESSION['flash_error'] = 'The new pass key must be at least 8 characters.'; redirect('payment_settings.php'); }
        if ($n1 !== $n2)          { $_SESSION['flash_error'] = 'The two new pass keys do not match.'; redirect('payment_settings.php'); }

        pg_set($db, 'payment_pass_hash', password_hash($n1, PASSWORD_BCRYPT));
        pg_log($db, 'pass_changed', 'The pass key was changed', $ME);
        $_SESSION['flash_success'] = 'The pass key has been changed. Keep it somewhere safe — it cannot be read back from here.';
        redirect('payment_settings.php');
    }

    /* ---- ask Razorpay whether the saved credentials actually work ---- */
    if (isset($_POST['test_conn'])) {
        $id  = pg_get($db, 'razorpay_key_id', '');
        $sec = pg_get($db, 'razorpay_key_secret', '');
        if ($id === '' || $sec === '') {
            $_SESSION['pg_test'] = ['ok' => false, 'msg' => 'Nothing is saved yet, so there is nothing to test.'];
            redirect('payment_settings.php');
        }
        $code = 0; $body = ''; $err = '';
        if (function_exists('curl_init')) {
            $ch = curl_init('https://api.razorpay.com/v1/payments?count=1');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 20);
            curl_setopt($ch, CURLOPT_USERPWD, $id . ':' . $sec);
            $body = (string)curl_exec($ch);
            $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $err  = curl_error($ch);
            curl_close($ch);
        } else { $err = 'cURL is not available on this server.'; }

        if ($code === 200) {
            $_SESSION['pg_test'] = ['ok' => true, 'msg' => 'Razorpay accepted these credentials. Payments can be verified.'];
        } elseif ($code === 401) {
            $_SESSION['pg_test'] = ['ok' => false, 'msg' => 'Razorpay refused them (401). The Key ID and Key Secret do not match, or they are from different modes.'];
        } elseif ($code === 0) {
            /* Nothing came back at all — the server could not reach Razorpay.
               That says nothing about the keys, only about the connection. */
            $_SESSION['pg_test'] = ['ok' => false, 'msg' =>
                'Could not reach Razorpay from this server' . ($err ? ' (' . $err . ')' : '') .
                '. The keys may still be fine — this is a network or firewall problem, and payment verification will fail until it is sorted out.'];
        } else {
            $d = json_decode($body, true);
            $m = $d['error']['description'] ?? ($err ?: 'No reply from Razorpay.');
            $_SESSION['pg_test'] = ['ok' => false, 'msg' => 'Could not confirm (HTTP ' . $code . '): ' . $m];
        }
        pg_log($db, 'tested', ($_SESSION['pg_test']['ok'] ? 'passed' : 'failed') . ' — ' . $_SESSION['pg_test']['msg'], $ME);
        redirect('payment_settings.php');
    }
}

/* ---------------------------------------------------------------------------
   WHAT THE PAGE SHOWS
   --------------------------------------------------------------------------- */
$key_id  = pg_get($db, 'razorpay_key_id', '');
$key_sec = pg_get($db, 'razorpay_key_secret', '');
$mode    = pg_mode($key_id);
$locked  = pg_locked();

$log = [];
try { $log = $db->select("SELECT * FROM gateway_log ORDER BY id DESC LIMIT 25"); } catch (\Throwable $e) {}

function dt($s) { return $s ? date('d M Y, g:i A', strtotime($s)) : '—'; }
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Gateway - <?php echo htmlspecialchars($company_name); ?> Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <style>
        body { font-family:'Inter',sans-serif; }
        [x-cloak] { display:none !important; }
        .lbl { display:block; font-size:11px; font-weight:700; color:#475569; margin-bottom:5px; }
        .fld { width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:10px 12px; font-size:13px; background:#fff; }
        .fld:focus { outline:none; border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.15); }
        .fld.mono { font-family:ui-monospace,SFMono-Regular,Menlo,monospace; letter-spacing:.02em; }
        .card { background:#fff; border:1px solid #e5e7eb; border-radius:18px; }
        .pill { display:inline-flex; align-items:center; gap:6px; padding:4px 12px; border-radius:999px;
                font-size:11px; font-weight:800; text-transform:uppercase; letter-spacing:.05em; }
        .p-live { background:#ecfdf5; color:#047857; border:1px solid #a7f3d0; }
        .p-test { background:#fffbeb; color:#b45309; border:1px solid #fde68a; }
        .p-none { background:#fef2f2; color:#b91c1c; border:1px solid #fecaca; }
        .btn { display:inline-flex; align-items:center; justify-content:center; gap:8px; font-weight:700;
               border-radius:11px; padding:11px 18px; font-size:13px; }
        .btn-go { background:#4f46e5; color:#fff; } .btn-go:hover { background:#4338ca; }
        .btn-gh { background:#f1f5f9; color:#475569; } .btn-gh:hover { background:#e2e8f0; }
        .secretline { font-family:ui-monospace,SFMono-Regular,Menlo,monospace; font-size:14px; letter-spacing:.04em; }
    </style>
</head>
<body class="bg-gray-50" x-data="{ sidebarOpen: window.innerWidth >= 768, showPass: false, showSecret: false, changePass: false }" x-cloak>

<div class="flex h-screen overflow-hidden">
    <?php include __DIR__ . '/includes/sidebar.php'; ?>

    <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">

        <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40 relative flex-shrink-0">
            <div class="flex items-center min-w-0">
                <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-indigo-600 rounded-lg hover:bg-gray-100"><i class="fas fa-bars text-xl"></i></button>
                <div class="min-w-0">
                    <h2 class="text-xl font-bold truncate">Payment Gateway</h2>
                    <p class="text-[11px] text-slate-400 hidden sm:block">The Razorpay keys every payment on the site runs through</p>
                </div>
            </div>
            <span class="pill <?php echo $mode === 'live' ? 'p-live' : ($mode === 'test' ? 'p-test' : 'p-none'); ?>">
                <i class="fas <?php echo $mode === 'live' ? 'fa-circle-check' : ($mode === 'test' ? 'fa-flask' : 'fa-circle-exclamation'); ?>"></i>
                <?php echo $mode === 'none' ? 'Not set up' : $mode; ?> mode
            </span>
        </header>

        <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">
          <div class="max-w-3xl mx-auto space-y-5">

            <?php if ($flash_ok): ?>
                <div class="bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl text-sm"><i class="fas fa-check-circle mr-2"></i><?php echo htmlspecialchars($flash_ok); ?></div>
            <?php endif; ?>
            <?php if ($flash_err): ?>
                <div class="bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl text-sm"><i class="fas fa-circle-exclamation mr-2"></i><?php echo htmlspecialchars($flash_err); ?></div>
            <?php endif; ?>
            <?php if ($test_result): ?>
                <div class="<?php echo $test_result['ok'] ? 'bg-emerald-50 border-emerald-200 text-emerald-700' : 'bg-amber-50 border-amber-200 text-amber-800'; ?> border px-4 py-3 rounded-xl text-sm">
                    <i class="fas <?php echo $test_result['ok'] ? 'fa-plug-circle-check' : 'fa-plug-circle-xmark'; ?> mr-2"></i><?php echo htmlspecialchars($test_result['msg']); ?>
                </div>
            <?php endif; ?>
            <?php if ($locked > 0): ?>
                <div class="bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl text-sm">
                    <i class="fas fa-lock mr-2"></i>Too many wrong pass keys. Saving is closed for <?php echo $locked; ?> more minute(s).
                </div>
            <?php endif; ?>

            <!-- what is saved right now -->
            <div class="card p-5">
                <p class="text-[11px] font-extrabold uppercase tracking-wider text-slate-400 mb-3">Saved right now</p>
                <div class="space-y-2.5">
                    <div class="flex items-center justify-between gap-3 flex-wrap">
                        <span class="text-[13px] font-bold text-slate-600">Key ID</span>
                        <span class="secretline text-slate-800"><?php echo $key_id !== '' ? htmlspecialchars($key_id) : '<span class="text-rose-500 font-sans text-[13px]">not set</span>'; ?></span>
                    </div>
                    <div class="flex items-center justify-between gap-3 flex-wrap border-t border-slate-100 pt-2.5">
                        <span class="text-[13px] font-bold text-slate-600">Key Secret</span>
                        <span class="secretline text-slate-800"><?php echo $key_sec !== '' ? htmlspecialchars(pg_mask($key_sec)) : '<span class="text-rose-500 font-sans text-[13px]">not set</span>'; ?></span>
                    </div>
                </div>
                <p class="text-[11.5px] text-slate-400 mt-3 leading-relaxed">
                    The secret is only ever shown masked, here and everywhere else. It is written in, never read back out.
                </p>
                <form method="POST" class="mt-4">
                    <button name="test_conn" value="1" class="btn btn-gh"><i class="fas fa-plug"></i> Test these keys with Razorpay</button>
                </form>
            </div>

            <!-- change them -->
            <div class="card p-5">
                <p class="text-[11px] font-extrabold uppercase tracking-wider text-slate-400 mb-1">Change the keys</p>
                <p class="text-[12.5px] text-slate-500 mb-4">
                    From your Razorpay dashboard: <b>Settings → API Keys</b>. Live keys start with
                    <code class="bg-slate-100 px-1 rounded">rzp_live_</code>, test keys with
                    <code class="bg-slate-100 px-1 rounded">rzp_test_</code>. Both must come from the same mode.
                </p>

                <form method="POST" class="space-y-4" autocomplete="off"
                      onsubmit="return confirm('Change the payment gateway keys? Every payment on the site will use them from this moment.');">
                    <div>
                        <label class="lbl">Key ID</label>
                        <input name="key_id" class="fld mono" autocomplete="off" spellcheck="false"
                               value="<?php echo htmlspecialchars($key_id); ?>" placeholder="rzp_live_xxxxxxxxxxxx">
                    </div>

                    <div>
                        <label class="lbl">Key Secret</label>
                        <div class="relative">
                            <input name="key_secret" class="fld mono pr-11" autocomplete="new-password" spellcheck="false"
                                   :type="showSecret ? 'text' : 'password'"
                                   placeholder="<?php echo $key_sec !== '' ? 'leave blank to keep the one already saved' : 'paste the Key Secret'; ?>">
                            <button type="button" @click="showSecret = !showSecret"
                                    class="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-700">
                                <i class="fas" :class="showSecret ? 'fa-eye-slash' : 'fa-eye'"></i>
                            </button>
                        </div>
                        <?php if ($key_sec !== ''): ?>
                            <p class="text-[11.5px] text-slate-400 mt-1">Leave it blank if you only want to correct the Key ID — the saved secret stays as it is.</p>
                        <?php endif; ?>
                    </div>

                    <label class="flex items-start gap-2.5 text-[12px] text-slate-600 bg-slate-50 border border-slate-200 rounded-xl p-3 cursor-pointer">
                        <input type="checkbox" name="force_mode" value="1" class="mt-0.5 accent-indigo-600">
                        <span>Save it even though the Key ID does not start with <code>rzp_live_</code> or <code>rzp_test_</code>
                            <span class="block text-[11px] text-slate-400 mt-0.5">Only tick this if you are certain. A wrong key makes every payment fail after the customer has already paid.</span>
                        </span>
                    </label>

                    <!-- the pass key -->
                    <div class="rounded-xl border-2 border-indigo-200 bg-indigo-50/50 p-4">
                        <label class="lbl text-indigo-800"><i class="fas fa-key mr-1"></i> Pass key</label>
                        <div class="relative">
                            <input name="pass_key" class="fld pr-11" autocomplete="new-password" required
                                   :type="showPass ? 'text' : 'password'" placeholder="Enter the pass key to confirm">
                            <button type="button" @click="showPass = !showPass"
                                    class="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-700">
                                <i class="fas" :class="showPass ? 'fa-eye-slash' : 'fa-eye'"></i>
                            </button>
                        </div>
                        <p class="text-[11.5px] text-indigo-700/70 mt-1.5 leading-snug">
                            Being logged in is not enough to move the money to another account. Five wrong tries and this page stops listening for 15 minutes.
                        </p>
                    </div>

                    <button name="save_gateway" value="1" class="btn btn-go w-full" <?php echo $locked > 0 ? 'disabled style="opacity:.4;pointer-events:none"' : ''; ?>>
                        <i class="fas fa-floppy-disk"></i> Save the gateway keys
                    </button>
                </form>
            </div>

            <!-- change the pass key -->
            <div class="card p-5">
                <button type="button" @click="changePass = !changePass" class="w-full flex items-center justify-between">
                    <span class="text-[13px] font-bold text-slate-700"><i class="fas fa-user-lock mr-1.5 text-slate-400"></i> Change the pass key</span>
                    <i class="fas text-slate-400" :class="changePass ? 'fa-chevron-up' : 'fa-chevron-down'"></i>
                </button>
                <form method="POST" class="space-y-3 mt-4" x-show="changePass" x-cloak autocomplete="off">
                    <div>
                        <label class="lbl">Current pass key</label>
                        <input type="password" name="old_pass" class="fld" autocomplete="new-password" required>
                    </div>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <div>
                            <label class="lbl">New pass key</label>
                            <input type="password" name="new_pass" class="fld" autocomplete="new-password" minlength="8" required>
                        </div>
                        <div>
                            <label class="lbl">New pass key again</label>
                            <input type="password" name="new_pass2" class="fld" autocomplete="new-password" minlength="8" required>
                        </div>
                    </div>
                    <p class="text-[11.5px] text-slate-400">
                        At least 8 characters. Only a hash of it is stored, so it can never be read back &mdash; if it is
                        forgotten, it has to be reset from the database.
                    </p>
                    <button name="change_pass" value="1" class="btn btn-gh"><i class="fas fa-key"></i> Change it</button>
                </form>
            </div>

            <!-- who touched what -->
            <div class="card overflow-hidden">
                <div class="px-5 py-4 border-b border-gray-100">
                    <p class="text-[13px] font-bold text-slate-700">History</p>
                    <p class="text-[11.5px] text-slate-400">Every change, and every refused attempt.</p>
                </div>
                <div class="overflow-x-auto">
                <table class="w-full text-[12.5px]">
                    <thead><tr class="bg-slate-50 text-slate-500 text-[10.5px] font-extrabold uppercase tracking-wider">
                        <th class="text-left p-3">What</th><th class="text-left p-3">Detail</th>
                        <th class="text-left p-3">Who</th><th class="text-left p-3">When</th>
                    </tr></thead>
                    <tbody>
                    <?php if (empty($log)): ?>
                        <tr><td colspan="4" class="p-10 text-center text-slate-400">Nothing yet.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($log as $l):
                        $bad = in_array($l['action'], ['wrong_pass'], true); ?>
                        <tr class="border-t border-slate-100">
                            <td class="p-3">
                                <span class="pill <?php echo $bad ? 'p-none' : 'p-live'; ?>" style="text-transform:none">
                                    <?php echo htmlspecialchars(str_replace('_', ' ', $l['action'])); ?>
                                </span>
                            </td>
                            <td class="p-3 text-slate-600"><?php echo htmlspecialchars($l['detail']); ?></td>
                            <td class="p-3 text-slate-600">
                                <?php echo htmlspecialchars($l['actor_name'] ?: '—'); ?>
                                <span class="block text-[11px] text-slate-400"><?php echo htmlspecialchars($l['ip_address']); ?></span>
                            </td>
                            <td class="p-3 text-slate-500 whitespace-nowrap"><?php echo dt($l['created_at']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
                </div>
            </div>

            <p class="text-[11.5px] text-slate-400 leading-relaxed">
                Everything on this page is read by <code>getSetting('razorpay_key_id')</code> and
                <code>getSetting('razorpay_key_secret')</code>, which is what <code>category.php</code>,
                <code>checkout.php</code>, <code>product.php</code>, <code>order.php</code>, <code>wallet.php</code>,
                <code>subscription.php</code> and the seller dashboard all use. A change here reaches every one of them
                straight away &mdash; no file edit, nothing to clear.
            </p>

          </div>
        </main>
    </div>
</div>
</body>
</html>
