<?php
declare(strict_types=1);

function db(): PDO {
  $cfg = require __DIR__ . '/../config.php';
  $pdo = new PDO('sqlite:' . $cfg['db_path']);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $pdo->exec("
    CREATE TABLE IF NOT EXISTS orders (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      email TEXT,
      amount_cents INTEGER NOT NULL,
      currency TEXT NOT NULL,
      tenant_ref TEXT NOT NULL UNIQUE,
      checkout_id TEXT,
      payment_id TEXT,
      status TEXT NOT NULL DEFAULT 'created',
      created_at TEXT NOT NULL
    );
    CREATE TABLE IF NOT EXISTS tenants (
      tenant_ref TEXT PRIMARY KEY,
      license_key TEXT NOT NULL UNIQUE,
      status TEXT NOT NULL DEFAULT 'active',
      created_at TEXT NOT NULL
    );
  ");
  return $pdo;
}

function rand_token(int $len=32): string {
  return bin2hex(random_bytes(intdiv($len,2)));
}
