<?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;
}
?>
<div class="page-exp-transfer">
<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-arrow-left-right me-2 text-primary"></i>Transfer Expenditures to Cash Book</h4>
      <small class="text-muted">Pick expenditures and post them as Payment transactions in the cash book</small>
    </div>
    <div class="d-flex gap-2">
      <button class="btn btn-outline-secondary btn-sm" id="btnShowTransferred">
        <i class="bi bi-check2-all me-1"></i>View Transferred
      </button>
      <a href="index.php?page=cash_book_entry" class="btn btn-outline-primary btn-sm">
        <i class="bi bi-journal-book me-1"></i>Cash Book Entry
      </a>
    </div>
  </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">
          <label class="form-label small mb-1">Search</label>
          <input type="text" id="etSearch" class="form-control form-control-sm" placeholder="Description, vendor, invoice…">
        </div>
        <div class="col-md-2">
          <label class="form-label small mb-1">Category</label>
          <select id="etCategory" class="form-select form-select-sm">
            <option value="">All Categories</option>
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label small mb-1">From</label>
          <input type="date" id="etDateFrom" class="form-control form-control-sm">
        </div>
        <div class="col-md-2">
          <label class="form-label small mb-1">To</label>
          <input type="date" id="etDateTo" class="form-control form-control-sm">
        </div>
        <div class="col-md-3 d-flex gap-2">
          <button class="btn btn-primary btn-sm w-100" id="btnEtFilter">
            <i class="bi bi-search me-1"></i>Filter
          </button>
          <button class="btn btn-outline-secondary btn-sm" id="btnEtReset">
            <i class="bi bi-x-circle"></i>
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- Transfer Settings Bar -->
  <div class="card mb-3 border-primary" id="transferSettingsBar" style="display:none;">
    <div class="card-body py-2">
      <div class="row g-2 align-items-end">
        <div class="col-12">
          <strong class="text-primary"><i class="bi bi-funnel me-1"></i>Transfer Settings — applied to all selected rows</strong>
        </div>
        <div class="col-md-4">
          <label class="form-label small mb-1">Bank Account <span class="text-danger">*</span></label>
          <select id="etBankAccount" class="form-select form-select-sm">
            <option value="">-- Select Bank Account --</option>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label small mb-1">Account Head <span class="text-danger">*</span></label>
          <select id="etAccountHead" class="form-select form-select-sm">
            <option value="">-- Select Account Head --</option>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label small mb-1">Sub Account Head</label>
          <select id="etSubAccountHead" class="form-select form-select-sm">
            <option value="">-- None --</option>
          </select>
          <div class="form-text text-muted small" id="etSubHint">Select an Account Head first</div>
        </div>
        <div class="col-md-2 d-flex align-items-end gap-2">
          <button class="btn btn-success btn-sm w-100" id="btnTransferSelected">
            <i class="bi bi-arrow-right-circle me-1"></i>Transfer Selected (<span id="etSelCount">0</span>)
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- Summary badges -->
  <div class="d-flex gap-3 mb-2 align-items-center flex-wrap">
    <div>
      <span class="badge bg-secondary" id="etTotalBadge">Total: 0</span>
      <span class="badge bg-primary ms-1" id="etSelectedBadge">Selected: 0</span>
      <span class="badge bg-success ms-1" id="etAmountBadge">Amount: LKR 0.00</span>
    </div>
    <div class="ms-auto d-flex gap-2">
      <button class="btn btn-outline-secondary btn-sm" id="btnSelectAll">Select All</button>
      <button class="btn btn-outline-secondary btn-sm" id="btnClearAll">Clear All</button>
    </div>
  </div>

  <!-- Table -->
  <div class="card">
    <div class="table-responsive">
      <table class="table table-sm table-hover align-middle mb-0" id="etTable">
        <thead class="table-dark">
          <tr>
            <th style="width:40px"><input type="checkbox" id="chkSelectAll" class="form-check-input"></th>
            <th>Date</th>
            <th>Category</th>
            <th>Description</th>
            <th>Vendor</th>
            <th>Invoice No</th>
            <th>Payment Method</th>
            <th class="text-end">Amount (LKR)</th>
            <th style="width:80px">Status</th>
          </tr>
        </thead>
        <tbody id="etTbody">
          <tr><td colspan="9" class="text-center text-muted py-4">Loading…</td></tr>
        </tbody>
      </table>
    </div>
  </div>

