<?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-finance-realtime-dashboard">
  <div class="container-fluid p-4">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
      <h4 class="mb-0"><i class="bi bi-graph-up-arrow me-2"></i>Real-Time Finance Dashboard</h4>
      <div class="d-flex gap-2">
        <span class="badge bg-success fs-6"><i class="bi bi-circle-fill me-1 small"></i>Live</span>
        <button class="btn btn-outline-primary btn-sm" onclick="refreshAllData()">
          <i class="bi bi-arrow-clockwise me-1"></i>Refresh Now
        </button>
      </div>
    </div>

    <!-- Section 1: Bank Accounts Summary Cards -->
    <div class="card shadow-sm mb-4 border-primary">
      <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-bank me-2"></i>Bank Accounts Overview</h5>
        <div class="d-flex gap-2">
          <span class="badge bg-light text-dark" id="totalAccountsBadge">0 Accounts</span>
          <span class="badge bg-warning" id="totalFundsBadge">LKR 0.00</span>
        </div>
      </div>
      <div class="card-body">
        <div class="row g-3" id="bankAccountsContainer">
          <!-- Bank account cards will be loaded here -->
          <div class="col-12 text-center py-4 text-muted">
            <div class="spinner-border spinner-border-sm me-2"></div>
            Loading bank accounts...
          </div>
        </div>
      </div>
    </div>

    <!-- Section 2: Cash Flow Report -->
    <div class="card shadow-sm">
      <div class="card-header bg-success text-white">
        <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
          <h5 class="mb-0"><i class="bi bi-cash-stack me-2"></i>Cash Flow Report</h5>
          <div class="d-flex gap-2 align-items-center flex-wrap">
            <!-- Petty Cash Toggle -->
            <div class="form-check form-switch text-white me-2">
              <input class="form-check-input" type="checkbox" id="includePettyCash" onchange="loadCashFlowReport()">
              <label class="form-check-label" for="includePettyCash">
                <i class="bi bi-wallet me-1"></i>Include Petty Cash
              </label>
            </div>
            <!-- Date Range Filter -->
            <div class="input-group input-group-sm" style="width: auto;">
              <span class="input-group-text bg-light"><i class="bi bi-calendar3"></i></span>
              <input type="date" id="cashFlowDateFrom" class="form-control" value="<?php echo date('Y-m-01'); ?>">
              <span class="input-group-text bg-light">to</span>
              <input type="date" id="cashFlowDateTo" class="form-control" value="<?php echo date('Y-m-d'); ?>">
              <button class="btn btn-light" type="button" onclick="loadCashFlowReport()">
                <i class="bi bi-search"></i> Filter
              </button>
            </div>
            <button class="btn btn-sm btn-outline-light" onclick="exportCashFlow()">
              <i class="bi bi-download me-1"></i>Export
            </button>
          </div>
        </div>
      </div>
      <div class="card-body p-0">
        <!-- Cash Flow Summary Row -->
        <div class="bg-light border-bottom p-3">
          <div class="row g-2">
            <div class="col-md-3">
              <div class="d-flex justify-content-between">
                <span class="text-muted">Opening Balance:</span>
                <strong id="cfOpeningBalance">LKR 0.00</strong>
              </div>
            </div>
            <div class="col-md-3">
              <div class="d-flex justify-content-between">
                <span class="text-success">Total Receipts (+):</span>
                <strong class="text-success" id="cfTotalReceipts">+ LKR 0.00</strong>
              </div>
            </div>
            <div class="col-md-3">
              <div class="d-flex justify-content-between">
                <span class="text-danger">Total Payments (-):</span>
                <strong class="text-danger" id="cfTotalPayments">- LKR 0.00</strong>
              </div>
            </div>
            <div class="col-md-3">
              <div class="d-flex justify-content-between">
                <span class="text-primary">Closing Balance:</span>
                <strong class="text-primary" id="cfClosingBalance">LKR 0.00</strong>
              </div>
            </div>
          </div>
        </div>

        <!-- Cash Flow Data Table -->
        <div class="table-responsive" style="max-height: 600px; overflow-y: auto;">
          <table class="table table-hover table-sm mb-0" id="cashFlowTable">
            <thead class="table-dark sticky-top">
              <tr>
                <th style="width: 80px;">Date</th>
                <th style="width: 120px;">Voucher #</th>
                <th style="width: 100px;">Type</th>
                <th style="width: 150px;">Source</th>
                <th>Description / Party</th>
                <th style="width: 120px;">Account</th>
                <th class="text-end" style="width: 120px;">Receipt (+)</th>
                <th class="text-end" style="width: 120px;">Payment (-)</th>
                <th class="text-end" style="width: 130px;">Running Balance</th>
                <th style="width: 80px;">Status</th>
              </tr>
            </thead>
            <tbody id="cashFlowTableBody">
              <tr>
                <td colspan="10" class="text-center text-muted py-4">
                  <div class="spinner-border spinner-border-sm me-2"></div>
                  Loading cash flow data...
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Quick Links -->
    <div class="row g-3 mt-3">
      <div class="col-md-3">
        <a href="?page=cash_book_entry" class="card text-decoration-none text-dark h-100">
          <div class="card-body text-center">
            <i class="bi bi-journal-plus fs-1 text-primary mb-2"></i>
            <h6>New Transaction</h6>
            <small class="text-muted">Create cash book entry</small>
          </div>
        </a>
      </div>
      <div class="col-md-3">
        <a href="?page=bank_reconciliation" class="card text-decoration-none text-dark h-100">
          <div class="card-body text-center">
            <i class="bi bi-bank fs-1 text-success mb-2"></i>
            <h6>Reconciliation</h6>
            <small class="text-muted">Match bank statements</small>
          </div>
        </a>
      </div>
      <div class="col-md-3">
        <a href="?page=finance_manager_dashboard" class="card text-decoration-none text-dark h-100">
          <div class="card-body text-center">
            <i class="bi bi-shield-check fs-1 text-warning mb-2"></i>
            <h6>Approvals</h6>
            <small class="text-muted">Review pending vouchers</small>
          </div>
        </a>
      </div>
      <div class="col-md-3">
        <a href="?page=petty_cash" class="card text-decoration-none text-dark h-100">
          <div class="card-body text-center">
            <i class="bi bi-wallet fs-1 text-secondary mb-2"></i>
            <h6>Petty Cash</h6>
            <small class="text-muted">Imprest system</small>
          </div>
        </a>
      </div>
    </div>
  </div>
