<?php
declare(strict_types=1);

header('Content-Type: application/json');

$cfg = require __DIR__ . '/../config.php';

function respond(int $code, array $payload): void {
  http_response_code($code);
  echo json_encode($payload, JSON_UNESCAPED_SLASHES);
  exit;
}

function read_json_body(): array {
  $raw = file_get_contents('php://input') ?: '';
  $d = json_decode($raw, true);
  return is_array($d) ? $d : [];
}

function ensure_dir(string $dir, int $mode = 0750): void {
  if (is_dir($dir)) return;
  if (!@mkdir($dir, $mode, true)) {
    respond(500, ['ok' => false, 'error' => 'Failed to create tenants directory']);
  }
  @chmod($dir, $mode);
}

function write_json_atomic(string $path, array $data, int $mode = 0640): void {
  $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
  if ($json === false) respond(500, ['ok' => false, 'error' => 'JSON encode failed']);
  $tmp = $path . '.tmp';
  if (file_put_contents($tmp, $json, LOCK_EX) === false) {
    respond(500, ['ok' => false, 'error' => 'Failed to write JSON']);
  }
  @chmod($tmp, $mode);
  if (!@rename($tmp, $path)) {
    @unlink($tmp);
    respond(500, ['ok' => false, 'error' => 'Failed to finalize JSON']);
  }
}

function yoco_create_checkout(array $cfg, int $amountCents, string $currency, string $successUrl, string $cancelUrl, array $metadata): ?array {
  $base = rtrim((string)($cfg['yoco_api_base'] ?? 'https://payments.yoco.com/api'), '/');
  $key  = (string)($cfg['yoco_secret_key'] ?? '');
  if ($key === '') return null;

  $payload = [
    'amount' => $amountCents,
    'currency' => $currency,
    'successUrl' => $successUrl,
    'cancelUrl' => $cancelUrl,
    'metadata' => $metadata,
  ];

  $ch = curl_init($base . '/checkouts');
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
      "Authorization: Bearer {$key}",
      "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_TIMEOUT => 20,
  ]);

  $res  = curl_exec($ch);
  $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  $d = json_decode((string)$res, true);
  if ($code >= 200 && $code < 300 && is_array($d)) return $d;

  return null;
}

$body = read_json_body();

$email = trim((string)($body['email'] ?? ''));
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  respond(400, ['ok' => false, 'error' => 'Valid email required']);
}

$amountCents = $body['amount_cents'] ?? null;
if ($amountCents === null || $amountCents === '') {
  $amountCents = (int)($cfg['price_cents'] ?? 9900);
}
$amountCents = (int)$amountCents;

if ($amountCents < 100) {
  respond(400, ['ok' => false, 'error' => 'Invalid amount_cents']);
}

$currency = strtoupper(trim((string)($body['currency'] ?? 'ZAR')));
if (!preg_match('/^[A-Z]{3}$/', $currency)) {
  respond(400, ['ok' => false, 'error' => 'Invalid currency']);
}

$tenantsDir = rtrim((string)($cfg['tenants_dir'] ?? '/home/mytown/blog.mytown.ink/tenants'), '/');
ensure_dir($tenantsDir, 0750);

$tenantRef = 't_' . bin2hex(random_bytes(8));
$tenantDir = $tenantsDir . '/' . $tenantRef;

ensure_dir($tenantDir, 0750);
ensure_dir($tenantDir . '/data', 0750);

// IMPORTANT: successUrl must keep trailing slash for your /paid/ route
$appBase = rtrim((string)($cfg['app_base'] ?? 'https://blogger.mytown.ink'), '/');
$successUrl = $appBase . '/paid/?ref=' . rawurlencode($tenantRef);
$cancelUrl  = $appBase . '/';

$checkout = yoco_create_checkout($cfg, $amountCents, $currency, $successUrl, $cancelUrl, [
  'tenant_ref' => $tenantRef,
  'email' => $email,
]);

if (!$checkout) {
  $missing = ((string)($cfg['yoco_secret_key'] ?? '') === '') ? 'missing yoco_secret_key' : 'yoco create failed';
  respond(500, ['ok' => false, 'error' => 'Server misconfigured or payment provider error (' . $missing . ')']);
}

$checkoutId  = (string)($checkout['id'] ?? '');
$redirectUrl = (string)($checkout['redirectUrl'] ?? $checkout['redirect_url'] ?? '');

if ($checkoutId === '' || $redirectUrl === '') {
  respond(500, ['ok' => false, 'error' => 'Invalid checkout response']);
}

$pending = [
  'tenant_ref' => $tenantRef,
  'email' => $email,
  'checkoutId' => $checkoutId,
  'redirectUrl' => $redirectUrl,
  'status' => 'pending',
  'created_at' => date('c'),
  'amount_cents' => $amountCents,
  'currency' => $currency,
];

write_json_atomic($tenantDir . '/pending.json', $pending, 0640);

respond(200, [
  'ok' => true,
  'tenant_ref' => $tenantRef,
  'checkoutId' => $checkoutId,
  'redirectUrl' => $redirectUrl,
  'successUrl' => $successUrl,
]);
