<?php
declare(strict_types=1);

require_once __DIR__ . '/../lib/db.php';
require_once __DIR__ . '/../lib/consent.php';
require_once __DIR__ . '/../lib/iys.php';

if (php_sapi_name() !== 'cli') {
  http_response_code(403);
  echo "CLI only\n";
  exit(1);
}

$args = $argv ?? [];
array_shift($args); // script name

if (count($args) === 0) {
  echo "Kullanim: php scripts/iys-register.php <numara> [onayli|onaysiz|1|2] [--force]\n";
  exit(1);
}

$phone = trim((string)($args[0] ?? ''));
$statusRaw = strtolower(trim((string)($args[1] ?? 'onayli')));
$force = in_array('--force', $args, true);
$configOverrides = [];

foreach ($args as $arg) {
  if (str_starts_with($arg, '--username=')) {
    $configOverrides['username'] = trim((string)substr($arg, 11));
    continue;
  }
  if (str_starts_with($arg, '--password=')) {
    $configOverrides['password'] = trim((string)substr($arg, 11));
    continue;
  }
  if (str_starts_with($arg, '--brand=')) {
    $configOverrides['brand_code'] = trim((string)substr($arg, 8));
    continue;
  }
  if (str_starts_with($arg, '--brand_code=')) {
    $configOverrides['brand_code'] = trim((string)substr($arg, 13));
    continue;
  }
}

$status = 'onayli';
if (in_array($statusRaw, ['onaysiz', 'rejected', 'ret'], true)) {
  $status = 'onaysiz';
} elseif ($statusRaw === consent_digit_rejected()) {
  $status = 'onaysiz';
} elseif ($statusRaw === consent_digit_approved()) {
  $status = 'onayli';
}

try {
  $pdo = db();
  $result = iys_sync_phone($pdo, $phone, $status, [
    'source' => 'cli_iys_register',
    'event_ref' => 'manual_' . date('Ymd_His'),
    'force' => $force,
    'config' => $configOverrides,
  ]);

  echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
  exit(!empty($result['ok']) ? 0 : 1);
} catch (Throwable $e) {
  $direct = iys_send_single($phone, $status, '', $configOverrides);
  $direct['db_error'] = $e->getMessage();
  $direct['db_mode'] = 'direct_send_without_state';
  echo json_encode($direct, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
  exit(!empty($direct['ok']) ? 0 : 1);
}