</div>
</div>

<!-- Transferred view modal -->
<div class="modal fade" id="transferredModal" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-check2-all me-2 text-success"></i>Already Transferred to Cash Book</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body p-0">
        <div class="table-responsive">
          <table class="table table-sm align-middle mb-0">
            <thead class="table-light">
              <tr>
                <th>Date</th><th>Category</th><th>Description</th><th>Vendor</th>
                <th class="text-end">Amount</th><th>Account Head</th><th>Sub Head</th><th>Cash Book Txn</th>
                <?php if (has_role(['admin','super_admin'])): ?>
                <th>Undo</th>
                <?php endif; ?>
              </tr>
            </thead>
            <tbody id="transferredTbody">
              <tr><td colspan="7" class="text-center text-muted py-3">Loading…</td></tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

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

  const csrf = '<?php echo htmlspecialchars(csrf_token()); ?>';
  const isAdmin = <?php echo has_role(['admin','super_admin']) ? 'true' : 'false'; ?>;
  let showingTransferred = false;
  let allRows = [];

  // ── Load dropdowns ────────────────────────────────────────────────────────
  $.get('api/finance.php', { action:'list_bank_accounts', is_active:1 }, function(res){
    const $sel = $('#etBankAccount');
    (res.data||[]).forEach(function(b){
      const label = b.account_name + (b.bank_name?' ('+b.bank_name+')':'');
      const opt = $('<option>').val(b.id).text(label);
      if (b.is_default==1) opt.prop('selected',true);
      $sel.append(opt);
    });
  });

  $.get('api/account_heads.php', { action:'list', active_only:1, parent_only:1 }, function(res){
    const $sel = $('#etAccountHead');
    const groups = {};
    (res.data||[]).forEach(function(h){
      if(!groups[h.account_type]) groups[h.account_type]=[];
      groups[h.account_type].push(h);
    });
    Object.keys(groups).forEach(function(cat){
      const $og = $('<optgroup>').attr('label', cat);
      groups[cat].forEach(function(h){
        const opt = $('<option>').val(h.account_name).text(h.account_name).attr('data-id', h.id);
        $og.append(opt);
      });
      $sel.append($og);
    });
  });

  function loadEtSubHeads() {
    const $sel = $('#etAccountHead');
    const parentId = $sel.find(':selected').data('id');
    const $sub  = $('#etSubAccountHead');
    const $hint = $('#etSubHint');
    $sub.html('<option value="">-- None --</option>');
    if (!parentId) { $hint.text('Select an Account Head first'); return; }
    $.get('api/account_heads.php', { action:'list', active_only:1, parent_id:parentId }, function(res){
      const subs = res.data || [];
      if (!subs.length) { $hint.text('No sub heads under this account head'); return; }
      subs.forEach(function(s){
        $sub.append($('<option>').val(s.account_name).text(s.account_name));
      });
      $hint.text(subs.length + ' sub head(s) available');
    });
  }

  $('#etAccountHead').on('change', loadEtSubHeads);

  $.get('api/expenditure_transfer.php', { action:'categories' }, function(res){
    const $sel = $('#etCategory');
    (res.data||[]).forEach(function(c){
      $sel.append($('<option>').val(c.id).text(c.name));
    });
  });

  // ── Load table ─────────────────────────────────────────────────────────────
  function loadTable() {
    const params = {
      action:      'list',
      transferred: showingTransferred ? 1 : 0,
      search:      $('#etSearch').val(),
      date_from:   $('#etDateFrom').val(),
      date_to:     $('#etDateTo').val(),
      category_id: $('#etCategory').val(),
    };
    $('#etTbody').html('<tr><td colspan="9" class="text-center text-muted py-4"><i class="bi bi-hourglass-split me-1"></i>Loading…</td></tr>');
    $.get('api/expenditure_transfer.php', params, function(res){
      allRows = res.data || [];
      renderTable(allRows);
      $('#etTotalBadge').text('Total: ' + allRows.length);
    }).fail(function(){ $('#etTbody').html('<tr><td colspan="9" class="text-danger text-center">Failed to load</td></tr>'); });
  }

  function fmt(n){ return 'LKR ' + parseFloat(n||0).toLocaleString('en-LK',{minimumFractionDigits:2,maximumFractionDigits:2}); }

  function renderTable(rows) {
    const $tb = $('#etTbody').empty();
    if (!rows.length) {
      $tb.html('<tr><td colspan="9" class="text-center text-muted py-4">No records found</td></tr>');
      return;
    }
    rows.forEach(function(r){
      const statusBadge = r.transferred_to_cashbook==1
        ? '<span class="badge bg-success">Transferred</span>'
        : '<span class="badge bg-warning text-dark">Pending</span>';
      const chk = r.transferred_to_cashbook==1 ? '' :
        `<input type="checkbox" class="form-check-input row-chk" data-id="${r.id}" data-amount="${r.amount}">`;
      const tr = `<tr data-id="${r.id}" data-amount="${r.amount}">
        <td>${chk}</td>
        <td class="text-nowrap">${r.expense_date}</td>
        <td><span class="badge bg-light text-dark border">${$('<div>').text(r.category_name||'').html()}</span></td>
        <td>${$('<div>').text(r.description||'').html()}</td>
        <td class="text-muted small">${$('<div>').text(r.vendor||'').html()}</td>
        <td class="text-muted small">${$('<div>').text(r.invoice_no||'').html()}</td>
        <td class="small">${$('<div>').text(r.payment_method||'').html()}</td>
        <td class="text-end fw-bold">${fmt(r.amount)}</td>
        <td>${statusBadge}</td>
      </tr>`;
      $tb.append(tr);
    });
    updateSelectionUI();
  }

  // ── Selection logic ────────────────────────────────────────────────────────
  function updateSelectionUI() {
    const checked = $('.row-chk:checked');
    const count = checked.length;
    let total = 0;
    checked.each(function(){ total += parseFloat($(this).data('amount')||0); });
    $('#etSelectedBadge').text('Selected: ' + count);
    $('#etAmountBadge').text('Amount: ' + fmt(total));
    $('#etSelCount').text(count);
    $('#transferSettingsBar').toggle(count > 0);
  }

  $(document).on('change', '.row-chk', updateSelectionUI);

  $('#chkSelectAll').on('change', function(){
    $('.row-chk').prop('checked', this.checked);
    updateSelectionUI();
  });

  $('#btnSelectAll').on('click', function(){ $('.row-chk').prop('checked',true); updateSelectionUI(); });
  $('#btnClearAll').on('click', function(){ $('.row-chk').prop('checked',false); $('#chkSelectAll').prop('checked',false); updateSelectionUI(); });

  // ── Filters ────────────────────────────────────────────────────────────────
  $('#btnEtFilter').on('click', loadTable);
  $('#etSearch').on('keydown', function(e){ if(e.key==='Enter') loadTable(); });
  $('#btnEtReset').on('click', function(){
    $('#etSearch,#etDateFrom,#etDateTo').val('');
    $('#etCategory').val('');
    loadTable();
  });

  // ── Transfer ────────────────────────────────────────────────────────────────
  $('#btnTransferSelected').on('click', function(){
    const ids = [];
    $('.row-chk:checked').each(function(){ ids.push($(this).data('id')); });
    if (!ids.length) { alert('Select at least one expenditure.'); return; }

    const bankId = $('#etBankAccount').val();
    const head   = $('#etAccountHead').val();
    if (!bankId) { alert('Please select a Bank Account.'); $('#etBankAccount').focus(); return; }
    if (!head)   { alert('Please select an Account Head.'); $('#etAccountHead').focus(); return; }

    const btn = $(this);
    btn.html('<i class="bi bi-hourglass-split me-1"></i>Transferring…').prop('disabled',true);

    const subHead = $('#etSubAccountHead').val();
    const payload = { action:'transfer', csrf:csrf, bank_account_id:bankId, account_head:head, sub_account_head:subHead };
    ids.forEach(function(id,i){ payload['ids['+i+']']=id; });

    $.post('api/expenditure_transfer.php', payload, function(res){
      btn.html('<i class="bi bi-arrow-right-circle me-1"></i>Transfer Selected (<span id="etSelCount">0</span>)').prop('disabled',false);
      alert(res.message);
      loadTable();
    }).fail(function(xhr){
      btn.html('<i class="bi bi-arrow-right-circle me-1"></i>Transfer Selected (<span id="etSelCount">0</span>)').prop('disabled',false);
      alert(xhr.responseJSON?.message || 'Transfer failed');
    });
  });

  // ── View Transferred ────────────────────────────────────────────────────────
  $('#btnShowTransferred').on('click', function(){
    $.get('api/expenditure_transfer.php', { action:'list', transferred:1 }, function(res){
      const $tb = $('#transferredTbody').empty();
      const rows = res.data || [];
      if (!rows.length) { $tb.html('<tr><td colspan="7" class="text-center text-muted py-3">None yet</td></tr>'); }
      rows.forEach(function(r){
        const undoBtn = isAdmin
          ? `<button class="btn btn-xs btn-outline-danger btn-sm btnUntransfer" data-id="${r.id}" title="Undo transfer"><i class="bi bi-arrow-counterclockwise"></i></button>`
          : '';
        const txLink = r.cashbook_transaction_id
          ? `<a href="index.php?page=transaction_history" class="badge bg-success">#${r.cashbook_transaction_id}</a>`
          : '<span class="text-muted">—</span>';
        const ahDisplay = r.cashbook_account_head
          ? `<span class="badge bg-primary">${$('<div>').text(r.cashbook_account_head).html()}</span>` : '<span class="text-muted">—</span>';
        const subDisplay = r.cashbook_sub_account_head
          ? `<span class="badge bg-info text-dark">${$('<div>').text(r.cashbook_sub_account_head).html()}</span>` : '<span class="text-muted">—</span>';
        $tb.append(`<tr>
          <td class="text-nowrap">${r.expense_date}</td>
          <td><span class="badge bg-light text-dark border">${$('<div>').text(r.category_name||'').html()}</span></td>
          <td>${$('<div>').text(r.description||'').html()}</td>
          <td class="text-muted small">${$('<div>').text(r.vendor||'').html()}</td>
          <td class="text-end fw-bold">${fmt(r.amount)}</td>
          <td>${ahDisplay}</td>
          <td>${subDisplay}</td>
          <td>${txLink}</td>
          <td>${undoBtn}</td>
        </tr>`);
      });
    });
    new bootstrap.Modal(document.getElementById('transferredModal')).show();
  });

  $(document).on('click', '.btnUntransfer', function(){
    const id = $(this).data('id');
    if (!confirm('Undo this transfer? The cash book transaction will be cancelled.')) return;
    $.post('api/expenditure_transfer.php', { action:'untransfer', csrf:csrf, id:id }, function(res){
      alert(res.message);
      $('#transferredModal').find('.btn-close').click();
      loadTable();
    }).fail(function(xhr){ alert(xhr.responseJSON?.message || 'Error'); });
  });

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