<?php require_once __DIR__ . '/../includes/auth.php'; 
require_login(); 
if (!has_role(['admin', 'super_admin', 'accountant', 'finance_manager'])) {
    header('Location: ?page=dashboard');
    exit;
}
?>
<div class="page-bank-reconciliation">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4 class="mb-0"><i class="bi bi-bank me-2"></i>Bank Reconciliation</h4>
      <div class="d-flex gap-2">
        <button class="btn btn-outline-secondary btn-sm" onclick="loadReconciliationData()">
          <i class="bi bi-arrow-repeat me-1"></i>Refresh
        </button>
      </div>
    </div>

    <!-- Summary Cards -->
    <div class="row g-3 mb-4">
      <div class="col-md-3">
        <div class="card border-primary">
          <div class="card-body text-center">
            <h6 class="text-muted">Bank Statement Balance</h6>
            <h3 class="text-primary" id="stmtBalance">LKR 0.00</h3>
            <small>Per uploaded statement</small>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card border-success">
          <div class="card-body text-center">
            <h6 class="text-muted">System Balance</h6>
            <h3 class="text-success" id="systemBalance">LKR 0.00</h3>
            <small>Per our records</small>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card border-info">
          <div class="card-body text-center">
            <h6 class="text-muted">Auto-Matched</h6>
            <h3 class="text-info" id="matchedCount">0</h3>
            <small id="matchedAmount">LKR 0.00</small>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card border-warning">
          <div class="card-body text-center">
            <h6 class="text-muted">Unmatched / Pending</h6>
            <h3 class="text-warning" id="unmatchedCount">0</h3>
            <small id="unmatchedAmount">LKR 0.00</small>
          </div>
        </div>
      </div>
    </div>

    <!-- Step 1: Select Bank Account & Upload -->
    <div class="card shadow-sm mb-4">
      <div class="card-header bg-primary text-white">
        <h6 class="mb-0"><i class="bi bi-upload me-2"></i>Step 1: Upload Bank Statement</h6>
      </div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label fw-bold">Select Bank Account <span class="text-danger">*</span></label>
            <select id="reconBankAccount" class="form-select" required>
              <option value="">-- Select Bank Account --</option>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label fw-bold">Statement Period <span class="text-danger">*</span></label>
            <div class="input-group">
              <input type="date" id="stmtDateFrom" class="form-control" required>
              <span class="input-group-text">to</span>
              <input type="date" id="stmtDateTo" class="form-control" required>
            </div>
          </div>
          <div class="col-md-4">
            <label class="form-label fw-bold">Upload Bank Statement (CSV) <span class="text-danger">*</span></label>
            <div class="input-group">
              <input type="file" id="stmtFile" class="form-control" accept=".csv,.xlsx,.xls" required>
              <button class="btn btn-success" type="button" id="btnProcessUpload">
                <i class="bi bi-upload me-1"></i>Process
              </button>
            </div>
            <div class="form-text">
              CSV format: Date, Reference, Description, Debit, Credit
              <a href="#" data-bs-toggle="modal" data-bs-target="#csvFormatModal">View sample format</a>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Step 2: Auto-Match Results -->
    <div class="row g-4">
      <!-- Matched Transactions -->
      <div class="col-md-6">
        <div class="card shadow-sm border-success">
          <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
            <h6 class="mb-0"><i class="bi bi-check-circle me-2"></i>Auto-Matched (Cleared)</h6>
            <span class="badge bg-light text-dark" id="matchedBadge">0</span>
          </div>
          <div class="card-body p-0">
            <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
              <table class="table table-sm table-hover mb-0" id="matchedTable">
                <thead class="table-light sticky-top">
                  <tr>
                    <th>Date</th>
                    <th>Reference</th>
                    <th class="text-end">Amount</th>
                    <th>Voucher</th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
          <div class="card-footer bg-light">
            <button class="btn btn-sm btn-outline-success w-100" id="btnConfirmMatched" disabled>
              <i class="bi bi-check-all me-1"></i>Confirm All Matched & Mark as Cleared
            </button>
          </div>
        </div>
      </div>

      <!-- Unmatched Transactions -->
      <div class="col-md-6">
        <div class="card shadow-sm border-warning">
          <div class="card-header bg-warning text-dark d-flex justify-content-between align-items-center">
            <h6 class="mb-0"><i class="bi bi-exclamation-triangle me-2"></i>Unmatched / Pending Review</h6>
            <span class="badge bg-dark" id="unmatchedBadge">0</span>
          </div>
          <div class="card-body p-0">
            <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
              <table class="table table-sm table-hover mb-0" id="unmatchedTable">
                <thead class="table-light sticky-top">
                  <tr>
                    <th>Source</th>
                    <th>Date</th>
                    <th>Reference</th>
                    <th class="text-end">Amount</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
          <div class="card-footer bg-light">
            <small class="text-muted">
              <i class="bi bi-info-circle me-1"></i>
              These items need manual review or may be timing differences
            </small>
          </div>
        </div>
      </div>
    </div>

    <!-- System Transactions Section -->
    <div class="card shadow-sm mt-4">
      <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
        <h6 class="mb-0"><i class="bi bi-journal-text me-2"></i>System Transactions (Uncleared)</h6>
        <div class="d-flex gap-2">
          <input type="text" id="searchSystemTxn" class="form-control form-control-sm" placeholder="Search voucher or reference...">
          <button class="btn btn-sm btn-light" onclick="loadSystemTransactions()">
            <i class="bi bi-arrow-repeat"></i>
          </button>
        </div>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive" style="max-height: 300px; overflow-y: auto;">
          <table class="table table-sm table-hover mb-0" id="systemTransactionsTable">
            <thead class="table-light sticky-top">
              <tr>
                <th>Voucher #</th>
                <th>Date</th>
                <th>Type</th>
                <th>Account Head</th>
                <th>Party</th>
                <th class="text-end">Amount</th>
                <th>Reference</th>
                <th class="text-center">Status</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Reconciliation Summary Report -->
    <div class="card shadow-sm mt-4 border-primary">
      <div class="card-header bg-primary text-white">
        <h6 class="mb-0"><i class="bi bi-calculator me-2"></i>Reconciliation Summary</h6>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-6">
            <table class="table table-sm table-borderless">
              <tbody>
                <tr>
                  <td>Bank Statement Opening Balance:</td>
                  <td class="text-end fw-bold" id="summaryStmtOpening">LKR 0.00</td>
                </tr>
                <tr>
                  <td>Add: Credits / Deposits:</td>
                  <td class="text-end text-success" id="summaryStmtCredits">+ LKR 0.00</td>
                </tr>
                <tr>
                  <td>Less: Debits / Withdrawals:</td>
                  <td class="text-end text-danger" id="summaryStmtDebits">- LKR 0.00</td>
                </tr>
                <tr class="border-top">
                  <td class="fw-bold">Bank Statement Closing Balance:</td>
                  <td class="text-end fw-bold" id="summaryStmtClosing">LKR 0.00</td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="col-md-6">
            <table class="table table-sm table-borderless">
              <tbody>
                <tr>
                  <td>System Book Balance:</td>
                  <td class="text-end fw-bold" id="summarySystemBalance">LKR 0.00</td>
                </tr>
                <tr>
                  <td>Less: Uncleared Debits:</td>
                  <td class="text-end text-danger" id="summaryUnclearedDr">- LKR 0.00</td>
                </tr>
                <tr>
                  <td>Add: Uncleared Credits:</td>
                  <td class="text-end text-success" id="summaryUnclearedCr">+ LKR 0.00</td>
                </tr>
                <tr class="border-top">
                  <td class="fw-bold">Adjusted Book Balance:</td>
                  <td class="text-end fw-bold" id="summaryAdjustedBalance">LKR 0.00</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="alert mt-3 mb-0" id="reconStatusAlert">
          <div class="d-flex justify-content-between align-items-center">
            <span><i class="bi bi-info-circle me-2"></i>Reconciliation Status:</span>
            <span class="fw-bold fs-5" id="reconStatusText">Please upload a bank statement to begin</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- CSV Format Modal -->
