#!/usr/bin/env php
<?php
include 'main.inc.php';

/**
 * CLI main logic
 */
$webhookUrl = null;
$deleteMode = false;
$listMode   = false;

// Parse arguments
foreach ($argv as $arg) {
    if (str_starts_with($arg, '--webhook=')) {
        $webhookUrl = substr($arg, 10);
    }
    if ($arg === '--delete') {
        $deleteMode = true;
    }
    if ($arg === '--list') {
        $listMode = true;
    }
}

// Help / usage
if (!$webhookUrl && !$listMode) {
    fwrite(STDERR, "Usage:\n");
    fwrite(STDERR, "  ./webhook-cli --webhook=https://yourdomain.com/webhook\n");
    fwrite(STDERR, "      Create the webhook if not already active.\n\n");
    fwrite(STDERR, "  ./webhook-cli --webhook=https://yourdomain.com/webhook --delete\n");
    fwrite(STDERR, "      Delete the active webhook for the specified URL (after confirmation).\n\n");
    fwrite(STDERR, "  ./webhook-cli --list\n");
    fwrite(STDERR, "      List all current webhook subscriptions and their status (no changes made).\n");
    exit(1);
}

// Get access token
$accessToken = getAccessTokenFromAssertion(CLIENT_ID, ASSERTION);
if (!$accessToken) {
    die("Failed to obtain access token.\n");
}

// --list mode
if ($listMode) {
    $subs = listZettleWebhookSubscriptions($accessToken, ORG_UUID);
    if (!$subs) {
        echo "No subscriptions found.\n";
        exit;
    }
    echo "Current webhook subscriptions:\n\n";
    foreach ($subs as $sub) {
        printf(
            "- %s → %s [%s]\n",
            implode(', ', $sub['eventNames']),
            $sub['destination'],
            $sub['status']
        );
    }
    echo "\n(No changes made)\n";
    exit;
}

// --delete mode
if ($deleteMode) {
    deleteZettleWebhookSubscription($accessToken, ORG_UUID, $webhookUrl);
    exit;
}

// Default: check and create if missing
$list = listZettleWebhookSubscriptions($accessToken, ORG_UUID);
if (!$list) {
    echo "Unable to retrieve existing webhook subscriptions.\n";
    $register = readline("Do you want to create a new subscription? (y/n): ");
    if (strtolower($register) === 'y') {
        $result = createZettleWebhookSubscription($accessToken, ORG_UUID, $webhookUrl, CONTACT_EMAIL);
        echo "Subscription created:\n";
        print_r($result);
    }
    exit;
}

// Look for existing active subscription
$activeSub = null;
foreach ($list as $sub) {
    if (
        $sub['transportName'] === 'WEBHOOK' &&
        in_array('PurchaseCreated', $sub['eventNames']) &&
        $sub['destination'] === $webhookUrl &&
        $sub['status'] === 'ACTIVE'
    ) {
        $activeSub = $sub;
        break;
    }
}

if ($activeSub) {
    echo "Webhook subscription is already active:\n";
    print_r($activeSub);
    exit;
}

// No active or valid subscription found
echo "No active webhook subscription found or status invalid.\n";
$register = readline("Do you want to create a new one? (y/n): ");

if (strtolower($register) === 'y') {
    $result = createZettleWebhookSubscription($accessToken, ORG_UUID, $webhookUrl, CONTACT_EMAIL);
    echo "Subscription created:\n";
    print_r($result);
} else {
    echo "No changes made.\n";
}
