<?php
require_once('../common.php');
require_once('checklogin.php');

// PayPal credentials are sensitive — administrators only.
if (!in_array($_SESSION['editor_type'] ?? '', ['admin', 'superadmin'], true)) {
    http_response_code(403);
    exit('Access denied. PayPal Settings is restricted to administrators.');
}
if (empty($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}

require_once('../paypal_rest.php');

function pp_get_all(PDO $pdo): array
{
    $out = [];
    foreach ($pdo->query("SELECT setting_key, setting_value FROM paypal_settings") as $r) {
        $out[$r['setting_key']] = $r['setting_value'];
    }
    return $out;
}
function pp_set(PDO $pdo, string $key, string $value): void
{
    $stmt = $pdo->prepare("INSERT INTO paypal_settings (setting_key, setting_value) VALUES (:k, :v)
                           ON DUPLICATE KEY UPDATE setting_value = :v2");
    $stmt->bindValue(':k', $key);
    $stmt->bindValue(':v', $value);
    $stmt->bindValue(':v2', $value);
    $stmt->execute();
}

$msg = '';
$error = '';

if (isset($_POST['save_paypal_settings'])) {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['token'], (string)$_POST['token'])) {
        $error = 'Invalid request. Please reload and try again.';
    } else {
        $env = ($_POST['environment'] ?? 'sandbox') === 'live' ? 'live' : 'sandbox';
        pp_set($pdo, 'environment', $env);
        pp_set($pdo, 'client_id', trim((string)($_POST['client_id'] ?? '')));
        $currency = strtoupper(preg_replace('/[^A-Za-z]/', '', (string)($_POST['currency'] ?? 'USD')));
        pp_set($pdo, 'currency', $currency !== '' ? $currency : 'USD');
        pp_set($pdo, 'enabled', isset($_POST['enabled']) ? '1' : '0');
        // Only overwrite the secret when a new value is actually entered.
        $new_secret = (string)($_POST['secret'] ?? '');
        if ($new_secret !== '') {
            pp_set($pdo, 'secret', trim($new_secret));
        }
        $msg = 'PayPal settings saved.';
    }
}

if (isset($_POST['test_paypal'])) {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['token'], (string)$_POST['token'])) {
        $error = 'Invalid request. Please reload and try again.';
    } else {
        // Fresh PDO read (settings may have just changed); pp_settings caches per request,
        // so run the test on a subsequent load if you just saved.
        try {
            $tok = pp_token($pdo);
            $msg = 'Success — connected to PayPal and obtained an access token. Credentials are valid.';
        } catch (Throwable $e) {
            error_log('paypal test: ' . $e->getMessage());
            $error = 'Connection failed: ' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
        }
    }
}

$s = pp_get_all($pdo);
$has_secret = !empty($s['secret']);

include_once('header.php');
include_once('editors-menu.php');
?>
<link rel="stylesheet" href="../styles.css">

<div class="container" style="max-width: 760px; padding: 30px 40px;">
    <h2>PayPal Settings</h2>
    <?php if ($msg): ?><p class="msg" style="color:#28a745;"><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?>
    <?php if ($error): ?><p class="error" style="color:#dc3545;"><?= $error /* already escaped where needed */ ?></p><?php endif; ?>

    <p style="color:#555; font-style:italic;">
        Contest entry fees come from each edition's fee. Enter your PayPal REST
        API credentials below (create them at developer.paypal.com → Apps &amp;
        Credentials). Test with <b>Sandbox</b> first, then switch to <b>Live</b>.
    </p>

    <form method="post">
        <input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8') ?>">
        <table class="gridtable" style="width:100%; border-collapse:collapse;">
            <tr>
                <th style="text-align:left; padding:10px;">Setting</th>
                <th style="text-align:left; padding:10px;">Value</th>
            </tr>
            <tr>
                <td style="padding:10px;">Environment</td>
                <td style="padding:10px;">
                    <select name="environment">
                        <option value="sandbox" <?= ($s['environment'] ?? 'sandbox') === 'sandbox' ? 'selected' : '' ?>>Sandbox (testing)</option>
                        <option value="live" <?= ($s['environment'] ?? '') === 'live' ? 'selected' : '' ?>>Live (real payments)</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td style="padding:10px;">Client ID</td>
                <td style="padding:10px;"><input type="text" name="client_id" style="width:100%;" value="<?= htmlspecialchars($s['client_id'] ?? '', ENT_QUOTES, 'UTF-8') ?>"></td>
            </tr>
            <tr>
                <td style="padding:10px;">Secret</td>
                <td style="padding:10px;">
                    <input type="password" name="secret" style="width:100%;" autocomplete="new-password" placeholder="<?= $has_secret ? '•••••••• (saved — leave blank to keep)' : 'paste your secret' ?>">
                </td>
            </tr>
            <tr>
                <td style="padding:10px;">Currency</td>
                <td style="padding:10px;"><input type="text" name="currency" size="6" maxlength="3" value="<?= htmlspecialchars($s['currency'] ?? 'USD', ENT_QUOTES, 'UTF-8') ?>"></td>
            </tr>
            <tr>
                <td style="padding:10px;">Enabled</td>
                <td style="padding:10px;">
                    <label><input type="checkbox" name="enabled" value="1" <?= ($s['enabled'] ?? '0') === '1' ? 'checked' : '' ?>> Accept PayPal payments for contest entries</label>
                </td>
            </tr>
        </table>
        <p style="margin-top:16px;">
            <input type="submit" name="save_paypal_settings" value="Save Settings" class="button-primary">
            <input type="submit" name="test_paypal" value="Test Connection" class="button-secondary" style="margin-left:10px;">
        </p>
        <p style="color:#777; font-size:13px;">
            Tip: save your credentials first, then click <b>Test Connection</b> to verify them against PayPal.
        </p>
    </form>
</div>

<?php
include_once('footer.php');