<div class="modal fade" id="csvFormatModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Bank Statement CSV Format</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p>Your CSV file should have the following columns:</p>
        <table class="table table-sm table-bordered">
          <thead class="table-light">
            <tr>
              <th>Column</th>
              <th>Description</th>
              <th>Example</th>
            </tr>
          </thead>
          <tbody>
            <tr><td><strong>Date</strong></td><td>Transaction date (YYYY-MM-DD)</td><td>2025-05-20</td></tr>
            <tr><td><strong>Reference</strong></td><td>Cheque/Ref number</td><td>CHQ-12345</td></tr>
            <tr><td><strong>Description</strong></td><td>Transaction description</td><td>Supplier Payment</td></tr>
            <tr><td><strong>Debit</strong></td><td>Amount withdrawn (out)</td><td>5000.00</td></tr>
            <tr><td><strong>Credit</strong></td><td>Amount deposited (in)</td><td>25000.00</td></tr>
          </tbody>
        </table>
        <h6>Sample CSV Content:</h6>
        <pre class="bg-light p-2 rounded"><code>Date,Reference,Description,Debit,Credit
2025-05-20,CHQ-001,Customer Payment,,50000.00
2025-05-20,CHQ-002,Supplier Payment,25000.00,
2025-05-21,ONL-003,Online Transfer,,100000.00</code></pre>
      </div>
    </div>
  </div>
