<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/lib/tenant.php';
require_once dirname(__DIR__) . '/lib/payments.php';
require_once dirname(__DIR__) . '/lib/admin_layout.php';

require_admin();
$tenantId = current_tenant_id();
$flash = '';
$error = '';
$s = payment_settings($tenantId);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $keep = static function (string $posted, ?string $existing): ?string {
            $posted = trim($posted);
            if ($posted === '' || str_contains($posted, '•')) {
                return $existing;
            }
            return $posted;
        };

        db()->prepare(
            'INSERT INTO payment_settings (
                tenant_id, mode, enable_stripe, enable_paypal, enable_venmo, enable_square, enable_ach, enable_pay_at_shop,
                stripe_publishable_key, stripe_secret_key, stripe_webhook_secret,
                paypal_client_id, paypal_client_secret, paypal_webhook_id,
                square_application_id, square_access_token, square_location_id,
                default_currency, booking_payments, retail_payments
             ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
             ON DUPLICATE KEY UPDATE
                mode=VALUES(mode), enable_stripe=VALUES(enable_stripe), enable_paypal=VALUES(enable_paypal),
                enable_venmo=VALUES(enable_venmo), enable_square=VALUES(enable_square), enable_ach=VALUES(enable_ach),
                enable_pay_at_shop=VALUES(enable_pay_at_shop),
                stripe_publishable_key=VALUES(stripe_publishable_key), stripe_secret_key=VALUES(stripe_secret_key),
                stripe_webhook_secret=VALUES(stripe_webhook_secret),
                paypal_client_id=VALUES(paypal_client_id), paypal_client_secret=VALUES(paypal_client_secret),
                paypal_webhook_id=VALUES(paypal_webhook_id),
                square_application_id=VALUES(square_application_id), square_access_token=VALUES(square_access_token),
                square_location_id=VALUES(square_location_id),
                default_currency=VALUES(default_currency), booking_payments=VALUES(booking_payments),
                retail_payments=VALUES(retail_payments)'
        )->execute([
            $tenantId,
            ($_POST['mode'] ?? 'test') === 'live' ? 'live' : 'test',
            isset($_POST['enable_stripe']) ? 1 : 0,
            isset($_POST['enable_paypal']) ? 1 : 0,
            isset($_POST['enable_venmo']) ? 1 : 0,
            isset($_POST['enable_square']) ? 1 : 0,
            isset($_POST['enable_ach']) ? 1 : 0,
            isset($_POST['enable_pay_at_shop']) ? 1 : 0,
            trim((string) ($_POST['stripe_publishable_key'] ?? '')) ?: null,
            $keep((string) ($_POST['stripe_secret_key'] ?? ''), $s['stripe_secret_key'] ?? null),
            $keep((string) ($_POST['stripe_webhook_secret'] ?? ''), $s['stripe_webhook_secret'] ?? null),
            trim((string) ($_POST['paypal_client_id'] ?? '')) ?: null,
            $keep((string) ($_POST['paypal_client_secret'] ?? ''), $s['paypal_client_secret'] ?? null),
            trim((string) ($_POST['paypal_webhook_id'] ?? '')) ?: null,
            trim((string) ($_POST['square_application_id'] ?? '')) ?: null,
            $keep((string) ($_POST['square_access_token'] ?? ''), $s['square_access_token'] ?? null),
            trim((string) ($_POST['square_location_id'] ?? '')) ?: null,
            strtoupper(substr(trim((string) ($_POST['default_currency'] ?? 'USD')), 0, 3)),
            in_array($_POST['booking_payments'] ?? '', ['off', 'deposit', 'full', 'optional'], true)
                ? $_POST['booking_payments'] : 'off',
            in_array($_POST['retail_payments'] ?? '', ['off', 'online', 'optional'], true)
                ? $_POST['retail_payments'] : 'optional',
        ]);
        $flash = 'Payment settings saved. Priority: Stripe + PayPal/Venmo live; Square stub until needed.';
        $s = payment_settings($tenantId);
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

admin_header('Payments', 'payments');
if ($flash): ?><div class="flash"><?= htmlspecialchars($flash) ?></div><?php endif; ?>
<?php if ($error): ?><div class="flash err"><?= htmlspecialchars($error) ?></div><?php endif; ?>

