<?php
// =============================================================================
// cron/addaplaylist_register.php — register THIS panel with addaplaylist.com.
//
// Usage (CLI only, run once per customer panel):
//   ADDAPLAYLIST_REGISTER_SECRET=<shared secret>  \
//   php cron/addaplaylist_register.php
//
// Optional env (sensible defaults inferred from PANEL_BASE_URL / host):
//   PANEL_DOMAIN=<host-and-optional-subpath>   default: from $_SERVER if missing
//   PANEL_ENDPOINT=<file.php>                  default: api/addaplaylist.php
//   ADDAPLAYLIST_BASE=<base url>               default: https://addaplaylist.com
//
// On success: writes config.addaplaylist_panel_code + addaplaylist_auth_token
// in this panel's panel.db so the QR rewrite + endpoint auth go live.
//
// Re-running is safe — addaplaylist's /api/panel/register issues a NEW
// panel_code + auth_token on every call. The previous code stops working,
// but no devices are affected (the device QR is fetched lazily from qr.php
// every time, so it picks up the new code on next render). Don't re-run
// casually in production — there's a small window where an in-flight
// scan against the old code will 404.
// =============================================================================

if (PHP_SAPI !== 'cli') {
    fwrite(STDERR, "this script is CLI-only\n"); exit(2);
}

require_once __DIR__ . '/../includes/db.php';

$secret    = getenv('ADDAPLAYLIST_REGISTER_SECRET');
$base      = rtrim((string)(getenv('ADDAPLAYLIST_BASE') ?: 'https://addaplaylist.com'), '/');
$endpoint  = (string)(getenv('PANEL_ENDPOINT') ?: 'api/addaplaylist.php');
$domain    = (string)getenv('PANEL_DOMAIN');

if ($secret === '' || $secret === false) {
    fwrite(STDERR, "ADDAPLAYLIST_REGISTER_SECRET env required\n"); exit(2);
}

// Auto-detect the panel's public-facing domain+subpath from the live config
// if the operator didn't pass one. Falls back to a panel_base_url stored at
// provision time (config.panel_base_url), then hard-fails.
if ($domain === '') {
    $cfg = db_one('SELECT panel_base_url FROM config WHERE id = 1');
    $base_url = trim((string)($cfg['panel_base_url'] ?? ''));
    if ($base_url !== '') {
        $parts = parse_url($base_url);
        if (is_array($parts) && !empty($parts['host'])) {
            $domain = $parts['host'] . (isset($parts['path']) ? rtrim($parts['path'], '/') : '');
        }
    }
}
if ($domain === '') {
    fwrite(STDERR, "PANEL_DOMAIN env required (or set config.panel_base_url first)\n");
    exit(2);
}

// addaplaylist's /api/panel/register expects: domain + endpoint_path + register_secret
$payload = json_encode([
    'domain'          => $domain,
    'endpoint_path'   => $endpoint,
    'register_secret' => $secret,
]);

$ch = curl_init($base . '/api/panel/register');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $payload,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT        => 15,
]);
$body = curl_exec($ch);
$code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err  = curl_error($ch);
curl_close($ch);

if ($code !== 200) {
    fwrite(STDERR, "register HTTP $code: " . ($body ?: $err) . "\n");
    exit(1);
}
$resp = json_decode((string)$body, true);
if (!is_array($resp) || empty($resp['panel_code']) || empty($resp['auth_token'])) {
    fwrite(STDERR, "register: unexpected response: " . $body . "\n");
    exit(1);
}

$panel_code = (string)$resp['panel_code'];
$auth_token = (string)$resp['auth_token'];

db_exec(
    'UPDATE config SET addaplaylist_panel_code = ?, addaplaylist_auth_token = ?, updated_at = ? WHERE id = 1',
    [$panel_code, $auth_token, time()]
);

fwrite(STDOUT, "registered with addaplaylist:\n");
fwrite(STDOUT, "  panel_code: $panel_code\n");
fwrite(STDOUT, "  auth_token: " . substr($auth_token, 0, 12) . "… (" . strlen($auth_token) . " chars)\n");
fwrite(STDOUT, "  domain:     $domain\n");
fwrite(STDOUT, "  endpoint:   $endpoint\n");
fwrite(STDOUT, "  → QR will now route to {$base}/{$panel_code}?code=<device_key>\n");
exit(0);
