<?php
require_once __DIR__ . '/../config/config.php';
require_permission('accounting.reports_view');
$u = current_user();

$id = (int)($_GET['id'] ?? 0);
$stmt = $pdo->prepare("SELECT je.*, u.username created_by_name FROM journal_entries je JOIN users u ON u.id=je.created_by WHERE je.id=?");
$stmt->execute([$id]);
$entry = $stmt->fetch();
if (!$entry) { flash('error', 'Journal entry not found.'); redirect('journal_entries/list.php'); }

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['void'])) {
    require_permission('accounting.journal_post');
    $reason = trim($_POST['reason'] ?? '');
    [$ok, $result] = void_journal_entry($pdo, $id, $u['id'], $reason);
    flash($ok ? 'success' : 'error', $ok ? 'Entry voided with a reversing entry.' : $result);
    redirect('journal_entries/view.php?id=' . $id);
}

$lineStmt = $pdo->prepare("SELECT jel.*, coa.account_code, coa.description acc_desc FROM journal_entry_lines jel
                            JOIN chart_of_accounts coa ON coa.id = jel.account_id WHERE jel.entry_id = ?");
$lineStmt->execute([$id]);
$lines = $lineStmt->fetchAll();

$totalDebit = array_sum(array_column($lines, 'debit'));
$totalCredit = array_sum(array_column($lines, 'credit'));

$pageTitle = 'JE ' . $entry['entry_number'];
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="flex items-center justify-between mb-6">
  <div>
    <h1 class="text-2xl font-bold"><?= e($entry['entry_number']) ?></h1>
    <p class="text-slate-500 text-sm"><?= e($entry['description']) ?> · <?= date('M j, Y', strtotime($entry['entry_date'])) ?> · by <?= e($entry['created_by_name']) ?></p>
  </div>
  <span class="px-3 py-1 rounded-full text-sm <?= $entry['status']==='posted' ? 'bg-emerald-100 text-emerald-700' : 'bg-red-100 text-red-700' ?> capitalize"><?= $entry['status'] ?></span>
</div>

<div class="overflow-x-auto">
<div class="bg-white rounded-xl shadow-sm border border-slate-200 mb-6">
  <table class="w-full text-sm">
    <thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
      <th class="text-left px-5 py-2">Account</th><th class="text-left px-5 py-2">Description</th>
      <th class="text-left px-5 py-2">Debit</th><th class="text-left px-5 py-2">Credit</th></tr></thead>
    <tbody>
    <?php foreach ($lines as $l): ?>
      <tr class="border-t border-slate-100">
        <td class="px-5 py-2.5"><?= e($l['account_code']) ?> - <?= e($l['acc_desc']) ?></td>
        <td class="px-5 py-2.5 text-slate-500"><?= e($l['description']) ?></td>
        <td class="px-5 py-2.5"><?= $l['debit'] > 0 ? '₦'.number_format($l['debit'],2) : '' ?></td>
        <td class="px-5 py-2.5"><?= $l['credit'] > 0 ? '₦'.number_format($l['credit'],2) : '' ?></td>
      </tr>
    <?php endforeach; ?>
    </tbody>
    <tfoot><tr class="border-t border-slate-200 font-semibold">
      <td colspan="2" class="px-5 py-2.5 text-right">Total</td>
      <td class="px-5 py-2.5">₦<?= number_format($totalDebit,2) ?></td>
      <td class="px-5 py-2.5">₦<?= number_format($totalCredit,2) ?></td>
    </tr></tfoot>
  </table>
</div>
</div>

<?php if ($entry['status'] === 'posted' && has_permission($pdo, $u, 'accounting.journal_post')): ?>
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5 max-w-md">
    <p class="text-sm font-semibold mb-2">Void This Entry</p>
    <p class="text-xs text-slate-500 mb-3">This creates an equal-and-opposite reversing entry rather than deleting history.</p>
    <form method="POST" class="space-y-3" onsubmit="return confirm('Void this journal entry? This cannot be undone.')">
      <input type="hidden" name="void" value="1">
      <input name="reason" placeholder="Reason for voiding" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <button class="bg-red-600 hover:bg-red-700 text-white text-sm font-medium px-4 py-2 rounded-lg">Void Entry</button>
    </form>
  </div>
<?php elseif ($entry['voided_by_entry_id']): ?>
  <p class="text-sm text-slate-500">Voided by <a href="view.php?id=<?= $entry['voided_by_entry_id'] ?>" class="text-blue-600 hover:underline">reversing entry</a>.</p>
<?php endif; ?>
<?php include __DIR__ . '/../includes/footer.php'; ?>
