<?php require_once __DIR__ . '/../includes/auth.php'; 
require_login(); 
if (!has_role(['admin', 'super_admin', 'finance_manager', 'accountant'])) {
    header('Location: ?page=dashboard');
    exit;
}
?>
<div class="page-bank-accounts">
  <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-bank me-2"></i>Bank Account Management</h4>
      <button class="btn btn-primary" onclick="openBankModal()">
        <i class="bi bi-plus-circle me-1"></i>Add New Bank Account
      </button>
    </div>

    <!-- Bank Accounts List -->
    <div class="card shadow-sm">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Your Bank Accounts</h5>
        <span class="badge bg-secondary" id="totalAccountsBadge">0 Accounts</span>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-hover table-striped mb-0" id="bankAccountsTable">
            <thead class="table-dark">
              <tr>
                <th>Account Name</th>
                <th>Bank Details</th>
                <th>Account Number</th>
                <th>Type</th>
                <th class="text-end">Initial Balance</th>
                <th class="text-end">Current Balance</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody id="bankAccountsTableBody">
              <tr>
                <td colspan="8" class="text-center text-muted py-4">
                  <div class="spinner-border spinner-border-sm me-2"></div>Loading bank accounts...
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Quick Guide -->
    <div class="card mt-4 bg-light border-0">
      <div class="card-body">
        <h6><i class="bi bi-info-circle me-2"></i>How to Add Your Bank Details</h6>
        <ol class="mb-0 small">
          <li>Click <strong>"Add New Bank Account"</strong> button above</li>
          <li>Enter your bank name (e.g., "Commercial Bank", "Sampath Bank", "HNB")</li>
          <li>Enter a descriptive account name (e.g., "Main Operating Account", "Salary Account")</li>
          <li>Enter your actual account number</li>
          <li>Set the initial/current balance (starting balance)</li>
          <li>Mark one account as <strong>Default</strong> for primary transactions</li>
          <li>Click <strong>Save</strong></li>
        </ol>
      </div>
    </div>
  </div>
</div>