</div>

<!-- Manual Match Modal -->
<div class="modal fade" id="manualMatchModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-warning">
        <h5 class="modal-title"><i class="bi bi-hand-index-thumb me-2"></i>Manual Match</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="manualMatchStmtId">
        <div class="row">
          <div class="col-md-6">
            <h6>Bank Statement Line:</h6>
            <div class="border rounded p-2 bg-light mb-3">
              <div id="manualStmtDetails"></div>
            </div>
          </div>
          <div class="col-md-6">
            <h6>Select Matching System Transaction:</h6>
            <div class="input-group mb-2">
              <input type="text" id="searchMatchTxn" class="form-control form-control-sm" placeholder="Search by voucher, reference or amount...">
              <button class="btn btn-sm btn-outline-secondary" onclick="searchMatchableTransactions()">Search</button>
            </div>
            <div class="table-responsive" style="max-height: 300px;">
              <table class="table table-sm table-hover" id="matchableTransactionsTable">
                <thead class="table-light">
                  <tr>
                    <th></th>
                    <th>Date</th>
                    <th>Voucher</th>
                    <th>Ref</th>
                    <th class="text-end">Amount</th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="btnConfirmManualMatch" disabled>
          <i class="bi bi-link me-1"></i>Confirm Match & Mark as Cleared
        </button>
      </div>
    </div>
  </div>
