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

$accounts = get_chart_of_accounts($pdo);
$formToken = new_form_token('je_create');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $entryDate = $_POST['entry_date'] ?: date('Y-m-d');
    $description = trim($_POST['description'] ?? '');
    $accountIds = $_POST['account_id'] ?? [];
    $debits = $_POST['debit'] ?? [];
    $credits = $_POST['credit'] ?? [];
    $lineDescs = $_POST['line_description'] ?? [];

    $lines = [];
    foreach ($accountIds as $i => $accId) {
        $debit = (float)($debits[$i] ?? 0);
        $credit = (float)($credits[$i] ?? 0);
        if (!$accId || ($debit == 0 && $credit == 0)) continue;
        $lines[] = ['account_id' => $accId, 'debit' => $debit, 'credit' => $credit, 'description' => $lineDescs[$i] ?? ''];
    }

    if (count($lines) < 2) {
        $msg = 'A journal entry needs at least two lines (one debit, one credit).';
        if (is_ajax()) json_response(false, $msg);
        flash('error', $msg);
    } elseif (!consume_form_token('je_create', $_POST['form_token'] ?? '')) {
        $msg = 'This form was already submitted. Refresh the page to post another entry.';
        if (is_ajax()) json_response(false, $msg);
        flash('error', $msg);
        redirect('journal_entries/create.php');
    } else {
        [$ok, $result] = post_journal_entry($pdo, $entryDate, $description, $lines, $u['id'], 'MANUAL');
        if ($ok) {
            $successMsg = 'Journal entry posted.';
            $redirectTo = 'journal_entries/view.php?id=' . $result;
            if (is_ajax()) json_response(true, $successMsg, ['redirect' => $redirectTo]);
            flash('success', $successMsg);
            redirect($redirectTo);
        } else {
            if (is_ajax()) json_response(false, $result);
            flash('error', $result);
        }
    }
}

$pageTitle = 'New Journal Entry';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-2">New Journal Entry</h1>
<p class="text-slate-500 text-sm mb-6">Total debits must equal total credits before this can be posted.</p>

<form method="POST" class="ajax-form bg-white rounded-xl shadow-sm border border-slate-200 p-6" data-loading-text="Posting...">
  <input type="hidden" name="form_token" value="<?= e($formToken) ?>">
  <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
    <div>
      <label class="text-sm font-medium block mb-1">Entry Date</label>
      <input type="date" name="entry_date" value="<?= date('Y-m-d') ?>" required class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
    </div>
    <div>
      <label class="text-sm font-medium block mb-1">Description</label>
      <input name="description" placeholder="What is this entry for?" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
    </div>
  </div>

  <div class="overflow-x-auto">
  <table class="w-full text-sm mb-2">
    <thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
      <th class="text-left px-3 py-2">Account</th><th class="text-left px-3 py-2">Debit</th>
      <th class="text-left px-3 py-2">Credit</th><th class="text-left px-3 py-2">Line Description</th><th></th></tr></thead>
    <tbody id="lineBody">
      <?php for ($i = 0; $i < 2; $i++): ?>
      <tr>
        <td class="px-3 py-2">
          <div class="account-autocomplete relative">
            <input type="text" class="account-search w-full border border-slate-300 rounded-lg px-2 py-1.5" placeholder="Type to search account..." autocomplete="off">
            <input type="hidden" class="account-id-input" name="account_id[]">
            <div class="account-dropdown hidden absolute z-20 bg-white border border-slate-200 rounded-lg mt-1 max-h-48 overflow-y-auto w-full shadow-lg"></div>
          </div>
        </td>
        <td class="px-3 py-2"><input type="number" step="0.01" name="debit[]" class="w-28 border border-slate-300 rounded-lg px-2 py-1.5"></td>
        <td class="px-3 py-2"><input type="number" step="0.01" name="credit[]" class="w-28 border border-slate-300 rounded-lg px-2 py-1.5"></td>
        <td class="px-3 py-2"><input name="line_description[]" class="w-full border border-slate-300 rounded-lg px-2 py-1.5"></td>
        <td><button type="button" onclick="this.closest('tr').remove()" class="text-red-500 px-2">✕</button></td>
      </tr>
      <?php endfor; ?>
    </tbody>
  </table>
  </div>
  <button type="button" id="addLine" class="text-blue-600 text-sm font-medium mb-2">+ Add another line</button>

  <div class="flex justify-end gap-6 text-sm font-medium mb-6 mt-4 border-t border-slate-200 pt-3">
    <span>Total Debit: <span id="totalDebit">0.00</span></span>
    <span>Total Credit: <span id="totalCredit">0.00</span></span>
    <span id="balanceIndicator" class="text-red-600">Unbalanced</span>
  </div>

  <div class="flex gap-3">
    <button type="submit" class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-5 py-2.5 rounded-lg">Post Journal Entry</button>
    <a href="list.php" class="text-slate-500 text-sm self-center">Cancel</a>
  </div>
</form>

<script>
window.ACCOUNTS_DATA = <?= json_encode(array_map(fn($a) => ['id' => $a['id'], 'code' => $a['account_code'], 'name' => $a['description']], $accounts)) ?>;

document.getElementById('addLine').addEventListener('click', function () {
  const row = document.querySelector('#lineBody tr').cloneNode(true);
  row.querySelectorAll('input').forEach(i => i.value = '');
  const dropdown = row.querySelector('.account-dropdown');
  if (dropdown) { dropdown.classList.add('hidden'); dropdown.innerHTML = ''; }
  document.getElementById('lineBody').appendChild(row);
  attachTotals();
});

function attachTotals() {
  document.querySelectorAll('input[name="debit[]"], input[name="credit[]"]').forEach(inp => {
    inp.removeEventListener('input', updateTotals);
    inp.addEventListener('input', updateTotals);
  });
}
function updateTotals() {
  let d = 0, c = 0;
  document.querySelectorAll('input[name="debit[]"]').forEach(i => d += parseFloat(i.value) || 0);
  document.querySelectorAll('input[name="credit[]"]').forEach(i => c += parseFloat(i.value) || 0);
  document.getElementById('totalDebit').textContent = d.toFixed(2);
  document.getElementById('totalCredit').textContent = c.toFixed(2);
  const ind = document.getElementById('balanceIndicator');
  if (d.toFixed(2) === c.toFixed(2) && d > 0) { ind.textContent = 'Balanced ✓'; ind.className = 'text-emerald-600'; }
  else { ind.textContent = 'Unbalanced'; ind.className = 'text-red-600'; }
}
attachTotals();
</script>
<?php include __DIR__ . '/../includes/account_autocomplete.php'; ?>
<?php include __DIR__ . '/../includes/footer.php'; ?>