<div class="panel">
  <h2>Provider priority</h2>
  <p class="muted" style="margin:0">
    <strong>B</strong> Stripe + PayPal/Venmo (now) →
    <strong>A</strong> Stripe core / ACH →
    <strong>C</strong> Square later.
    Cards never touch our database — only provider payment IDs are stored.
  </p>
</div>

<form method="post">
  <div class="panel">
    <h2>Modes</h2>
    <div class="grid-2">
      <div>
        <label>Environment</label>
        <select name="mode">
          <option value="test" <?= ($s['mode'] ?? '') === 'test' ? 'selected' : '' ?>>Test / sandbox</option>
          <option value="live" <?= ($s['mode'] ?? '') === 'live' ? 'selected' : '' ?>>Live</option>
        </select>
        <label>Currency</label>
        <input type="text" name="default_currency" maxlength="3" value="<?= htmlspecialchars((string) ($s['default_currency'] ?? 'USD')) ?>">
        <label>Retail checkout</label>
        <select name="retail_payments">
          <option value="optional" <?= ($s['retail_payments'] ?? '') === 'optional' ? 'selected' : '' ?>>Online or pay at shop</option>
          <option value="online" <?= ($s['retail_payments'] ?? '') === 'online' ? 'selected' : '' ?>>Online required</option>
          <option value="off" <?= ($s['retail_payments'] ?? '') === 'off' ? 'selected' : '' ?>>Pay at shop only</option>
        </select>
        <label>Booking payments</label>
        <select name="booking_payments">
          <option value="off" <?= ($s['booking_payments'] ?? '') === 'off' ? 'selected' : '' ?>>Off (pay at chair)</option>
          <option value="optional" <?= ($s['booking_payments'] ?? '') === 'optional' ? 'selected' : '' ?>>Optional online</option>
          <option value="deposit" <?= ($s['booking_payments'] ?? '') === 'deposit' ? 'selected' : '' ?>>Deposit required</option>
          <option value="full" <?= ($s['booking_payments'] ?? '') === 'full' ? 'selected' : '' ?>>Full prepay</option>
        </select>
      </div>
      <div>
        <label style="display:flex;gap:.5rem;align-items:center;color:var(--text)"><input type="checkbox" name="enable_stripe" <?= !empty($s['enable_stripe']) ? 'checked' : '' ?>> Enable Stripe (cards<?= !empty($s['enable_ach']) ? ' + ACH' : '' ?>)</label>
        <label style="display:flex;gap:.5rem;align-items:center;color:var(--text);margin-top:.5rem"><input type="checkbox" name="enable_ach" <?= !empty($s['enable_ach']) ? 'checked' : '' ?>> Stripe ACH / bank (when enabled on Stripe account)</label>
        <label style="display:flex;gap:.5rem;align-items:center;color:var(--text);margin-top:.5rem"><input type="checkbox" name="enable_paypal" <?= !empty($s['enable_paypal']) ? 'checked' : '' ?>> Enable PayPal</label>
        <label style="display:flex;gap:.5rem;align-items:center;color:var(--text);margin-top:.5rem"><input type="checkbox" name="enable_venmo" <?= !empty($s['enable_venmo']) ? 'checked' : '' ?>> Offer Venmo via PayPal (US)</label>
        <label style="display:flex;gap:.5rem;align-items:center;color:var(--text);margin-top:.5rem"><input type="checkbox" name="enable_square" <?= !empty($s['enable_square']) ? 'checked' : '' ?>> Enable Square (stub — priority C)</label>
        <label style="display:flex;gap:.5rem;align-items:center;color:var(--text);margin-top:.5rem"><input type="checkbox" name="enable_pay_at_shop" <?= !empty($s['enable_pay_at_shop']) ? 'checked' : '' ?>> Allow pay at shop</label>
      </div>
    </div>
  </div>

  <div class="grid-2">
    <div class="panel">
      <h2>Stripe</h2>
      <label>Publishable key</label>
      <input type="text" name="stripe_publishable_key" value="<?= htmlspecialchars((string) ($s['stripe_publishable_key'] ?? '')) ?>" placeholder="pk_test_…">
      <label>Secret key</label>
      <input type="password" name="stripe_secret_key" value="<?= htmlspecialchars(payment_mask_secret($s['stripe_secret_key'] ?? null)) ?>" placeholder="sk_test_…">
      <label>Webhook signing secret</label>
      <input type="password" name="stripe_webhook_secret" value="<?= htmlspecialchars(payment_mask_secret($s['stripe_webhook_secret'] ?? null)) ?>" placeholder="whsec_…">
      <p class="muted">Webhook URL: <code><?= APP_BASE ?>/api/payments/webhook.php?provider=stripe&amp;tenant=<?= htmlspecialchars(tenant_param()) ?></code></p>
    </div>
    <div class="panel">
      <h2>PayPal / Venmo</h2>
      <label>Client ID</label>
      <input type="text" name="paypal_client_id" value="<?= htmlspecialchars((string) ($s['paypal_client_id'] ?? '')) ?>">
      <label>Client secret</label>
      <input type="password" name="paypal_client_secret" value="<?= htmlspecialchars(payment_mask_secret($s['paypal_client_secret'] ?? null)) ?>">
      <label>Webhook ID (optional)</label>
      <input type="text" name="paypal_webhook_id" value="<?= htmlspecialchars((string) ($s['paypal_webhook_id'] ?? '')) ?>">
      <p class="muted">Use sandbox credentials while Environment = Test. Venmo shows in PayPal Checkout when enabled for the merchant.</p>
    </div>
  </div>

  <div class="panel">
    <h2>Square (later)</h2>
    <div class="grid-2">
      <div>
        <label>Application ID</label>
        <input type="text" name="square_application_id" value="<?= htmlspecialchars((string) ($s['square_application_id'] ?? '')) ?>">
        <label>Location ID</label>
        <input type="text" name="square_location_id" value="<?= htmlspecialchars((string) ($s['square_location_id'] ?? '')) ?>">
      </div>
      <div>
        <label>Access token</label>
        <input type="password" name="square_access_token" value="<?= htmlspecialchars(payment_mask_secret($s['square_access_token'] ?? null)) ?>">
        <p class="muted">Fields saved now; live Square Checkout is not wired until priority C.</p>
      </div>
    </div>
    <button class="btn" type="submit">Save payment settings</button>
  </div>