</div>

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

  const csrf = '<?php echo htmlspecialchars(csrf_token()); ?>';
  let currentReconData = null;
  let selectedMatchTransaction = null;

  // Format currency
  function formatCurrency(amount) {
    return 'LKR ' + parseFloat(amount || 0).toLocaleString('en-LK', {minimumFractionDigits: 2, maximumFractionDigits: 2});
  }

  // Escape HTML
  function escapeHtml(text) {
    if (!text) return '';
    return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  }

  // Load bank accounts
  function loadBankAccounts() {
    $.get('api/finance.php', { action: 'list_bank_accounts', is_active: 1 }, function(res) {
      const $select = $('#reconBankAccount');
      $select.html('<option value="">-- Select Bank Account --</option>');
      
      (res.data || []).forEach(function(acc) {
        const balance = parseFloat(acc.current_balance || 0).toLocaleString('en-LK', {minimumFractionDigits: 2});
        $select.append(`<option value="${acc.id}" data-currency="${acc.currency}" data-balance="${acc.current_balance}">
          ${escapeHtml(acc.account_name)} - ${escapeHtml(acc.bank_name)} [${acc.currency} ${balance}]
        </option>`);
      });
    });
  }

  // Process uploaded file
  function processUpload() {
    const bankAccountId = $('#reconBankAccount').val();
    const dateFrom = $('#stmtDateFrom').val();
    const dateTo = $('#stmtDateTo').val();
    const fileInput = $('#stmtFile')[0];

    if (!bankAccountId || !dateFrom || !dateTo) {
      alert('Please select bank account and statement period');
      return;
    }

    if (!fileInput.files.length) {
      alert('Please select a CSV file to upload');
      return;
    }

    const file = fileInput.files[0];
    const reader = new FileReader();

    reader.onload = function(e) {
      const csvData = e.target.result;
      
      // Parse CSV
      const lines = csvData.split('\n').filter(line => line.trim());
      const headers = lines[0].split(',').map(h => h.trim().toLowerCase());
      
      const stmtLines = [];
      let totalCredits = 0;
      let totalDebits = 0;

      for (let i = 1; i < lines.length; i++) {
        const cols = lines[i].split(',');
        if (cols.length >= 2) {
          const date = cols[0]?.trim();
          const reference = cols[1]?.trim();
          const description = cols[2]?.trim() || '';
          const debit = parseFloat(cols[3]) || 0;
          const credit = parseFloat(cols[4]) || 0;
          const amount = credit > 0 ? credit : (debit > 0 ? -debit : 0);
          
          if (date && (debit > 0 || credit > 0)) {
            stmtLines.push({
              line_no: i,
              date: date,
              reference: reference,
              description: description,
              debit: debit,
              credit: credit,
              amount: amount
            });
            
            if (credit > 0) totalCredits += credit;
            if (debit > 0) totalDebits += debit;
          }
        }
      }

      // Send to API for auto-matching
      const formData = new FormData();
      formData.append('action', 'process_reconciliation');
      formData.append('csrf', csrf);
      formData.append('bank_account_id', bankAccountId);
      formData.append('date_from', dateFrom);
      formData.append('date_to', dateTo);
      formData.append('statement_data', JSON.stringify(stmtLines));
      formData.append('total_credits', totalCredits);
      formData.append('total_debits', totalDebits);

      $.ajax({
        url: 'api/reconciliation.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(res) {
          currentReconData = res.data;
          displayReconciliationResults(res.data);
        },
        error: function(xhr) {
          alert('Error: ' + (xhr.responseJSON?.message || 'Failed to process statement'));
        }
      });
    };

    reader.readAsText(file);
  }

  // Display reconciliation results
  function displayReconciliationResults(data) {
    // Update summary cards
    $('#stmtBalance').text(formatCurrency(data.statement_balance));
    $('#systemBalance').text(formatCurrency(data.system_balance));
    $('#matchedCount').text(data.matched.length);
    $('#matchedAmount').text(formatCurrency(data.matched.reduce((sum, m) => sum + Math.abs(m.amount), 0)));
    $('#unmatchedCount').text(data.unmatched.length);
    $('#unmatchedAmount').text(formatCurrency(data.unmatched.reduce((sum, u) => sum + Math.abs(u.amount), 0)));

    // Update badges
    $('#matchedBadge').text(data.matched.length);
    $('#unmatchedBadge').text(data.unmatched.length);

    // Display matched
    const $matchedBody = $('#matchedTable tbody');
    $matchedBody.empty();
    data.matched.forEach(function(item) {
      const row = `
        <tr>
          <td>${item.date}</td>
          <td><code>${escapeHtml(item.reference)}</code></td>
          <td class="text-end ${item.amount >= 0 ? 'text-success' : 'text-danger'}">
            ${formatCurrency(Math.abs(item.amount))} ${item.amount >= 0 ? '(Cr)' : '(Dr)'}
          </td>
          <td><span class="badge bg-primary">${escapeHtml(item.voucher_number)}</span></td>
        </tr>
      `;
      $matchedBody.append(row);
    });

    if (data.matched.length === 0) {
      $matchedBody.append('<tr><td colspan="4" class="text-center text-muted py-3">No matched transactions</td></tr>');
    }

    // Enable confirm button if there are matches
    $('#btnConfirmMatched').prop('disabled', data.matched.length === 0);

    // Display unmatched
    const $unmatchedBody = $('#unmatchedTable tbody');
    $unmatchedBody.empty();
    data.unmatched.forEach(function(item) {
      const isStmt = item.source === 'statement';
      const row = `
        <tr>
          <td><span class="badge ${isStmt ? 'bg-info' : 'bg-secondary'}">${item.source}</span></td>
          <td>${item.date}</td>
          <td><code>${escapeHtml(item.reference || '-')}</code></td>
          <td class="text-end ${item.amount >= 0 ? 'text-success' : 'text-danger'}">
            ${formatCurrency(Math.abs(item.amount))} ${item.amount >= 0 ? '(Cr)' : '(Dr)'}
          </td>
          <td>
            ${isStmt ? 
              `<button class="btn btn-sm btn-outline-primary" onclick="openManualMatch(${item.id})">
                <i class="bi bi-hand-index-thumb me-1"></i>Match
              </button>` :
              `<span class="badge bg-warning">Pending</span>`
            }
          </td>
        </tr>
      `;
      $unmatchedBody.append(row);
    });

    if (data.unmatched.length === 0) {
      $unmatchedBody.append('<tr><td colspan="5" class="text-center text-muted py-3">No unmatched transactions</td></tr>');
    }

    // Update summary report
    $('#summaryStmtOpening').text(formatCurrency(data.statement_opening));
    $('#summaryStmtCredits').text('+ ' + formatCurrency(data.total_credits));
    $('#summaryStmtDebits').text('- ' + formatCurrency(data.total_debits));
    $('#summaryStmtClosing').text(formatCurrency(data.statement_balance));
    $('#summarySystemBalance').text(formatCurrency(data.system_balance));
    $('#summaryUnclearedDr').text('- ' + formatCurrency(data.uncleared_dr));
    $('#summaryUnclearedCr').text('+ ' + formatCurrency(data.uncleared_cr));
    $('#summaryAdjustedBalance').text(formatCurrency(data.adjusted_balance));

    // Update status
    const variance = Math.abs(data.statement_balance - data.adjusted_balance);
    if (variance < 0.01) {
      $('#reconStatusAlert').removeClass('alert-warning alert-danger').addClass('alert-success');
      $('#reconStatusText').html('<i class="bi bi-check-circle me-2"></i>RECONCILED - Balances Match');
    } else {
      $('#reconStatusAlert').removeClass('alert-success alert-warning').addClass('alert-danger');
      $('#reconStatusText').html('<i class="bi bi-x-circle me-2"></i>NOT RECONCILED - Variance: ' + formatCurrency(variance));
    }

    // Load system transactions
    loadSystemTransactions();
  }

  // Load uncleared system transactions
  function loadSystemTransactions() {
    const bankAccountId = $('#reconBankAccount').val();
    if (!bankAccountId) return;

    const dateFrom = $('#stmtDateFrom').val() || new Date(new Date().setDate(new Date().getDate() - 30)).toISOString().split('T')[0];
    const dateTo = $('#stmtDateTo').val() || new Date().toISOString().split('T')[0];

    $.get('api/transactions.php', {
      action: 'list',
      bank_account_id: bankAccountId,
      date_from: dateFrom,
      date_to: dateTo,
      is_reconciled: 0,
      is_cancelled: 0
    }, function(res) {
      const $tbody = $('#systemTransactionsTable tbody');
      $tbody.empty();
      
      const searchTerm = $('#searchSystemTxn').val().toLowerCase();
      
      (res.data || []).forEach(function(txn) {
        // Filter by search term if provided
        if (searchTerm) {
          const searchable = (txn.voucher_number + txn.document_reference + txn.party_name).toLowerCase();
          if (!searchable.includes(searchTerm)) return;
        }

        const amount = parseFloat(txn.amount || 0);
        const row = `
          <tr>
            <td><code class="fw-bold text-primary">${escapeHtml(txn.voucher_number)}</code></td>
            <td>${txn.transaction_date}</td>
            <td><span class="badge ${txn.transaction_type === 'Receipt' ? 'bg-info' : (txn.transaction_type === 'Payment' ? 'bg-warning text-dark' : 'bg-secondary')}">${txn.transaction_type}</span></td>
            <td>${escapeHtml(txn.account_head)}</td>
            <td>${escapeHtml(txn.party_name || '-')}</td>
            <td class="text-end fw-bold">${formatCurrency(amount)}</td>
            <td><small>${escapeHtml(txn.document_reference || '-')}</small></td>
            <td class="text-center"><span class="badge bg-warning">Pending</span></td>
            <td>
              <button class="btn btn-sm btn-outline-success" onclick="manualClearTransaction(${txn.id})">
                <i class="bi bi-check"></i> Clear
              </button>
            </td>
          </tr>
        `;
        $tbody.append(row);
      });

      if ($tbody.children().length === 0) {
        $tbody.append('<tr><td colspan="9" class="text-center text-muted py-3">No uncleared transactions found</td></tr>');
      }
    });
  }

  // Confirm matched transactions as cleared
  function confirmMatched() {
    if (!currentReconData || !currentReconData.matched.length) return;

    if (!confirm(`Mark ${currentReconData.matched.length} matched transactions as Cleared?`)) return;

    const formData = new FormData();
    formData.append('action', 'confirm_reconciliation');
    formData.append('csrf', csrf);
    formData.append('matches', JSON.stringify(currentReconData.matched));

    $.ajax({
      url: 'api/reconciliation.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(res) {
        alert(`${res.cleared_count} transactions marked as Cleared!`);
        loadSystemTransactions();
        $('#btnConfirmMatched').prop('disabled', true);
      },
      error: function(xhr) {
        alert('Error: ' + (xhr.responseJSON?.message || 'Failed to confirm'));
      }
    });
  }

  // Open manual match modal
  function openManualMatch(stmtLineId) {
    if (!currentReconData) return;
    
    const stmtLine = currentReconData.unmatched.find(u => u.id === stmtLineId && u.source === 'statement');
    if (!stmtLine) return;

    $('#manualMatchStmtId').val(stmtLineId);
    $('#manualStmtDetails').html(`
      <p><strong>Date:</strong> ${stmtLine.date}</p>
      <p><strong>Reference:</strong> ${escapeHtml(stmtLine.reference)}</p>
      <p><strong>Description:</strong> ${escapeHtml(stmtLine.description)}</p>
      <p><strong>Amount:</strong> <span class="${stmtLine.amount >= 0 ? 'text-success' : 'text-danger'} fs-5">
        ${formatCurrency(Math.abs(stmtLine.amount))} ${stmtLine.amount >= 0 ? '(Credit)' : '(Debit)'}
      </span></p>
    `);

    $('#manualMatchModal').modal('show');
    searchMatchableTransactions();
  }

  // Search matchable transactions
  function searchMatchableTransactions() {
    const bankAccountId = $('#reconBankAccount').val();
    const searchTerm = $('#searchMatchTxn').val();
    const stmtLineId = $('#manualMatchStmtId').val();
    
    if (!currentReconData || !stmtLineId) return;
    
    const stmtLine = currentReconData.unmatched.find(u => u.id == stmtLineId);
    if (!stmtLine) return;

    // Load potential matches
    $.get('api/transactions.php', {
      action: 'list',
      bank_account_id: bankAccountId,
      date_from: stmtLine.date,
      date_to: stmtLine.date,
      is_reconciled: 0,
      is_cancelled: 0
    }, function(res) {
      const $tbody = $('#matchableTransactionsTable tbody');
      $tbody.empty();
      
      (res.data || []).forEach(function(txn) {
        const amount = parseFloat(txn.amount || 0);
        const amountMatch = Math.abs(Math.abs(amount) - Math.abs(stmtLine.amount)) < 0.01;
        
        const row = `
          <tr class="${amountMatch ? 'table-success' : ''}">
            <td>
              <input type="radio" name="matchTransaction" value="${txn.id}" 
                onchange="selectMatchTransaction(${txn.id}, '${escapeHtml(txn.voucher_number)}', ${amount})"
                ${amountMatch ? 'checked' : ''}>
            </td>
            <td>${txn.transaction_date}</td>
            <td><code>${escapeHtml(txn.voucher_number)}</code></td>
            <td><small>${escapeHtml(txn.document_reference || '-')}</small></td>
            <td class="text-end ${amountMatch ? 'fw-bold' : ''}">${formatCurrency(amount)}</td>
          </tr>
        `;
        $tbody.append(row);
      });

      if ($tbody.children().length === 0) {
        $tbody.append('<tr><td colspan="5" class="text-center text-muted">No matching transactions found</td></tr>');
      }
    });
  }

  // Select match transaction
  function selectMatchTransaction(id, voucher, amount) {
    selectedMatchTransaction = { id, voucher, amount };
    $('#btnConfirmManualMatch').prop('disabled', false);
  }

  // Confirm manual match
  function confirmManualMatch() {
    if (!selectedMatchTransaction) return;

    const stmtLineId = $('#manualMatchStmtId').val();
    
    const formData = new FormData();
    formData.append('action', 'manual_match');
    formData.append('csrf', csrf);
    formData.append('statement_id', stmtLineId);
    formData.append('transaction_id', selectedMatchTransaction.id);

    $.ajax({
      url: 'api/reconciliation.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(res) {
        $('#manualMatchModal').modal('hide');
        alert('Transaction matched and marked as Cleared!');
        
        // Refresh display
        if (currentReconData) {
          // Remove from unmatched
          currentReconData.unmatched = currentReconData.unmatched.filter(u => u.id != stmtLineId);
          // Add to matched
          currentReconData.matched.push(res.data);
          displayReconciliationResults(currentReconData);
        }
      },
      error: function(xhr) {
        alert('Error: ' + (xhr.responseJSON?.message || 'Failed to match'));
      }
    });
  }

  // Manual clear a transaction
  function manualClearTransaction(transactionId) {
    if (!confirm('Mark this transaction as Cleared without bank statement match?')) return;

    const formData = new FormData();
    formData.append('action', 'manual_clear');
    formData.append('csrf', csrf);
    formData.append('transaction_id', transactionId);

    $.ajax({
      url: 'api/reconciliation.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function() {
        alert('Transaction marked as Cleared!');
        loadSystemTransactions();
      },
      error: function(xhr) {
        alert('Error: ' + (xhr.responseJSON?.message || 'Failed to clear'));
      }
    });
  }

  // Set default dates
  function setDefaultDates() {
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    $('#stmtDateTo').val(today.toISOString().split('T')[0]);
    $('#stmtDateFrom').val(firstDay.toISOString().split('T')[0]);
  }

  // Event handlers
  $('#btnProcessUpload').on('click', processUpload);
  $('#btnConfirmMatched').on('click', confirmMatched);
  $('#btnConfirmManualMatch').on('click', confirmManualMatch);
  $('#searchSystemTxn').on('input', loadSystemTransactions);
  $('#searchMatchTxn').on('keypress', function(e) {
    if (e.which === 13) searchMatchableTransactions();
  });

  // Initialize
  loadBankAccounts();
  setDefaultDates();

  // Expose functions globally for onclick handlers
  window.openManualMatch = openManualMatch;
  window.selectMatchTransaction = selectMatchTransaction;
  window.searchMatchableTransactions = searchMatchableTransactions;
  window.manualClearTransaction = manualClearTransaction;
  window.loadSystemTransactions = loadSystemTransactions;
})();
</script>
