<?php
require_once __DIR__ . '/../includes/auth.php';
require_login();
if (!has_role(['admin','super_admin','accountant','finance_manager'])) {
    echo '<div class="alert alert-danger m-4">Access denied.</div>'; exit;
}
$canPost    = has_role(['admin','super_admin','accountant','finance_manager']);
$canReverse = has_role(['admin','super_admin']);
$canDelete  = has_role(['admin','super_admin']);
?>
<div class="page-journal-entries">
<div class="container-fluid p-4">

  <div class="d-flex justify-content-between align-items-center mb-3">
    <div>
      <h4 class="mb-0"><i class="bi bi-journal-bookmark-fill me-2 text-primary"></i>Journal Entries</h4>
      <small class="text-muted">Double-entry bookkeeping &middot; General Ledger</small>
    </div>
    <button class="btn btn-primary" id="btnNewJournal">
      <i class="bi bi-plus-lg me-1"></i>New Journal Entry
    </button>
  </div>

  <!-- Filters -->
  <div class="card mb-3">
    <div class="card-body py-2">
      <div class="row g-2 align-items-end">
        <div class="col-md-3">
          <input type="text" id="jSearch" class="form-control form-control-sm" placeholder="Voucher, narration, reference…">
        </div>
        <div class="col-md-2">
          <select id="jStatus" class="form-select form-select-sm">
            <option value="">All Status</option>
            <option value="Draft">Draft</option>
            <option value="Posted">Posted</option>
            <option value="Reversed">Reversed</option>
          </select>
        </div>
        <div class="col-md-2">
          <select id="jType" class="form-select form-select-sm">
            <option value="">All Types</option>
            <option value="Simple">Simple</option>
            <option value="Compound">Compound</option>
            <option value="Adjusting">Adjusting</option>
            <option value="Closing">Closing</option>
            <option value="Opening">Opening</option>
            <option value="Reversing">Reversing</option>
          </select>
        </div>
        <div class="col-md-2">
          <input type="date" id="jDateFrom" class="form-control form-control-sm">
        </div>
        <div class="col-md-2">
          <input type="date" id="jDateTo" class="form-control form-control-sm">
        </div>
        <div class="col-md-1 d-flex gap-1">
          <button class="btn btn-primary btn-sm flex-fill" id="btnJFilter"><i class="bi bi-search"></i></button>
          <button class="btn btn-outline-secondary btn-sm" id="btnJReset"><i class="bi bi-x"></i></button>
        </div>
      </div>
    </div>
  </div>

  <!-- Summary KPIs -->
  <div class="row g-3 mb-3" id="jKpis" style="display:none!important"></div>

  <!-- Table -->
  <div class="card">
    <div class="table-responsive">
      <table class="table table-sm table-hover align-middle mb-0">
        <thead class="table-dark">
          <tr>
            <th>Voucher</th><th>Date</th><th>Type</th><th>Narration</th>
            <th>Reference</th><th class="text-end">Debit</th><th class="text-end">Credit</th>
            <th>Status</th><th>Created By</th><th style="width:130px">Actions</th>
          </tr>
        </thead>
        <tbody id="jTbody">
          <tr><td colspan="10" class="text-center text-muted py-4">Loading…</td></tr>
        </tbody>
      </table>
    </div>
  </div>
</div>
</div>

