<?php
require_once __DIR__ . '/../app/init.php';

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

// entry must belong to current company and posted
$stmt = $pdo->prepare("SELECT * FROM journal_entries WHERE id=? AND company_id=? AND status='POSTED'");
$stmt->execute([$id, (int)$_SESSION['company_id']]);
$entry = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$entry) die('Not found');

$pdo->beginTransaction();
try {
  // create reversal entry
  $ref = 'REV-' . $entry['ref'];
  $memo = 'قيد عكسي للقيد #' . $entry['id'];

  $stmt = $pdo->prepare("INSERT INTO journal_entries (company_id, entry_date, ref, memo, source, source_id, status, created_by, reversed_entry_id)
                         VALUES (?,?,?,?, 'MANUAL', NULL, 'POSTED', ?, ?)");
  // reversed_entry_id column may not exist; detect
  $hasReversedCol = true;
  try { $pdo->query("SELECT reversed_entry_id FROM journal_entries LIMIT 1"); } catch (Throwable $e) { $hasReversedCol = false; }

  if ($hasReversedCol) {
    $stmt = $pdo->prepare("INSERT INTO journal_entries (company_id, entry_date, ref, memo, source, source_id, status, created_by, reversed_entry_id)
                           VALUES (?,?,?,?, 'MANUAL', NULL, 'POSTED', ?, ?)");
    $stmt->execute([(int)$entry['company_id'], date('Y-m-d'), $ref, $memo, (int)($_SESSION['user_id'] ?? 0), $id]);
  } else {
    $stmt = $pdo->prepare("INSERT INTO journal_entries (company_id, entry_date, ref, memo, source, source_id, status, created_by)
                           VALUES (?,?,?,?, 'MANUAL', NULL, 'POSTED', ?)");
    $stmt->execute([(int)$entry['company_id'], date('Y-m-d'), $ref, $memo, (int)($_SESSION['user_id'] ?? 0)]);
  }
  $newEntryId = (int)$pdo->lastInsertId();

  // fetch lines
  $stmt = $pdo->prepare("SELECT * FROM journal_lines WHERE entry_id=? AND company_id=? ORDER BY line_no");
  $stmt->execute([$id, (int)$_SESSION['company_id']]);
  $lines = $stmt->fetchAll(PDO::FETCH_ASSOC);

  $ins = $pdo->prepare("INSERT INTO journal_lines (company_id, entry_id, line_no, account_id, description, debit, credit)
                        VALUES (?,?,?,?,?,?,?)");
  $ln = 1;
  foreach ($lines as $l) {
    $ins->execute([
      (int)$l['company_id'],
      $newEntryId,
      $ln++,
      (int)$l['account_id'],
      'عكسي: ' . ($l['description'] ?? ''),
      (float)$l['credit'],
      (float)$l['debit']
    ]);
  }

  $pdo->commit();
  flash_set('تم إنشاء القيد العكسي بنجاح');
  header('Location: index.php');
  exit;
} catch (Throwable $e) {
  $pdo->rollBack();
  die('حدث خطأ: ' . $e->getMessage());
}
