<?php

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

$conn = ensure_db(true);
$code = 'ACC-20260619';
$codeEsc = $conn->real_escape_string($code);
$rs = $conn->query("SELECT id FROM agents WHERE code='{$codeEsc}' AND archived_at IS NULL LIMIT 1");
if (!$rs || !$rs->num_rows) {
  fwrite(STDERR, "Acceptance agent {$code} was not found.\n");
  exit(1);
}
$agentId = (int)$rs->fetch_assoc()['id'];

$operations = [
  [
    'direction'=>'DEBIT',
    'entry_type'=>'ADMIN_ADJUSTMENT',
    'amount'=>1000,
    'idempotency_key'=>'LIVE_ACCEPTANCE:DEBIT:20260619',
    'source_type'=>'acceptance_test',
    'source_id'=>'ACC-DEBIT-20260619',
    'description'=>'تسوية مدينة فعلية لاختبار قبول وحدة المعتمدين',
  ],
  [
    'direction'=>'CREDIT',
    'entry_type'=>'AGENT_RECEIPT',
    'amount'=>250,
    'idempotency_key'=>'LIVE_ACCEPTANCE:RECEIPT:20260619',
    'source_type'=>'receipt',
    'source_id'=>'ACC-RECEIPT-20260619',
    'description'=>'قبض فعلي لاختبار قبول وحدة المعتمدين',
  ],
  [
    'direction'=>'CREDIT',
    'entry_type'=>'ADMIN_ADJUSTMENT',
    'amount'=>50,
    'idempotency_key'=>'LIVE_ACCEPTANCE:CREDIT:20260619',
    'source_type'=>'acceptance_test',
    'source_id'=>'ACC-CREDIT-20260619',
    'description'=>'تسوية دائنة فعلية لاختبار قبول وحدة المعتمدين',
  ],
];

$results = [];
foreach ($operations as $operation) {
  $result = ua_agent_ledger_post($conn, ['agent_id'=>$agentId] + $operation);
  if (!$result['ok']) {
    fwrite(STDERR, $result['error'] . PHP_EOL);
    exit(1);
  }
  $results[] = [
    'type'=>$operation['entry_type'],
    'direction'=>$operation['direction'],
    'amount'=>$operation['amount'],
    'duplicate'=>!empty($result['duplicate']),
  ];
  ua_agent_activity_add($conn, [
    'event_uuid'=>substr(hash('sha256', $operation['idempotency_key']), 0, 8) . '-0000-4000-8000-' . substr(hash('sha256', $operation['idempotency_key']), 8, 12),
    'agent_id'=>$agentId,
    'event_type'=>'LIVE_ACCEPTANCE_OPERATION',
    'direction'=>'LOCAL',
    'entity_type'=>'ledger_entry',
    'entity_id'=>$operation['source_id'],
    'request_id'=>$operation['idempotency_key'],
    'summary'=>$operation['description'],
    'payload'=>['direction'=>$operation['direction'],'amount'=>$operation['amount']],
    'actor_type'=>'admin',
    'actor_id'=>1,
  ]);
}

$balance = ua_agent_ledger_balance($conn, $agentId);
$acceptanceBalanceRs = $conn->query("SELECT COALESCE(SUM(CASE WHEN direction='DEBIT' THEN amount WHEN direction='CREDIT' THEN -amount ELSE 0 END),0) balance FROM agent_ledger_entries WHERE agent_id={$agentId} AND idempotency_key LIKE 'LIVE_ACCEPTANCE:%' AND status IN ('POSTED','REVERSED')");
$acceptanceBalance = (float)$acceptanceBalanceRs->fetch_assoc()['balance'];
$ledgerRs = $conn->query("SELECT COUNT(*) c FROM agent_ledger_entries WHERE agent_id={$agentId} AND idempotency_key LIKE 'LIVE_ACCEPTANCE:%'");
$activityRs = $conn->query("SELECT COUNT(*) c FROM agent_activity_log WHERE agent_id={$agentId} AND event_type='LIVE_ACCEPTANCE_OPERATION'");
echo json_encode([
  'ok'=>abs($acceptanceBalance - 700.0) < 0.001,
  'agent_id'=>$agentId,
  'agent_code'=>$code,
  'operations'=>$results,
  'balance'=>$balance,
  'acceptance_operations_balance'=>$acceptanceBalance,
  'ledger_entries'=>(int)$ledgerRs->fetch_assoc()['c'],
  'activity_entries'=>(int)$activityRs->fetch_assoc()['c'],
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . PHP_EOL;
exit(abs($acceptanceBalance - 700.0) < 0.001 ? 0 : 1);
