<?php
// Shared helpers for agent/delegate interfaces.

require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db_schema_helpers.php';
require_once __DIR__ . '/agent_service.php';

if (!function_exists('ua_agent_ensure_tables')) {
  function ua_agent_ensure_tables(mysqli $conn): void {
    ua_agent_schema_migrate($conn);
  }
}

if (!function_exists('ua_agent_get')) {
  function ua_agent_get(mysqli $conn, int $agentId): ?array {
    return ua_agent_repo_get($conn, $agentId);
  }
}

if (!function_exists('ua_agent_password_ok')) {
  function ua_agent_password_ok(array $agent, string $password, bool $allowPinFallback = false): bool {
    $password = trim($password);
    if ($password === '') return false;

    $hash = (string)($agent['password_hash'] ?? '');
    if ($hash !== '' && password_verify($password, $hash)) return true;

    if ($allowPinFallback) {
      $pinHash = (string)($agent['pin_hash'] ?? '');
      if ($pinHash !== '' && password_verify($password, $pinHash)) return true;
    }

    return false;
  }
}

if (!function_exists('ua_agent_tx_add')) {
  function ua_agent_tx_add(mysqli $conn, int $agentId, string $type, float $amount = 0, string $note = ''): void {
    if ($amount == 0.0) {
      ua_agent_activity_add($conn, [
        'agent_id'=>$agentId,
        'event_type'=>strtoupper(substr($type, 0, 60)),
        'summary'=>$note,
      ]);
      return;
    }
    ua_agent_ledger_post($conn, [
      'agent_id'=>$agentId,
      'direction'=>$amount >= 0 ? 'DEBIT' : 'CREDIT',
      'entry_type'=>strtoupper(substr($type, 0, 50)),
      'amount'=>abs($amount),
      'idempotency_key'=>'LEGACY_TX:' . ua_agent_uuid(),
      'description'=>$note,
      'source_type'=>'legacy_agent_tx',
    ]);
  }
}

if (!function_exists('ua_agent_add_due_balance')) {
  function ua_agent_add_due_balance(mysqli $conn, int $agentId, float $amount): bool {
    $result = ua_agent_ledger_post($conn, [
      'agent_id'=>$agentId,
      'direction'=>$amount >= 0 ? 'DEBIT' : 'CREDIT',
      'entry_type'=>'LEGACY_DUE_BALANCE',
      'amount'=>abs($amount),
      'idempotency_key'=>'LEGACY_DUE:' . ua_agent_uuid(),
      'description'=>'Legacy due balance compatibility entry',
      'source_type'=>'legacy_balance',
    ]);
    return !empty($result['ok']);
  }
}

if (!function_exists('ua_agent_invoice_is_paid')) {
  function ua_agent_invoice_is_paid(array $invoice): bool {
    $status = trim((string)($invoice['status'] ?? ''));
    $paymentStatus = strtolower(trim((string)($invoice['payment_status'] ?? '')));
    return $status === 'مدفوع' || in_array($paymentStatus, ['paid', 'settled'], true);
  }
}

if (!function_exists('ua_agent_money')) {
  function ua_agent_money($value): string {
    return number_format((float)$value, 2);
  }
}