<!-- ═══ New/Edit Journal Modal ══════════════════════════════════════════════ -->
<div class="modal fade" id="journalModal" tabindex="-1" data-bs-backdrop="static">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title"><i class="bi bi-journal-plus me-2"></i><span id="jModalTitle">New Journal Entry</span></h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="jEditId">
        <div class="row g-3 mb-3">
          <div class="col-md-3">
            <label class="form-label fw-bold">Voucher No</label>
            <input type="text" id="jVoucher" class="form-control bg-light" readonly placeholder="Auto on save">
          </div>
          <div class="col-md-2">
            <label class="form-label fw-bold">Date <span class="text-danger">*</span></label>
            <input type="date" id="jDate" class="form-control" required>
          </div>
          <div class="col-md-2">
            <label class="form-label fw-bold">Entry Type</label>
            <select id="jEntryType" class="form-select">
              <option value="Simple">Simple</option>
              <option value="Compound">Compound</option>
              <option value="Adjusting">Adjusting</option>
              <option value="Closing">Closing</option>
              <option value="Opening">Opening</option>
              <option value="Reversing">Reversing</option>
            </select>
          </div>
          <div class="col-md-2">
            <label class="form-label">Reference</label>
            <input type="text" id="jReference" class="form-control" placeholder="Invoice / Bill no">
          </div>
          <div class="col-md-3">
            <label class="form-label fw-bold">Narration <span class="text-danger">*</span></label>
            <input type="text" id="jNarration" class="form-control" placeholder="Short description of this entry">
          </div>
        </div>

        <!-- Lines -->
        <div class="d-flex justify-content-between align-items-center mb-2">
          <h6 class="mb-0 text-primary"><i class="bi bi-list-columns me-1"></i>Debit / Credit Lines</h6>
          <button type="button" class="btn btn-outline-success btn-sm" id="btnAddLine">
            <i class="bi bi-plus-lg me-1"></i>Add Line
          </button>
        </div>
        <div class="table-responsive">
          <table class="table table-sm table-bordered align-middle mb-0" id="jLinesTable">
            <thead class="table-secondary">
              <tr>
                <th style="width:22%">Account Head <span class="text-danger">*</span></th>
                <th style="width:18%">Sub Account Head</th>
                <th style="width:12%">Cost Center</th>
                <th style="width:18%">Line Narration</th>
                <th style="width:12%" class="text-end">Debit (LKR)</th>
                <th style="width:12%" class="text-end">Credit (LKR)</th>
                <th style="width:40px"></th>
              </tr>
            </thead>
            <tbody id="jLinesTbody"></tbody>
            <tfoot class="table-light fw-bold">
              <tr>
                <td colspan="4" class="text-end pe-3">Totals</td>
                <td class="text-end text-primary fs-6" id="jTotalDr">0.00</td>
                <td class="text-end text-danger fs-6" id="jTotalCr">0.00</td>
                <td></td>
              </tr>
              <tr id="jBalanceRow" style="display:none">
                <td colspan="6" class="text-center py-1" id="jBalanceMsg"></td>
              </tr>
            </tfoot>
          </table>
        </div>
        <div class="alert alert-light border mt-3 py-2 small mb-0">
          <i class="bi bi-lightbulb text-warning me-1"></i>
          <strong>Rule:</strong> Total Debits must equal Total Credits to post.
          Save as <em>Draft</em> to finish later.
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
        <?php if ($canPost): ?>
        <button type="button" class="btn btn-outline-primary" id="btnSaveDraft">
          <i class="bi bi-save me-1"></i>Save as Draft
        </button>
        <button type="button" class="btn btn-success" id="btnPostJournal">
          <i class="bi bi-check-circle me-1"></i>Post Journal
        </button>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<!-- ═══ View Journal Modal ═══════════════════════════════════════════════════ -->
<div class="modal fade" id="viewJournalModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-journal-text me-2"></i><span id="vjTitle">Journal Entry</span></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" id="vjBody">Loading…</div>
      <div class="modal-footer" id="vjFooter"></div>
    </div>
  </div>
</div>

