<?php

declare(strict_types=1);

require dirname(__DIR__) . '/autoload.php';

use PhpWA\Client;
use PhpWA\Config\ClientOptions;

$workDirectory = getenv('PHPWA_WORK_DIR') ?: '';
$accountId = getenv('PHPWA_ACCOUNT_ID') ?: '';
$encodedKey = getenv('PHPWA_STORAGE_KEY_BASE64') ?: '';
$storageKey = base64_decode($encodedKey, true);
if ($workDirectory === '' || $accountId === '' || !is_string($storageKey) || strlen($storageKey) !== 32) {
    throw new RuntimeException('Set PHPWA_WORK_DIR, PHPWA_ACCOUNT_ID and a 32-byte PHPWA_STORAGE_KEY_BASE64.');
}

$client = new Client(new ClientOptions($accountId, $workDirectory, $storageKey));
$phone = getenv('PHPWA_PAIR_PHONE') ?: '';
$pairingRequested = false;
$client->onQr(static function (array $codes, Client $client) use ($phone, &$pairingRequested): void {
    if ($phone !== '' && !$pairingRequested) {
        $pairingRequested = true;
        $request = $client->requestPairingCode($phone);
        fwrite(STDOUT, 'Enter this one-time linking code in WhatsApp: ' . $request->code() . PHP_EOL);
        return;
    }
    fwrite(STDOUT, 'A fresh QR login secret is available; publish it through your protected admin UI.' . PHP_EOL);
     
     
});
$client->onSessionEvent(static function ($event): void {
    fwrite(STDOUT, 'Session state: ' . $event->type() . PHP_EOL);
});
$client->runFor(25.0, 500);
