<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/../app/Services/AccountingService.php';
require_once __DIR__ . '/../app/audit.php';

$pdo = db();
$svc = new AccountingService($pdo);

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { die('Invalid id'); }

// fetch original tx (must belong to current company and active)
$stmt = $pdo->prepare("SELECT * FROM cash_transactions WHERE id=? AND company_id=?");
$stmt->execute([$id, (int)$_SESSION['company_id']]);
$tx = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$tx) { die('Not found'); }

// If status column exists use it; else fall back to map existence
$hasStatus = true;
try { $pdo->query("SELECT status FROM cash_transactions LIMIT 1"); } catch (Throwable $e) { $hasStatus = false; }

if ($hasStatus && $tx['status'] === 'VOID') {
  die('تم إلغاء الحركة بالفعل');
}

$reverseType = ($tx['tx_type'] === 'IN') ? 'OUT' : 'IN';

$data = [
  'company_id' => (int)$tx['company_id'],
  'tx_date' => date('Y-m-d'),
  'tx_type' => $reverseType,
  'cash_account_id' => (int)$tx['cash_account_id'],
  'counter_account_id' => (int)$tx['counter_account_id'],
  'amount' => (float)$tx['amount'],
  'memo' => 'قيد عكسي للحركة #' . (int)$tx['id'],
  'created_by' => (int)($_SESSION['user_id'] ?? 0),
];

$pdo->beginTransaction();
try {
  $newTxId = $svc->createCashTxDraft($data);

  // mark original as void and link, if columns exist
  if ($hasStatus) {
    $pdo->prepare("UPDATE cash_transactions SET status='VOID', reversed_by_tx_id=? WHERE id=?")->execute([$newTxId, $id]);
    $pdo->prepare("UPDATE cash_transactions SET reverse_of_tx_id=? WHERE id=?")->execute([$id, $newTxId]);
  }

  audit_log($pdo, [
    'company_id' => (int)$tx['company_id'],
    'user_id' => (int)($_SESSION['user_id'] ?? 0),
    'module' => 'cash',
    'action' => 'REVERSE',
    'entity_type' => 'cash_transaction',
    'entity_id' => (string)$newTxId,
    'description' => audit_compose_description('إنشاء حركة عكسية', [
      'رقم الحركة الأصلية' => (string)$id,
      'رقم الحركة العكسية' => (string)$newTxId,
      'النوع الأصلي' => audit_tx_type_label((string)$tx['tx_type']),
      'النوع العكسي' => audit_tx_type_label((string)$reverseType),
      'المبلغ' => audit_money($tx['amount']),
      'حساب النقدية' => audit_account_label($pdo, (int)$tx['company_id'], (int)$tx['cash_account_id']),
      'الحساب المقابل' => audit_account_label($pdo, (int)$tx['company_id'], (int)$tx['counter_account_id']),
    ]),
  ]);
  $pdo->commit();
  flash_set('تم إنشاء حركة عكسية وإلغاء الحركة الأصلية');
  header('Location: index.php');
  exit;
} catch (Throwable $e) {
  $pdo->rollBack();
  die('حدث خطأ: ' . $e->getMessage());
}