<!-- Bank Account Modal -->
<div class="modal fade" id="bankAccountModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="modalTitle"><i class="bi bi-bank me-2"></i>Add Bank Account</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="bankAccountForm">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <input type="hidden" name="account_id" id="accountId">
          
          <div class="row g-3">
            <!-- Bank Name -->
            <div class="col-md-6">
              <label class="form-label">Bank Name <span class="text-danger">*</span></label>
              <input type="text" name="bank_name" id="bankName" class="form-control" required 
                     placeholder="e.g., Commercial Bank of Ceylon">
              <div class="form-text">Full name of your bank</div>
            </div>
            
            <!-- Account Name -->
            <div class="col-md-6">
              <label class="form-label">Account Name <span class="text-danger">*</span></label>
              <input type="text" name="account_name" id="accountName" class="form-control" required
                     placeholder="e.g., Main Operating Account">
              <div class="form-text">Descriptive name for this account</div>
            </div>
            
            <!-- Account Number -->
            <div class="col-md-6">
              <label class="form-label">Account Number <span class="text-danger">*</span></label>
              <input type="text" name="account_number" id="accountNumber" class="form-control" required
                     placeholder="e.g., 0123456789">
            </div>
            
            <!-- Branch Name -->
            <div class="col-md-6">
              <label class="form-label">Branch Name</label>
              <input type="text" name="branch_name" id="branchName" class="form-control"
                     placeholder="e.g., Colombo Main Branch">
            </div>
            
            <!-- Account Type -->
            <div class="col-md-4">
              <label class="form-label">Account Type <span class="text-danger">*</span></label>
              <select name="account_type" id="accountType" class="form-select" required>
                <option value="Current">Current Account</option>
                <option value="Savings">Savings Account</option>
                <option value="Fixed Deposit">Fixed Deposit</option>
                <option value="Recurring Deposit">Recurring Deposit</option>
                <option value="Other">Other</option>
              </select>
            </div>
            
            <!-- Currency -->
            <div class="col-md-4">
              <label class="form-label">Currency <span class="text-danger">*</span></label>
              <select name="currency" id="currency" class="form-select" required>
                <option value="LKR" selected>Sri Lankan Rupee (LKR)</option>
                <option value="USD">US Dollar (USD)</option>
                <option value="EUR">Euro (EUR)</option>
                <option value="GBP">British Pound (GBP)</option>
                <option value="AUD">Australian Dollar (AUD)</option>
              </select>
            </div>
            
            <!-- Opening Date -->
            <div class="col-md-4">
              <label class="form-label">Opening Date</label>
              <input type="date" name="opening_date" id="openingDate" class="form-control">
            </div>
            
            <!-- Initial Balance -->
            <div class="col-md-6">
              <label class="form-label">Initial Balance <span class="text-danger">*</span></label>
              <div class="input-group">
                <span class="input-group-text" id="currencySymbol">LKR</span>
                <input type="number" name="initial_balance" id="initialBalance" class="form-control" 
                       required min="0" step="0.01" value="0.00">
              </div>
              <div class="form-text">Starting balance when account was opened</div>
            </div>
            
            <!-- Current Balance -->
            <div class="col-md-6">
              <label class="form-label">Current Balance <span class="text-danger">*</span></label>
              <div class="input-group">
                <span class="input-group-text" id="currentCurrencySymbol">LKR</span>
                <input type="number" name="current_balance" id="currentBalance" class="form-control" 
                       required min="0" step="0.01" value="0.00">
              </div>
              <div class="form-text">Current available balance</div>
            </div>
            
            <!-- IFSC Code -->
            <div class="col-md-6">
              <label class="form-label">IFSC/Sort Code</label>
              <input type="text" name="ifsc_code" id="ifscCode" class="form-control" placeholder="e.g., CCEYLKLX">
              <div class="form-text">Bank identification code (if applicable)</div>
            </div>
            
            <!-- SWIFT Code -->
            <div class="col-md-6">
              <label class="form-label">SWIFT/BIC Code</label>
              <input type="text" name="swift_code" id="swiftCode" class="form-control" placeholder="e.g., CCEYLKLX001">
              <div class="form-text">For international transfers</div>
            </div>
            
            <!-- Description -->
            <div class="col-12">
              <label class="form-label">Description / Notes</label>
              <textarea name="description" id="description" class="form-control" rows="2"
                        placeholder="Purpose of this account, any special notes..."></textarea>
            </div>
            
            <!-- Options -->
            <div class="col-md-6">
              <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" name="is_default" id="isDefault" value="1">
                <label class="form-check-label" for="isDefault">
                  Set as Default Account
                </label>
              </div>
              <div class="form-text">Primary account for transactions</div>
            </div>
            
            <div class="col-md-6">
              <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" name="is_active" id="isActive" value="1" checked>
                <label class="form-check-label" for="isActive">
                  Account is Active
                </label>
              </div>
            </div>
          </div>
        </form>
      </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" onclick="saveBankAccount()">
          <i class="bi bi-check-circle me-1"></i>Save Account
        </button>
      </div>
    </div>
  </div>
