<?php

require_once __DIR__ . '/agent_repository.php';
require_once __DIR__ . '/agent_ledger_lib.php';
require_once __DIR__ . '/agent_activity_lib.php';
require_once __DIR__ . '/agent_sync_lib.php';

if (!function_exists('ua_agent_service_save')) {
  function ua_agent_service_save(mysqli $conn, array $data, array $actor = []): array {
    $actorId = (int)($actor['id'] ?? 0);
    $result = ua_agent_repo_save($conn, $data, $actorId);
    ua_agent_activity_add($conn, [
      'agent_id'=>$result['id'] ?? ($data['id'] ?? null),
      'event_type'=>!empty($data['id']) ? 'AGENT_UPDATED' : 'AGENT_CREATED',
      'status'=>$result['ok'] ? 'SUCCESS' : 'FAILED',
      'summary'=>$result['ok'] ? 'تم حفظ بيانات المعتمد.' : 'فشل حفظ بيانات المعتمد.',
      'error_message'=>$result['error'] ?? '',
      'actor_type'=>$actor['type'] ?? 'admin',
      'actor_id'=>$actorId,
    ]);
    return $result;
  }
}

if (!function_exists('ua_agent_service_post_receipt')) {
  function ua_agent_service_post_receipt(mysqli $conn, int $agentId, float $amount, string $reference, string $note, array $actor = []): array {
    return ua_agent_ledger_post($conn, [
      'agent_id'=>$agentId,
      'direction'=>'CREDIT',
      'entry_type'=>'AGENT_RECEIPT',
      'amount'=>$amount,
      'idempotency_key'=>'AGENT_RECEIPT:' . $reference,
      'source_type'=>'receipt',
      'source_id'=>$reference,
      'description'=>$note,
      'created_by_type'=>$actor['type'] ?? 'admin',
      'created_by_id'=>$actor['id'] ?? null,
    ]);
  }
}

if (!function_exists('ua_agent_service_post_charge')) {
  function ua_agent_service_post_charge(mysqli $conn, array $data, bool $manageTransaction = true): array {
    $agentId = (int)($data['agent_id'] ?? 0);
    $amount = round((float)($data['amount'] ?? 0), 2);
    $key = trim((string)($data['idempotency_key'] ?? ''));
    if ($agentId <= 0 || $amount <= 0 || $key === '') {
      return ['ok'=>false,'error'=>'بيانات تحميل المعتمد غير مكتملة.'];
    }
    $agent = ua_agent_repo_get($conn, $agentId);
    if (!$agent) return ['ok'=>false,'error'=>'المعتمد غير موجود أو مؤرشف.'];

    try {
      if ($manageTransaction) $conn->begin_transaction();
      $charge = ua_agent_ledger_post($conn, $data + [
        'direction'=>'DEBIT',
        'created_by_type'=>'agent',
        'created_by_id'=>$agentId,
      ], false);
      if (!$charge['ok']) throw new RuntimeException($charge['error']);

      $commissionAmount = 0.0;
      $commissionType = (string)($agent['commission_type'] ?? 'none');
      $commissionValue = max(0.0, (float)($agent['commission_value'] ?? 0));
      if ($commissionType === 'fixed') $commissionAmount = min($amount, $commissionValue);
      if ($commissionType === 'percent') $commissionAmount = min($amount, round($amount * $commissionValue / 100, 2));
      $commission = null;
      if ($commissionAmount > 0) {
        $commission = ua_agent_ledger_post($conn, [
          'agent_id'=>$agentId,
          'direction'=>'CREDIT',
          'entry_type'=>'COMMISSION',
          'amount'=>$commissionAmount,
          'currency'=>$data['currency'] ?? 'SYP',
          'subscriber_id'=>$data['subscriber_id'] ?? null,
          'invoice_id'=>$data['invoice_id'] ?? null,
          'payment_id'=>$data['payment_id'] ?? null,
          'sale_id'=>$data['sale_id'] ?? null,
          'voucher_id'=>$data['voucher_id'] ?? null,
          'source_type'=>'commission',
          'source_id'=>$data['source_id'] ?? '',
          'source_instance_id'=>$data['source_instance_id'] ?? '',
          'idempotency_key'=>'COMMISSION:' . $key,
          'description'=>'عمولة المعتمد عن: ' . (string)($data['description'] ?? $data['entry_type'] ?? ''),
          'metadata'=>['commission_type'=>$commissionType,'commission_value'=>$commissionValue,'gross_amount'=>$amount],
          'created_by_type'=>$data['created_by_type'] ?? 'agent',
          'created_by_id'=>$data['created_by_id'] ?? $agentId,
        ], false);
        if (!$commission['ok']) throw new RuntimeException($commission['error']);
      }
      if ($manageTransaction) $conn->commit();
      return ['ok'=>true,'charge'=>$charge,'commission'=>$commission,'commission_amount'=>$commissionAmount,'error'=>''];
    } catch (Throwable $e) {
      if ($manageTransaction) @$conn->rollback();
      return ['ok'=>false,'error'=>$e->getMessage()];
    }
  }
}

if (!function_exists('ua_agent_service_charge_subscriber')) {
  function ua_agent_service_charge_subscriber(mysqli $conn, int $agentId, int $subscriberId, int $invoiceId, float $amount, array $actor = []): array {
    return ua_agent_service_post_charge($conn, [
      'agent_id'=>$agentId,
      'entry_type'=>'SUBSCRIBER_REGISTRATION',
      'amount'=>$amount,
      'subscriber_id'=>$subscriberId,
      'invoice_id'=>$invoiceId,
      'source_type'=>'subscriber',
      'source_id'=>(string)$subscriberId,
      'source_instance_id'=>(string)($actor['source_instance_id'] ?? ''),
      'idempotency_key'=>'AGENT_SUBSCRIBER:' . $agentId . ':' . $subscriberId,
      'description'=>'رسوم تسجيل مشترك جديد وباقته الأولية.',
      'created_by_type'=>$actor['type'] ?? 'agent',
      'created_by_id'=>$actor['id'] ?? $agentId,
    ], !isset($actor['manage_transaction']) || (bool)$actor['manage_transaction']);
  }
}

if (!function_exists('ua_agent_service_charge_sale')) {
  function ua_agent_service_charge_sale(mysqli $conn, int $agentId, int $saleId, int $paymentId, float $amount, string $description, array $context = []): array {
    return ua_agent_service_post_charge($conn, [
      'agent_id'=>$agentId,
      'entry_type'=>'VOUCHER_SALE',
      'amount'=>$amount,
      'payment_id'=>$paymentId,
      'sale_id'=>$saleId,
      'voucher_id'=>(int)($context['voucher_id'] ?? 0),
      'source_type'=>'shop_sale',
      'source_id'=>(string)$saleId,
      'source_instance_id'=>(string)($context['source_instance_id'] ?? ''),
      'idempotency_key'=>'AGENT_SALE:' . $agentId . ':' . $saleId,
      'description'=>$description,
      'created_by_type'=>'agent',
      'created_by_id'=>$agentId,
    ], !isset($context['manage_transaction']) || (bool)$context['manage_transaction']);
  }
}