</form>

<?php
$recent = db()->prepare(
    'SELECT * FROM payments WHERE tenant_id = ? ORDER BY id DESC LIMIT 25'
);
$recent->execute([$tenantId]);
$payments = $recent->fetchAll();
?>
<div class="panel">
  <h2>Recent payments</h2>
  <?php if (!$payments): ?>
    <p class="muted">No payments yet.</p>
  <?php else: ?>
    <table class="table">
      <thead>
        <tr><th>ID</th><th>Provider</th><th>Purpose</th><th>Ref</th><th>Amount</th><th>Status</th><th></th></tr>
      </thead>
      <tbody>
        <?php foreach ($payments as $p): ?>
          <tr>
            <td>#<?= (int) $p['id'] ?></td>
            <td><?= htmlspecialchars((string) $p['provider']) ?></td>
            <td><?= htmlspecialchars((string) $p['purpose']) ?></td>
            <td><?= htmlspecialchars((string) $p['reference_type']) ?> #<?= (int) $p['reference_id'] ?></td>
            <td>$<?= number_format((float) $p['amount'], 2) ?></td>
            <td><?= htmlspecialchars((string) $p['status']) ?></td>
            <td>
              <?php if ($p['status'] === 'paid'): ?>
                <button type="button" class="btn small secondary refund-btn" data-id="<?= (int) $p['id'] ?>">Refund</button>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  <?php endif; ?>
</div>
<script>
document.querySelectorAll('.refund-btn').forEach(btn => {
  btn.addEventListener('click', async () => {
    if (!confirm('Refund this payment? Stripe refunds attempt via API when possible.')) return;
    const fd = new FormData();
    fd.append('action', 'refund_payment');
    fd.append('payment_id', btn.dataset.id);
    fd.append('note', 'Admin refund');
    try {
      await BarberAdmin.postForm(APP_BASE + '/api/bookings.php', fd);
      BarberAdmin.toast('Refund recorded');
      location.reload();
    } catch (e) { BarberAdmin.toast(e.message, true); }
  });
});
</script>
<?php admin_footer(); ?>
