<?php

require_once dirname(__DIR__) . '/db_bootstrap.php';
require_once dirname(__DIR__) . '/agent_service.php';

$conn = ensure_db(true);
$key = 'CRUD-' . bin2hex(random_bytes(5));
$conn->begin_transaction();
try {
  $created = ua_agent_service_save($conn, [
    'code'=>$key,
    'full_name'=>'CRUD Test Agent',
    'username'=>strtolower($key),
    'password'=>'test-password',
    'pin'=>'4321',
    'phone'=>'000000',
    'is_active'=>1,
    'portal_enabled'=>1,
    'pos_enabled'=>1,
  ], ['type'=>'admin','id'=>1]);
  if (!$created['ok']) throw new RuntimeException($created['error']);
  $agentId = (int)$created['id'];
  $agent = ua_agent_repo_get($conn, $agentId);
  if (!$agent || !password_verify('test-password', (string)$agent['password_hash']) || !password_verify('4321', (string)$agent['pin_hash'])) {
    throw new RuntimeException('Create or credential hashing failed.');
  }

  $updated = ua_agent_service_save($conn, [
    'id'=>$agentId,
    'code'=>$key,
    'full_name'=>'CRUD Test Agent Updated',
    'username'=>strtolower($key),
    'phone'=>'111111',
    'is_active'=>1,
    'portal_enabled'=>1,
    'pos_enabled'=>0,
  ], ['type'=>'admin','id'=>1]);
  if (!$updated['ok']) throw new RuntimeException($updated['error']);
  $agent = ua_agent_repo_get($conn, $agentId);
  if (($agent['full_name'] ?? '') !== 'CRUD Test Agent Updated' || ($agent['phone'] ?? '') !== '111111' || (int)$agent['pos_enabled'] !== 0) {
    throw new RuntimeException('Update failed.');
  }

  if (!ua_agent_repo_archive($conn, $agentId, 1)) throw new RuntimeException('Archive failed.');
  if (ua_agent_repo_get($conn, $agentId) !== null || ua_agent_repo_get($conn, $agentId, true) === null) {
    throw new RuntimeException('Archived visibility contract failed.');
  }

  $conn->rollback();
  $escaped = $conn->real_escape_string($key);
  $left = $conn->query("SELECT COUNT(*) c FROM agents WHERE code='{$escaped}'")->fetch_assoc();
  if ((int)$left['c'] !== 0) throw new RuntimeException('Rollback left CRUD test data.');
  echo json_encode([
    'ok'=>true,
    'created'=>true,
    'credentials_hashed'=>true,
    'updated'=>true,
    'archived_without_delete'=>true,
    'rows_after_rollback'=>0,
  ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . PHP_EOL;
} catch (Throwable $e) {
  @$conn->rollback();
  fwrite(STDERR, $e->getMessage() . PHP_EOL);
  exit(1);
}