</div>

<script>
(function() {
  if (!$('.page-finance-realtime-dashboard').length) return;

  const csrf = '<?php echo htmlspecialchars(csrf_token()); ?>';
  let allBankAccounts = [];
  let cashFlowData = [];

  // Format currency
  function formatCurrency(amount, currency) {
    const symbol = currency === 'USD' ? '$' : 'LKR';
    return symbol + ' ' + 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;');
  }

  // Get type badge
  function getTypeBadge(type) {
    const badges = {
      'Receipt': '<span class="badge bg-info"><i class="bi bi-arrow-down-left me-1"></i>Receipt</span>',
      'Payment': '<span class="badge bg-warning text-dark"><i class="bi bi-arrow-up-right me-1"></i>Payment</span>',
      'Contra': '<span class="badge bg-secondary"><i class="bi bi-arrow-left-right me-1"></i>Contra</span>',
      'Journal': '<span class="badge bg-primary"><i class="bi bi-journal-text me-1"></i>Journal</span>',
      'Invoice': '<span class="badge bg-success"><i class="bi bi-receipt me-1"></i>Invoice</span>',
      'Expense': '<span class="badge bg-danger"><i class="bi bi-cash-stack me-1"></i>Expense</span>'
    };
    return badges[type] || '<span class="badge bg-light text-dark">' + type + '</span>';
  }

  // Load bank accounts summary (including petty cash)
  function loadBankAccounts() {
    $.when(
      $.get('api/finance.php', { action: 'list_bank_accounts', is_active: 1 }),
      $.get('api/petty_cash.php', { action: 'get_float_status' })
    ).done(function(bankRes, pettyRes) {
      allBankAccounts = bankRes[0].data || [];
      const pettyCashFloats = pettyRes[0].data || [];
      
      const $container = $('#bankAccountsContainer');
      $container.empty();

      let totalLKR = 0;
      let totalUSD = 0;
      let pettyCashTotal = 0;

      // Render Bank Accounts
      if (allBankAccounts.length === 0 && pettyCashFloats.length === 0) {
        $container.html('<div class="col-12 text-center text-muted py-4">No bank accounts or petty cash configured</div>');
        return;
      }

      // Add Petty Cash Floats first
      pettyCashFloats.forEach(function(float) {
        const currentBalance = parseFloat(float.current_balance || 0);
        const floatLimit = parseFloat(float.float_limit || 0);
        const utilizationPercent = floatLimit > 0 ? (currentBalance / floatLimit * 100) : 0;
        
        pettyCashTotal += currentBalance;

        const balanceStatusClass = float.balance_status === 'CRITICAL' ? 'border-danger' : 
                                   (float.balance_status === 'LOW' ? 'border-warning' : 'border-success');
        const balanceTextClass = float.balance_status === 'CRITICAL' ? 'text-danger' : 
                                 (float.balance_status === 'LOW' ? 'text-warning' : 'text-success');

        const card = `
          <div class="col-md-6 col-lg-4 col-xl-3">
            <div class="card h-100 ${balanceStatusClass} border-2 shadow-sm">
              <div class="card-header bg-warning bg-opacity-25 d-flex justify-content-between align-items-center py-2">
                <strong class="text-truncate" title="${escapeHtml(float.float_name)}">
                  <i class="bi bi-wallet me-1"></i>${escapeHtml(float.float_name)}
                </strong>
                <span class="badge bg-warning text-dark">Petty Cash</span>
              </div>
              <div class="card-body">
                <div class="mb-2">
                  <small class="text-muted">Float Limit</small>
                  <div class="font-monospace">${formatCurrency(floatLimit, 'LKR')}</div>
                </div>
                <div class="mb-2">
                  <small class="text-muted">Cost Center</small>
                  <div>${escapeHtml(float.cost_center || '-')}</div>
                </div>
                <div class="row g-2 mt-1">
                  <div class="col-6">
                    <small class="text-muted d-block">Current</small>
                    <strong class="${balanceTextClass}">${formatCurrency(currentBalance, 'LKR')}</strong>
                  </div>
                  <div class="col-6 text-end">
                    <small class="text-muted d-block">Status</small>
                    <span class="badge ${float.balance_status === 'NORMAL' ? 'bg-success' : (float.balance_status === 'LOW' ? 'bg-warning' : 'bg-danger')}">${float.balance_status}</span>
                  </div>
                </div>
                <div class="mt-2 pt-2 border-top">
                  <small class="text-muted">Utilization: ${utilizationPercent.toFixed(1)}%</small>
                  <div class="progress" style="height: 4px;">
                    <div class="progress-bar ${utilizationPercent > 80 ? 'bg-danger' : (utilizationPercent > 50 ? 'bg-warning' : 'bg-success')}" style="width: ${Math.min(100, utilizationPercent)}%"></div>
                  </div>
                </div>
              </div>
              <div class="card-footer bg-light py-1">
                <small class="text-muted">
                  <i class="bi bi-circle-fill small me-1" style="color: ${float.is_active ? '#28a745' : '#dc3545'}"></i>
                  ${float.is_active ? 'Active' : 'Inactive'} Imprest
                </small>
              </div>
            </div>
          </div>
        `;
        $container.append(card);
      });

      // Add Bank Accounts
      allBankAccounts.forEach(function(acc) {
        const initialBalance = parseFloat(acc.initial_balance || 0);
        const currentBalance = parseFloat(acc.current_balance || 0);
        const variance = currentBalance - initialBalance;
        const varianceClass = variance >= 0 ? 'text-success' : 'text-danger';
        const varianceIcon = variance >= 0 ? 'bi-arrow-up-short' : 'bi-arrow-down-short';

        if (acc.currency === 'LKR') {
          totalLKR += currentBalance;
        } else if (acc.currency === 'USD') {
          totalUSD += currentBalance;
        }

        const card = `
          <div class="col-md-6 col-lg-4 col-xl-3">
            <div class="card h-100 border-0 shadow-sm">
              <div class="card-header bg-light d-flex justify-content-between align-items-center py-2">
                <strong class="text-truncate" title="${escapeHtml(acc.account_name)}">
                  <i class="bi bi-bank me-1"></i>${escapeHtml(acc.account_name)}
                </strong>
                ${acc.is_default == 1 ? '<span class="badge bg-primary">Default</span>' : ''}
              </div>
              <div class="card-body">
                <div class="mb-2">
                  <small class="text-muted">Account Number</small>
                  <div class="font-monospace">${escapeHtml(acc.account_number)}</div>
                </div>
                <div class="mb-2">
                  <small class="text-muted">Bank</small>
                  <div>${escapeHtml(acc.bank_name || '-')}</div>
                </div>
                <div class="row g-2 mt-1">
                  <div class="col-6">
                    <small class="text-muted d-block">Initial</small>
                    <strong class="text-secondary">${formatCurrency(initialBalance, acc.currency)}</strong>
                  </div>
                  <div class="col-6 text-end">
                    <small class="text-muted d-block">Current</small>
                    <strong class="${currentBalance >= 0 ? 'text-success' : 'text-danger'}">${formatCurrency(currentBalance, acc.currency)}</strong>
                  </div>
                </div>
                <div class="mt-2 pt-2 border-top">
                  <small class="text-muted">Variance: </small>
                  <span class="${varianceClass}">
                    <i class="bi ${varianceIcon}"></i>${formatCurrency(Math.abs(variance), acc.currency)}
                  </span>
                </div>
              </div>
              <div class="card-footer bg-light py-1">
                <small class="text-muted">
                  <i class="bi bi-circle-fill small me-1" style="color: ${acc.is_active ? '#28a745' : '#dc3545'}"></i>
                  ${acc.is_active ? 'Active' : 'Inactive'} Bank
                </small>
              </div>
            </div>
          </div>
        `;
        $container.append(card);
      });

      // Update summary badges
      const totalAccounts = allBankAccounts.length + pettyCashFloats.length;
      $('#totalAccountsBadge').text(`${totalAccounts} Accounts (Bank: ${allBankAccounts.length}, Petty: ${pettyCashFloats.length})`);
      $('#totalFundsBadge').text(`Bank: ${formatCurrency(totalLKR, 'LKR')} | Petty: ${formatCurrency(pettyCashTotal, 'LKR')}`);
    }).fail(function(xhr) {
      $('#bankAccountsContainer').html('<div class="col-12 text-center text-danger py-4">Failed to load accounts</div>');
    });
  }

  // Load cash flow report
  function loadCashFlowReport() {
    const dateFrom = $('#cashFlowDateFrom').val();
    const dateTo = $('#cashFlowDateTo').val();
    const includePettyCash = $('#includePettyCash').prop('checked');

    if (!dateFrom || !dateTo) {
      alert('Please select a date range');
      return;
    }

    const $tbody = $('#cashFlowTableBody');
    $tbody.html('<tr><td colspan="10" class="text-center py-4"><div class="spinner-border spinner-border-sm me-2"></div>Loading cash flow data...</td></tr>');

    // Prepare API calls
    const apiCalls = [
      $.get('api/transactions.php', { action: 'list', date_from: dateFrom, date_to: dateTo, approval_status: 'Approved', is_cancelled: 0 }),
      $.get('api/finance.php', { action: 'get_finance_summary', date_from: dateFrom, date_to: dateTo })
    ];
    
    // Add petty cash vouchers if enabled
    if (includePettyCash) {
      apiCalls.push($.get('api/petty_cash.php', { action: 'list_vouchers', date_from: dateFrom, date_to: dateTo, status: 'Posted' }));
    }

    // Fetch all transaction types
    $.when.apply($, apiCalls).done(function() {
      const transactionsRes = arguments[0];
      const summaryRes = arguments[1];
      const pettyRes = includePettyCash ? arguments[2] : null;
      
      let transactions = transactionsRes[0].data || [];
      const summary = summaryRes[0];
      
      // Add petty cash vouchers to transactions if enabled
      if (includePettyCash && pettyRes) {
        const pettyVouchers = pettyRes[0].data || [];
        pettyVouchers.forEach(function(v) {
          transactions.push({
            id: 'PC-' + v.id,
            voucher_number: v.voucher_number,
            transaction_date: v.voucher_date,
            transaction_type: 'Payment',
            account_head: v.expense_account_head,
            bank_account_name: v.float_name + ' (Petty Cash)',
            party_name: v.recipient_name,
            narration: v.narration,
            amount: v.amount,
            document_reference: 'Petty Cash Voucher',
            is_reconciled: 1, // Posted vouchers are considered reconciled
            source: 'petty_cash'
          });
        });
      }

      // Sort by date
      transactions.sort(function(a, b) {
        return new Date(a.transaction_date) - new Date(b.transaction_date);
      });

      // Calculate opening balance (balance before dateFrom)
      let runningBalance = 0;

      $tbody.empty();

      let totalReceipts = 0;
      let totalPayments = 0;

      if (transactions.length === 0) {
        $tbody.html('<tr><td colspan="10" class="text-center text-muted py-4">No transactions found for the selected period</td></tr>');
      } else {
        transactions.forEach(function(txn, index) {
          const amount = parseFloat(txn.amount || 0);
          const isReceipt = txn.transaction_type === 'Receipt' || (amount > 0 && txn.transaction_type !== 'Payment');
          const isPayment = txn.transaction_type === 'Payment' || (amount < 0 && txn.transaction_type === 'Receipt');

          let receiptAmt = 0;
          let paymentAmt = 0;

          if (isReceipt || (amount > 0 && txn.transaction_type === 'Contra')) {
            receiptAmt = Math.abs(amount);
            runningBalance += receiptAmt;
            totalReceipts += receiptAmt;
          } else {
            paymentAmt = Math.abs(amount);
            runningBalance -= paymentAmt;
            totalPayments += paymentAmt;
          }

          // Determine source
          let source = 'Cash Book';
          let sourceClass = 'text-primary';
          if (txn.source === 'petty_cash') {
            source = 'Petty Cash';
            sourceClass = 'text-secondary';
          } else if (txn.reference_type === 'Invoice') {
            source = 'Invoice Receipt';
            sourceClass = 'text-success';
          } else if (txn.reference_type === 'Expense') {
            source = 'Expenditure';
            sourceClass = 'text-danger';
          }

          const row = `
            <tr class="${txn.is_reconciled ? 'table-success' : ''}">
              <td>${txn.transaction_date}</td>
              <td><code class="fw-bold text-primary">${escapeHtml(txn.voucher_number)}</code></td>
              <td>${getTypeBadge(txn.transaction_type)}</td>
              <td class="${sourceClass}">${source}</td>
              <td>
                <div>${escapeHtml(txn.narration || txn.account_head || '-')}</div>
                <small class="text-muted">${escapeHtml(txn.party_name || '')}</small>
              </td>
              <td>
                <small>${escapeHtml(txn.bank_account_name || '-')}</small>
              </td>
              <td class="text-end ${receiptAmt > 0 ? 'text-success fw-bold' : ''}">
                ${receiptAmt > 0 ? formatCurrency(receiptAmt, txn.bank_currency) : '-'}
              </td>
              <td class="text-end ${paymentAmt > 0 ? 'text-danger fw-bold' : ''}">
                ${paymentAmt > 0 ? formatCurrency(paymentAmt, txn.bank_currency) : '-'}
              </td>
              <td class="text-end fw-bold ${runningBalance >= 0 ? 'text-primary' : 'text-danger'}">
                ${formatCurrency(runningBalance, txn.bank_currency)}
              </td>
              <td class="text-center">
                ${txn.is_reconciled 
                  ? '<span class="badge bg-success" title="Reconciled"><i class="bi bi-check-circle"></i></span>'
                  : '<span class="badge bg-warning" title="Pending"><i class="bi bi-clock"></i></span>'
                }
              </td>
            </tr>
          `;
          $tbody.append(row);
        });
      }

      // Update summary
      const openingBalance = summary?.bank_summary?.total_lkr_balance || 0;
      const closingBalance = openingBalance + totalReceipts - totalPayments;

      $('#cfOpeningBalance').text(formatCurrency(openingBalance, 'LKR'));
      $('#cfTotalReceipts').text('+ ' + formatCurrency(totalReceipts, 'LKR'));
      $('#cfTotalPayments').text('- ' + formatCurrency(totalPayments, 'LKR'));
      $('#cfClosingBalance').text(formatCurrency(closingBalance, 'LKR'));

      cashFlowData = transactions;
    }).fail(function(xhr) {
      $tbody.html('<tr><td colspan="10" class="text-center text-danger py-4">Failed to load cash flow data</td></tr>');
    });
  }

  // Refresh all data
  function refreshAllData() {
    loadBankAccounts();
    loadCashFlowReport();
  }

  // Export cash flow to CSV
  function exportCashFlow() {
    if (cashFlowData.length === 0) {
      alert('No data to export');
      return;
    }

    let csv = 'Date,Voucher,Type,Source,Description,Party,Account,Receipt,Payment,Balance,Status\n';

    let runningBalance = 0;
    cashFlowData.forEach(function(txn) {
      const amount = parseFloat(txn.amount || 0);
      const isReceipt = txn.transaction_type === 'Receipt' || amount > 0;
      let receipt = '';
      let payment = '';

      if (isReceipt) {
        receipt = Math.abs(amount).toFixed(2);
        runningBalance += Math.abs(amount);
      } else {
        payment = Math.abs(amount).toFixed(2);
        runningBalance -= Math.abs(amount);
      }

      let source = 'Cash Book';
      if (txn.reference_type === 'Invoice') source = 'Invoice Receipt';
      if (txn.reference_type === 'Expense') source = 'Expenditure';

      csv += [
        txn.transaction_date,
        txn.voucher_number,
        txn.transaction_type,
        source,
        '"' + (txn.narration || '').replace(/"/g, '""') + '"',
        '"' + (txn.party_name || '').replace(/"/g, '""') + '"',
        txn.bank_account_name || '',
        receipt,
        payment,
        runningBalance.toFixed(2),
        txn.is_reconciled ? 'Reconciled' : 'Pending'
      ].join(',') + '\n';
    });

    const blob = new Blob([csv], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'cash_flow_report_' + new Date().toISOString().split('T')[0] + '.csv';
    a.click();
    window.URL.revokeObjectURL(url);
  }

  // Initialize
  loadBankAccounts();
  loadCashFlowReport();

  // Auto-refresh every 60 seconds
  setInterval(refreshAllData, 60000);

  // Expose functions globally
  window.refreshAllData = refreshAllData;
  window.loadCashFlowReport = loadCashFlowReport;
  window.exportCashFlow = exportCashFlow;
})();
</script>