<!-- ═══ Reversal Date Modal ══════════════════════════════════════════════════ -->
<div class="modal fade" id="reversalModal" tabindex="-1">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header"><h6 class="modal-title">Set Reversal Date</h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <label class="form-label">Reversal Entry Date</label>
        <input type="date" id="revDate" class="form-control">
        <input type="hidden" id="revJournalId">
      </div>
      <div class="modal-footer">
        <button class="btn btn-danger w-100" id="btnConfirmReverse">
          <i class="bi bi-arrow-counterclockwise me-1"></i>Create Reversal Entry
        </button>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  if (!$('.page-journal-entries').length) return;

  const csrf = '<?php echo htmlspecialchars(csrf_token()); ?>';
  const canDelete  = <?php echo $canDelete  ? 'true':'false'; ?>;
  const canReverse = <?php echo $canReverse ? 'true':'false'; ?>;
  let accountHeads = [];
  let costCenters  = [];
  let lineIdx = 0;

  // ── Helpers ────────────────────────────────────────────────────────────────
  function fmt(n){ return parseFloat(n||0).toLocaleString('en-LK',{minimumFractionDigits:2,maximumFractionDigits:2}); }
  function r2(n){ return Math.round(n*100)/100; }
  function today(){ return new Date().toISOString().slice(0,10); }

  function statusBadge(s){
    const m={Draft:'bg-warning text-dark',Posted:'bg-success',Reversed:'bg-secondary'};
    return `<span class="badge ${m[s]||'bg-light text-dark'}">${s}</span>`;
  }
  function typeBadge(t){
    const m={Simple:'bg-info text-dark',Compound:'bg-primary',Adjusting:'bg-warning text-dark',
             Closing:'bg-danger',Opening:'bg-success',Reversing:'bg-secondary'};
    return `<span class="badge ${m[t]||'bg-light text-dark'}">${t}</span>`;
  }

  // ── Load account heads (parents only) ────────────────────────────────────
  $.get('api/account_heads.php', {action:'list',active_only:1,parent_only:1}, function(res){
    accountHeads = res.data||[];
    refreshLineDropdowns();
  });

  // ── Load cost centers ──────────────────────────────────────────────────────
  $.get('api/cost_centers.php', {action:'list',active_only:1}, function(res){
    costCenters = (res.data||[]).map(c => c.name);
    refreshLineDropdowns();
  });

  function buildAhOptions(selected){
    let opts = '<option value="">-- Account Head --</option>';
    accountHeads.forEach(function(h){
      const esc = $('<div>').text(h.account_name).html();
      opts += `<option value="${esc}" data-id="${h.id}" ${h.account_name===selected?'selected':''}>${esc}</option>`;
    });
    return opts;
  }

  function buildSubAhOptions(subs, selected){
    let opts = '<option value="">-- None --</option>';
    (subs||[]).forEach(function(s){
      const esc = $('<div>').text(s.account_name).html();
      opts += `<option value="${esc}" ${s.account_name===selected?'selected':''}>${esc}</option>`;
    });
    return opts;
  }

  function loadLineSubs($row, selectedSub){
    const parentId = $row.find('.line-ah').find(':selected').data('id');
    const $sub = $row.find('.line-sah');
    $sub.html('<option value="">-- None --</option>');
    if (!parentId) return;
    $.get('api/account_heads.php', {action:'list',active_only:1,parent_id:parentId}, function(res){
      $sub.html(buildSubAhOptions(res.data||[], selectedSub||''));
    });
  }

  function buildCcOptions(selected){
    let opts = '<option value="">-- Cost Center --</option>';
    costCenters.forEach(function(c){
      const esc = $('<div>').text(c).html();
      opts += `<option value="${esc}" ${c===selected?'selected':''}>${esc}</option>`;
    });
    return opts;
  }

  function refreshLineDropdowns(){
    $('#jLinesTbody .line-ah').each(function(){
      const cur=$(this).val();
      $(this).html(buildAhOptions(cur));
    });
    $('#jLinesTbody .line-cc').each(function(){
      const cur=$(this).val();
      $(this).html(buildCcOptions(cur));
    });
  }

  // Reload sub-account-head when parent changes
  $(document).on('change','.line-ah',function(){
    loadLineSubs($(this).closest('tr'), '');
  });

  // ── Load journal list ──────────────────────────────────────────────────────
  function loadJournals(){
    const p={action:'list',search:$('#jSearch').val(),status:$('#jStatus').val(),
             entry_type:$('#jType').val(),date_from:$('#jDateFrom').val(),date_to:$('#jDateTo').val()};
    $('#jTbody').html('<tr><td colspan="10" class="text-center py-4 text-muted">Loading…</td></tr>');
    $.get('api/journal_entries.php',p,function(res){
      const $tb=$('#jTbody').empty();
      const rows=res.data||[];
      if(!rows.length){$tb.html('<tr><td colspan="10" class="text-center py-4 text-muted">No entries found</td></tr>');return;}
      rows.forEach(function(j){
        const postBtn = j.status==='Draft'
          ? `<button class="btn btn-sm btn-outline-success me-1 btnPostJ" data-id="${j.id}" title="Post"><i class="bi bi-check-circle"></i></button>` : '';
        const delBtn = j.status==='Draft' && canDelete
          ? `<button class="btn btn-sm btn-outline-danger me-1 btnDelJ" data-id="${j.id}" title="Delete"><i class="bi bi-trash"></i></button>` : '';
        const revBtn = j.status==='Posted' && canReverse
          ? `<button class="btn btn-sm btn-outline-warning btnRevJ" data-id="${j.id}" title="Reverse"><i class="bi bi-arrow-counterclockwise"></i></button>` : '';
        $tb.append(`<tr>
          <td><code class="small">${j.voucher_number}</code></td>
          <td class="text-nowrap small">${j.entry_date}</td>
          <td>${typeBadge(j.entry_type)}</td>
          <td class="small">${$('<div>').text(j.narration).html()}</td>
          <td class="small text-muted">${$('<div>').text(j.reference||'').html()}</td>
          <td class="text-end text-primary fw-bold small">${fmt(j.total_debit)}</td>
          <td class="text-end text-danger fw-bold small">${fmt(j.total_credit)}</td>
          <td>${statusBadge(j.status)}</td>
          <td class="small text-muted">${$('<div>').text(j.created_by_name||'').html()}</td>
          <td>
            <button class="btn btn-sm btn-outline-secondary me-1 btnViewJ" data-id="${j.id}" title="View"><i class="bi bi-eye"></i></button>
            ${postBtn}${delBtn}${revBtn}
          </td>
        </tr>`);
      });
    });
  }

  $('#btnJFilter').on('click',loadJournals);
  $('#jSearch').on('keydown',function(e){if(e.key==='Enter')loadJournals();});
  $('#btnJReset').on('click',function(){$('#jSearch,#jDateFrom,#jDateTo').val('');$('#jStatus,#jType').val('');loadJournals();});

  // ── Journal lines ──────────────────────────────────────────────────────────
  function addLine(ah,dr,cr,cc,ln,sah){
    ah=ah||''; dr=dr||''; cr=cr||''; cc=cc||''; ln=ln||''; sah=sah||'';
    const i=lineIdx++;
    $('#jLinesTbody').append(`<tr data-line="${i}">
      <td><select class="form-select form-select-sm line-ah">${buildAhOptions(ah)}</select></td>
      <td><select class="form-select form-select-sm line-sah"><option value="">-- None --</option></select></td>
      <td><select class="form-select form-select-sm line-cc">${buildCcOptions(cc)}</select></td>
      <td><input type="text" class="form-control form-control-sm line-ln" placeholder="Optional" value="${$('<div>').text(ln).html()}"></td>
      <td><input type="number" class="form-control form-control-sm text-end line-dr" min="0" step="0.01" placeholder="0.00" value="${dr}"></td>
      <td><input type="number" class="form-control form-control-sm text-end line-cr" min="0" step="0.01" placeholder="0.00" value="${cr}"></td>
      <td class="text-center"><button type="button" class="btn btn-sm btn-outline-danger btnRemoveLine"><i class="bi bi-x-lg"></i></button></td>
    </tr>`);
    // If pre-filled account head, load its subs
    if (ah) loadLineSubs($('#jLinesTbody tr[data-line="'+i+'"]'), sah);
    recalc();
  }

  $(document).on('click','.btnRemoveLine',function(){$(this).closest('tr').remove();recalc();});
  $(document).on('input','.line-dr,.line-cr',recalc);

  function recalc(){
    let dr=0,cr=0;
    $('.line-dr').each(function(){dr+=parseFloat($(this).val()||0);});
    $('.line-cr').each(function(){cr+=parseFloat($(this).val()||0);});
    $('#jTotalDr').text(fmt(dr));
    $('#jTotalCr').text(fmt(cr));
    const diff=Math.abs(r2(dr)-r2(cr));
    if(dr===0&&cr===0){$('#jBalanceRow').hide();return;}
    if(diff<0.01){
      $('#jBalanceMsg').html('<span class="text-success fw-bold"><i class="bi bi-check-circle-fill me-1"></i>Balanced — Debits = Credits</span>');
    } else {
      const side=dr>cr?'Credit':'Debit';
      $('#jBalanceMsg').html(`<span class="text-danger fw-bold"><i class="bi bi-exclamation-triangle-fill me-1"></i>Out of balance by LKR ${fmt(diff)} — need LKR ${fmt(diff)} more ${side}</span>`);
    }
    $('#jBalanceRow').show();
  }

  $('#btnAddLine').on('click',function(){addLine();});

  // ── Open new journal modal ─────────────────────────────────────────────────
  $('#btnNewJournal').on('click',function(){
    $('#jEditId').val('');
    $('#jModalTitle').text('New Journal Entry');
    $('#jVoucher').val('');
    $('#jDate').val(today());
    $('#jEntryType').val('Simple');
    $('#jReference,#jNarration').val('');
    $('#jLinesTbody').empty(); lineIdx=0;
    addLine(); addLine();
    new bootstrap.Modal(document.getElementById('journalModal')).show();
  });

  // ── Collect lines for POST ─────────────────────────────────────────────────
  function collectPayload(saveAs){
    const params=new URLSearchParams();
    params.append('action','create');
    params.append('csrf',csrf);
    params.append('entry_date',$('#jDate').val());
    params.append('entry_type',$('#jEntryType').val());
    params.append('narration',$('#jNarration').val().trim());
    params.append('reference',$('#jReference').val().trim());
    params.append('save_as',saveAs);
    let i=0;
    $('#jLinesTbody tr').each(function(){
      const ah  = $(this).find('.line-ah').val();
      const sah = $(this).find('.line-sah').val();
      params.append(`lines[${i}][account_head]`, ah);
      params.append(`lines[${i}][account_code]`, $(this).find('.line-ah :selected').data('code')||'');
      params.append(`lines[${i}][sub_account_head]`, sah);
      params.append(`lines[${i}][debit]`,$(this).find('.line-dr').val()||'0');
      params.append(`lines[${i}][credit]`,$(this).find('.line-cr').val()||'0');
      params.append(`lines[${i}][cost_center]`,$(this).find('.line-cc').val());
      params.append(`lines[${i}][line_narration]`,$(this).find('.line-ln').val());
      i++;
    });
    return params;
  }

  function doSave(saveAs){
    if(!$('#jDate').val()){alert('Date is required');return;}
    if(!$('#jNarration').val().trim()){alert('Narration is required');return;}
    const $btn = saveAs==='draft' ? $('#btnSaveDraft') : $('#btnPostJournal');
    $btn.prop('disabled',true).prepend('<i class="bi bi-hourglass-split me-1"></i>');
    $.ajax({url:'api/journal_entries.php',method:'POST',
      data:collectPayload(saveAs).toString(),
      contentType:'application/x-www-form-urlencoded',
      success:function(res){
        $btn.prop('disabled',false).find('.bi-hourglass-split').remove();
        if(res.success){
          alert(res.message);
          bootstrap.Modal.getInstance(document.getElementById('journalModal')).hide();
          loadJournals();
        } else { alert(res.message||'Error'); }
      },
      error:function(xhr){
        $btn.prop('disabled',false).find('.bi-hourglass-split').remove();
        alert(xhr.responseJSON?.message||'Server error');
      }
    });
  }

  $('#btnSaveDraft').on('click',function(){doSave('draft');});
  $('#btnPostJournal').on('click',function(){doSave('post');});

  // ── View journal ──────────────────────────────────────────────────────────
  $(document).on('click','.btnViewJ',function(){
    const id=$(this).data('id');
    $.get('api/journal_entries.php',{action:'get',id:id},function(res){
      const j=res.data; const lines=res.lines||[];
      let linesHtml='<table class="table table-sm table-bordered mb-0"><thead class="table-secondary"><tr><th>Account Head</th><th>Sub Account Head</th><th>Cost Center</th><th>Line Narration</th><th class="text-end">Debit</th><th class="text-end">Credit</th></tr></thead><tbody>';
      lines.forEach(function(l){
        const subDisp = l.sub_account_head
          ? `<span class="badge bg-info text-dark">${$('<div>').text(l.sub_account_head).html()}</span>`
          : '<span class="text-muted small">—</span>';
        linesHtml+=`<tr>
          <td>${$('<div>').text(l.account_head).html()}</td>
          <td>${subDisp}</td>
          <td class="text-muted small">${$('<div>').text(l.cost_center||'').html()}</td>
          <td class="text-muted small">${$('<div>').text(l.line_narration||'').html()}</td>
          <td class="text-end text-primary">${parseFloat(l.debit_amount)>0?fmt(l.debit_amount):''}</td>
          <td class="text-end text-danger">${parseFloat(l.credit_amount)>0?fmt(l.credit_amount):''}</td>
        </tr>`;
      });
      linesHtml+=`</tbody><tfoot class="table-light fw-bold"><tr><td colspan="4" class="text-end">Total</td><td class="text-end text-primary">${fmt(j.total_debit)}</td><td class="text-end text-danger">${fmt(j.total_credit)}</td></tr></tfoot></table>`;

      $('#vjTitle').text(j.voucher_number);
      $('#vjBody').html(`
        <div class="row g-2 mb-3">
          <div class="col-6 col-md-3"><small class="text-muted d-block">Date</small><strong>${j.entry_date}</strong></div>
          <div class="col-6 col-md-3"><small class="text-muted d-block">Type</small>${typeBadge(j.entry_type)}</div>
          <div class="col-6 col-md-3"><small class="text-muted d-block">Status</small>${statusBadge(j.status)}</div>
          <div class="col-6 col-md-3"><small class="text-muted d-block">Reference</small>${$('<div>').text(j.reference||'—').html()}</div>
          <div class="col-12"><small class="text-muted d-block">Narration</small><strong>${$('<div>').text(j.narration).html()}</strong></div>
        </div>
        ${linesHtml}
      `);
      const footer=[];
      if(j.status==='Draft'){
        footer.push(`<button class="btn btn-success btnPostJ" data-id="${j.id}"><i class="bi bi-check-circle me-1"></i>Post</button>`);
        if(canDelete) footer.push(`<button class="btn btn-outline-danger btnDelJ" data-id="${j.id}"><i class="bi bi-trash me-1"></i>Delete Draft</button>`);
      }
      if(j.status==='Posted'&&canReverse) footer.push(`<button class="btn btn-warning btnRevJ" data-id="${j.id}"><i class="bi bi-arrow-counterclockwise me-1"></i>Reverse</button>`);
      $('#vjFooter').html(footer.join(''));
      new bootstrap.Modal(document.getElementById('viewJournalModal')).show();
    });
  });

  // ── Post draft ────────────────────────────────────────────────────────────
  $(document).on('click','.btnPostJ',function(){
    const id=$(this).data('id');
    if(!confirm('Post this journal? This cannot be undone (only reversed).')) return;
    $.post('api/journal_entries.php',{action:'post',csrf:csrf,id:id},function(res){
      alert(res.message);
      $('.modal.show').each(function(){ bootstrap.Modal.getInstance(this)?.hide(); });
      loadJournals();
    }).fail(function(xhr){alert(xhr.responseJSON?.message||'Error');});
  });

  // ── Delete draft ──────────────────────────────────────────────────────────
  $(document).on('click','.btnDelJ',function(){
    const id=$(this).data('id');
    if(!confirm('Delete this draft journal entry?')) return;
    $.post('api/journal_entries.php',{action:'delete',csrf:csrf,id:id},function(res){
      alert(res.message);
      $('.modal.show').each(function(){ bootstrap.Modal.getInstance(this)?.hide(); });
      loadJournals();
    }).fail(function(xhr){alert(xhr.responseJSON?.message||'Error');});
  });

  // ── Reverse ───────────────────────────────────────────────────────────────
  $(document).on('click','.btnRevJ',function(){
    $('#revJournalId').val($(this).data('id'));
    $('#revDate').val(today());
    new bootstrap.Modal(document.getElementById('reversalModal')).show();
  });

  $('#btnConfirmReverse').on('click',function(){
    const id=$('#revJournalId').val();
    const dt=$('#revDate').val();
    if(!dt){alert('Select a reversal date');return;}
    $.post('api/journal_entries.php',{action:'reverse',csrf:csrf,id:id,reversal_date:dt},function(res){
      alert(res.message);
      bootstrap.Modal.getInstance(document.getElementById('reversalModal')).hide();
      loadJournals();
    }).fail(function(xhr){alert(xhr.responseJSON?.message||'Error');});
  });

  // ── Init ──────────────────────────────────────────────────────────────────
  loadJournals();
})();
</script>
