<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-finance-dashboard">
  <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-cash-coin me-2"></i>Finance Dashboard</h4>
      <div class="d-flex gap-2">
        <a href="?page=cash_book_entry" class="btn btn-primary btn-sm"><i class="bi bi-journal-plus me-1"></i>New Transaction</a>
      </div>
    </div>

    <!-- Summary Cards -->
    <div class="row g-3 mb-4">
      <div class="col-md-3">
        <div class="card bg-success text-white">
          <div class="card-body">
            <h6 class="card-title"><i class="bi bi-bank me-2"></i>Total Bank Balance</h6>
            <h4 id="totalBalance">LKR 0.00</h4>
            <small>Across all active accounts</small>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card bg-info text-white">
          <div class="card-body">
            <h6 class="card-title"><i class="bi bi-arrow-down-circle me-2"></i>Today's Receipts</h6>
            <h4 id="todayReceipts">LKR 0.00</h4>
            <small id="receiptCount">0 transactions</small>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card bg-warning text-dark">
          <div class="card-body">
            <h6 class="card-title"><i class="bi bi-arrow-up-circle me-2"></i>Today's Payments</h6>
            <h4 id="todayPayments">LKR 0.00</h4>
            <small id="paymentCount">0 transactions</small>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card bg-primary text-white">
          <div class="card-body">
            <h6 class="card-title"><i class="bi bi-wallet2 me-2"></i>Bank Accounts</h6>
            <h4 id="accountCount">0</h4>
            <small>Active accounts</small>
          </div>
        </div>
      </div>
    </div>

    <!-- Bank Accounts -->
    <div class="card shadow-sm mb-4">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h6 class="mb-0"><i class="bi bi-bank me-2"></i>Bank Accounts</h6>
        <button class="btn btn-sm btn-outline-primary" onclick="loadBankAccounts()">
          <i class="bi bi-arrow-repeat"></i> Refresh
        </button>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-sm table-hover" id="bankAccountsTable">
            <thead>
              <tr>
                <th>Account Name</th>
                <th>Bank</th>
                <th>Account Number</th>
                <th class="text-center">Currency</th>
                <th class="text-end">Current Balance</th>
                <th class="text-center">Status</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Recent Transactions -->
    <div class="card shadow-sm">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h6 class="mb-0"><i class="bi bi-journal-text me-2"></i>Recent Transactions</h6>
        <a href="?page=cash_book_entry" class="btn btn-sm btn-success">
          <i class="bi bi-plus-lg me-1"></i>Add Entry
        </a>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-sm table-hover" id="transactionsTable">
            <thead>
              <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>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

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

  const currencyFormatter = new Intl.NumberFormat('en-LK', {
    style: 'currency',
    currency: 'LKR'
  });

  // Load bank accounts
  function loadBankAccounts() {
    $.get('api/finance.php', { action: 'list_bank_accounts', is_active: 1 }, function(res) {
      const accounts = res.data || [];
      let totalLKR = 0;
      let totalUSD = 0;
      
      const $tbody = $('#bankAccountsTable tbody');
      $tbody.empty();
      
      accounts.forEach(function(acc) {
        // Calculate totals
        if (acc.currency === 'LKR') {
          totalLKR += parseFloat(acc.current_balance || 0);
        } else if (acc.currency === 'USD') {
          totalUSD += parseFloat(acc.current_balance || 0);
        }
        
        // Format balance
        const balance = parseFloat(acc.current_balance || 0).toLocaleString('en-LK', {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2
        });
        
        const row = `
          <tr>
            <td><strong>${escapeHtml(acc.account_name)}</strong>
              ${acc.is_default == 1 ? '<span class="badge bg-primary ms-1">Default</span>' : ''}
            </td>
            <td>${escapeHtml(acc.bank_name)}<br><small class="text-muted">${escapeHtml(acc.branch_name || '')}</small></td>
            <td><code>${escapeHtml(acc.account_number)}</code></td>
            <td class="text-center"><span class="badge bg-secondary">${acc.currency}</span></td>
            <td class="text-end fw-bold ${acc.current_balance > 0 ? 'text-success' : (acc.current_balance < 0 ? 'text-danger' : '')}">
              ${acc.currency === 'LKR' ? 'LKR' : acc.currency} ${balance}
            </td>
            <td class="text-center">
              ${acc.is_active == 1 
                ? '<span class="badge bg-success">Active</span>' 
                : '<span class="badge bg-secondary">Inactive</span>'}
            </td>
          </tr>
        `;
        $tbody.append(row);
      });
      
      // Update summary
      $('#totalBalance').text('LKR ' + totalLKR.toLocaleString('en-LK', {minimumFractionDigits: 2}));
      $('#accountCount').text(accounts.length);
      
      // Load recent transactions
      loadRecentTransactions();
      
    }).fail(function(xhr) {
      console.error('Failed to load bank accounts:', xhr);
    });
  }

  // Load recent transactions
  function loadRecentTransactions() {
    const today = new Date().toISOString().split('T')[0];
    
    $.get('api/transactions.php', { 
      action: 'list',
      date_from: today,
      date_to: today,
      is_cancelled: 0
    }, function(res) {
      const transactions = res.data || [];
      
      let receiptTotal = 0;
      let receiptCount = 0;
      let paymentTotal = 0;
      let paymentCount = 0;
      
      const $tbody = $('#transactionsTable tbody');
      $tbody.empty();
      
      transactions.slice(0, 20).forEach(function(txn) { // Show last 20
        // Calculate totals
        const amount = parseFloat(txn.amount || 0);
        if (txn.transaction_type === 'Receipt') {
          receiptTotal += amount;
          receiptCount++;
        } else if (txn.transaction_type === 'Payment') {
          paymentTotal += amount;
          paymentCount++;
        }
        
        const typeBadge = getTypeBadge(txn.transaction_type);
        const statusBadge = txn.is_cancelled == 1 
          ? '<span class="badge bg-danger">Cancelled</span>'
          : (txn.is_approved == 1 
            ? '<span class="badge bg-success">Approved</span>'
            : '<span class="badge bg-warning">Pending</span>');
        
        const row = `
          <tr>
            <td><code class="fw-bold text-primary">${escapeHtml(txn.voucher_number)}</code></td>
            <td>${txn.transaction_date}</td>
            <td>${typeBadge}</td>
            <td>${escapeHtml(txn.account_head)}<br><small class="text-muted">${escapeHtml(txn.bank_account_name || '')}</small></td>
            <td>${escapeHtml(txn.party_name || '-')}</td>
            <td class="text-end fw-bold ${getAmountClass(txn.transaction_type)}">
              ${getCurrencySymbol(txn.bank_currency)} ${amount.toLocaleString('en-LK', {minimumFractionDigits: 2})}
            </td>
            <td><small>${escapeHtml(txn.document_reference || '-')}</small></td>
            <td class="text-center">${statusBadge}</td>
          </tr>
        `;
        $tbody.append(row);
      });
      
      if (transactions.length === 0) {
        $tbody.append('<tr><td colspan="8" class="text-center text-muted py-3">No transactions today</td></tr>');
      }
      
      // Update today's summary
      $('#todayReceipts').text('LKR ' + receiptTotal.toLocaleString('en-LK', {minimumFractionDigits: 2}));
      $('#receiptCount').text(receiptCount + ' transaction' + (receiptCount !== 1 ? 's' : ''));
      $('#todayPayments').text('LKR ' + paymentTotal.toLocaleString('en-LK', {minimumFractionDigits: 2}));
      $('#paymentCount').text(paymentCount + ' transaction' + (paymentCount !== 1 ? 's' : ''));
      
    }).fail(function(xhr) {
      console.error('Failed to load transactions:', xhr);
    });
  }

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

  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>'
    };
    return badges[type] || '<span class="badge bg-light text-dark">' + type + '</span>';
  }

  function getAmountClass(type) {
    const classes = {
      'Receipt': 'text-success',
      'Payment': 'text-danger',
      'Contra': 'text-primary',
      'Journal': 'text-secondary'
    };
    return classes[type] || '';
  }

  function getCurrencySymbol(currency) {
    return currency === 'USD' ? '$' : 'LKR';
  }

  // Initialize
  loadBankAccounts();
  
  // Refresh every 30 seconds
  setInterval(loadBankAccounts, 30000);
})();
</script>