</div>

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

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

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

  // Update currency symbols
  function updateCurrencySymbols() {
    const currency = $('#currency').val();
    let symbol = 'LKR';
    switch(currency) {
      case 'USD': symbol = '$'; break;
      case 'EUR': symbol = '€'; break;
      case 'GBP': symbol = '£'; break;
      case 'AUD': symbol = 'A$'; break;
      default: symbol = 'LKR';
    }
    $('#currencySymbol, #currentCurrencySymbol').text(symbol);
  }

  // Load bank accounts
  function loadBankAccounts() {
    $.get('api/finance.php', { action: 'list_bank_accounts' }, function(res) {
      const accounts = res.data || [];
      const $tbody = $('#bankAccountsTableBody');
      $tbody.empty();

      $('#totalAccountsBadge').text(accounts.length + ' Account' + (accounts.length !== 1 ? 's' : ''));

      if (accounts.length === 0) {
        $tbody.html('<tr><td colspan="8" class="text-center text-muted py-4">No bank accounts found. Click "Add New Bank Account" to create one.</td></tr>');
        return;
      }

      accounts.forEach(function(acc) {
        const isDefaultBadge = acc.is_default == 1 ? '<span class="badge bg-primary ms-1">Default</span>' : '';
        const statusBadge = acc.is_active == 1 ? 
          '<span class="badge bg-success">Active</span>' : 
          '<span class="badge bg-secondary">Inactive</span>';

        const row = `
          <tr>
            <td>
              <strong>${escapeHtml(acc.account_name)}</strong>
              ${isDefaultBadge}
            </td>
            <td>
              <div><strong>${escapeHtml(acc.bank_name)}</strong></div>
              <small class="text-muted">${escapeHtml(acc.branch_name || '-')}</small>
            </td>
            <td><code class="font-monospace">${escapeHtml(acc.account_number)}</code></td>
            <td>${escapeHtml(acc.account_type)}</td>
            <td class="text-end">${formatCurrency(acc.initial_balance, acc.currency)}</td>
            <td class="text-end fw-bold ${acc.current_balance < 0 ? 'text-danger' : 'text-success'}">
              ${formatCurrency(acc.current_balance, acc.currency)}
            </td>
            <td>${statusBadge}</td>
            <td>
              <button class="btn btn-sm btn-outline-primary me-1" onclick="editBankAccount(${acc.id})" title="Edit">
                <i class="bi bi-pencil"></i>
              </button>
              <button class="btn btn-sm btn-outline-danger" onclick="deleteBankAccount(${acc.id})" title="Delete">
                <i class="bi bi-trash"></i>
              </button>
            </td>
          </tr>
        `;
        $tbody.append(row);
      });
    }).fail(function() {
      $('#bankAccountsTableBody').html('<tr><td colspan="8" class="text-center text-danger py-4">Failed to load bank accounts</td></tr>');
    });
  }

  // Open modal for new account
  function openBankModal() {
    editingId = null;
    $('#modalTitle').html('<i class="bi bi-bank me-2"></i>Add Bank Account');
    $('#bankAccountForm')[0].reset();
    $('#accountId').val('');
    $('#isDefault').prop('checked', false);
    $('#isActive').prop('checked', true);
    $('#currencySymbol, #currentCurrencySymbol').text('LKR');
    
    new bootstrap.Modal(document.getElementById('bankAccountModal')).show();
  }

  // Edit bank account
  function editBankAccount(id) {
    editingId = id;
    $('#modalTitle').html('<i class="bi bi-bank me-2"></i>Edit Bank Account');
    
    $.get('api/finance.php', { action: 'get_bank_account', id: id }, function(res) {
      if (res.data) {
        const acc = res.data;
        $('#accountId').val(acc.id);
        $('#bankName').val(acc.bank_name);
        $('#accountName').val(acc.account_name);
        $('#accountNumber').val(acc.account_number);
        $('#branchName').val(acc.branch_name);
        $('#accountType').val(acc.account_type);
        $('#currency').val(acc.currency);
        $('#openingDate').val(acc.opening_date);
        $('#initialBalance').val(acc.initial_balance);
        $('#currentBalance').val(acc.current_balance);
        $('#ifscCode').val(acc.ifsc_code);
        $('#swiftCode').val(acc.swift_code);
        $('#description').val(acc.description);
        $('#isDefault').prop('checked', acc.is_default == 1);
        $('#isActive').prop('checked', acc.is_active == 1);
        
        updateCurrencySymbols();
        new bootstrap.Modal(document.getElementById('bankAccountModal')).show();
      }
    });
  }

  // Save bank account
  function saveBankAccount() {
    const formData = new FormData($('#bankAccountForm')[0]);
    formData.append('action', editingId ? 'update_bank_account' : 'create_bank_account');
    
    // Ensure is_default and is_active are included even if unchecked
    formData.set('is_default', $('#isDefault').prop('checked') ? '1' : '0');
    formData.set('is_active', $('#isActive').prop('checked') ? '1' : '0');

    $.ajax({
      url: 'api/finance.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(res) {
        $('#bankAccountModal').modal('hide');
        alert('Bank account saved successfully!');
        loadBankAccounts();
      },
      error: function(xhr) {
        alert('Error: ' + (xhr.responseJSON?.message || 'Failed to save bank account'));
      }
    });
  }

  // Delete bank account
  function deleteBankAccount(id) {
    if (!confirm('Are you sure you want to delete this bank account?\n\nNote: This will only work if there are no transactions linked to this account.')) {
      return;
    }

    const formData = new FormData();
    formData.append('action', 'delete_bank_account');
    formData.append('csrf', csrf);
    formData.append('id', id);

    $.ajax({
      url: 'api/finance.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function() {
        alert('Bank account deleted successfully!');
        loadBankAccounts();
      },
      error: function(xhr) {
        alert('Error: ' + (xhr.responseJSON?.message || 'Cannot delete - account may have transactions'));
      }
    });
  }

  // Event handlers
  $('#currency').on('change', updateCurrencySymbols);
  $('#initialBalance').on('input', function() {
    // Sync current balance with initial for new accounts
    if (!editingId) {
      $('#currentBalance').val($(this).val());
    }
  });

  // Initialize
  loadBankAccounts();

  // Expose functions
  window.openBankModal = openBankModal;
  window.editBankAccount = editBankAccount;
  window.saveBankAccount = saveBankAccount;
  window.deleteBankAccount = deleteBankAccount;
})();
</script>
