<?php require_once __DIR__ . '/../includes/auth.php'; 
require_login(); 
// Only finance managers, admins, and super admins can access
if (!has_role(['admin', 'super_admin', 'finance_manager'])) {
    header('Location: ?page=dashboard');
    exit;
}
?>
<div class="page-finance-manager">
  <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-shield-check me-2"></i>Finance Manager Dashboard</h4>
      <div class="d-flex gap-2">
        <span class="badge bg-warning fs-6" id="pendingBadge">
          <i class="bi bi-clock-history me-1"></i><span id="pendingCount">0</span> Pending
        </span>
      </div>
    </div>

    <!-- Summary Cards -->
    <div class="row g-3 mb-4">
      <div class="col-md-3">
        <div class="card border-warning">
          <div class="card-body text-center">
            <h6 class="text-muted">Pending Approvals</h6>
            <h3 class="text-warning" id="statPending">0</h3>
            <small>Transactions awaiting review</small>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card border-success">
          <div class="card-body text-center">
            <h6 class="text-muted">Approved Today</h6>
            <h3 class="text-success" id="statApproved">0</h3>
            <small>By <?php echo htmlspecialchars($_SESSION['username'] ?? 'you'); ?></small>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card border-info">
          <div class="card-body text-center">
            <h6 class="text-muted">Total Value Pending</h6>
            <h3 class="text-info" id="statPendingValue">LKR 0.00</h3>
            <small>Combined amount</small>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card border-primary">
          <div class="card-body text-center">
            <h6 class="text-muted">GL Entries Today</h6>
            <h3 class="text-primary" id="statGLEntries">0</h3>
            <small>Posted to ledger</small>
          </div>
        </div>
      </div>
    </div>

    <!-- Pending Transactions Section -->
    <div class="card shadow-sm mb-4 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-clock-history me-2"></i>Pending Voucher Approvals</h6>
        <button class="btn btn-sm btn-light" onclick="loadPendingTransactions()">
          <i class="bi bi-arrow-repeat"></i> Refresh
        </button>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-hover table-sm" id="pendingTable">
            <thead class="table-light">
              <tr>
                <th>Voucher #</th>
                <th>Date</th>
                <th>Type</th>
                <th>Account Head</th>
                <th>Bank Account</th>
                <th>Party</th>
                <th class="text-end">Amount</th>
                <th>Entered By</th>
                <th class="text-center">Actions</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
        <div id="noPendingMsg" class="text-center text-muted py-4 d-none">
          <i class="bi bi-check-circle fs-1 text-success"></i>
          <p class="mt-2">No pending transactions. All vouchers have been reviewed!</p>
        </div>
      </div>
    </div>

    <!-- Recent GL Postings -->
    <div class="card shadow-sm">
      <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
        <h6 class="mb-0"><i class="bi bi-journal-book me-2"></i>Recent GL Postings</h6>
        <button class="btn btn-sm btn-light" onclick="loadGLPostings()">
          <i class="bi bi-arrow-repeat"></i> Refresh
        </button>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-hover table-sm" id="glTable">
            <thead class="table-light">
              <tr>
                <th>Voucher #</th>
                <th>Date</th>
                <th>Account Code</th>
                <th>Account Name</th>
                <th class="text-end">Debit</th>
                <th class="text-end">Credit</th>
                <th>Narration</th>
                <th>Posted By</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Approve/Reject Modal -->
<div class="modal fade" id="approvalModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-clipboard-check me-2"></i>Review Transaction</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="reviewTransactionId">
        <input type="hidden" id="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
        
        <!-- Transaction Summary -->
        <div class="alert alert-info">
          <div class="row">
            <div class="col-md-6">
              <strong>Voucher:</strong> <span id="reviewVoucher" class="fw-bold text-primary"></span>
            </div>
            <div class="col-md-6 text-end">
              <strong>Amount:</strong> <span id="reviewAmount" class="fw-bold fs-5"></span>
            </div>
          </div>
        </div>
        
        <div class="row mb-3">
          <div class="col-md-6">
            <label class="form-label text-muted">Transaction Type</label>
            <p id="reviewType" class="fw-bold"></p>
          </div>
          <div class="col-md-6">
            <label class="form-label text-muted">Account Head</label>
            <p id="reviewAccountHead" class="fw-bold"></p>
          </div>
        </div>
        
        <div class="row mb-3">
          <div class="col-md-6">
            <label class="form-label text-muted">Bank Account</label>
            <p id="reviewBankAccount"></p>
          </div>
          <div class="col-md-6">
            <label class="form-label text-muted">Party</label>
            <p id="reviewParty"></p>
          </div>
        </div>
        
        <div class="mb-3">
          <label class="form-label text-muted">Narration</label>
          <p id="reviewNarration" class="border rounded p-2 bg-light"></p>
        </div>
        
        <div class="row mb-3">
          <div class="col-md-6">
            <label class="form-label text-muted">Document Reference</label>
            <p id="reviewDocRef"></p>
          </div>
          <div class="col-md-6">
            <label class="form-label text-muted">Payment Mode</label>
            <p id="reviewPaymentMode"></p>
          </div>
        </div>
        
        <!-- GL Posting Preview -->
        <div class="card border-primary mb-3">
          <div class="card-header bg-primary text-white">
            <i class="bi bi-journal-book me-2"></i>GL Posting Preview (Double Entry)
          </div>
          <div class="card-body p-0">
            <table class="table table-sm mb-0">
              <thead class="table-light">
                <tr>
                  <th>Account Code</th>
                  <th>Account Name</th>
                  <th class="text-end">Debit</th>
                  <th class="text-end">Credit</th>
                </tr>
              </thead>
              <tbody id="glPreviewTable"></tbody>
            </table>
          </div>
        </div>
        
        <!-- Manager Action -->
        <div class="mb-3">
          <label class="form-label fw-bold">Manager Action <span class="text-danger">*</span></label>
          <select id="managerAction" class="form-select">
            <option value="">Select Action...</option>
            <option value="Approved">✓ Approve and Post to GL</option>
            <option value="Rejected">✗ Reject Transaction</option>
          </select>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Remarks / Reason</label>
          <textarea id="managerRemarks" class="form-control" rows="2" placeholder="Enter approval remarks or rejection reason..."></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" id="btnConfirmAction" class="btn btn-primary" disabled>
          <i class="bi bi-check-lg me-1"></i>Confirm Action
        </button>
      </div>
    </div>
  </div>
</div>

<!-- GL Entry Detail Modal -->
<div class="modal fade" id="glDetailModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title"><i class="bi bi-journal-book me-2"></i>GL Entry Details</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div id="glDetailContent"></div>
      </div>
    </div>
  </div>
</div>

<script>
(function() {
  if (!$('.page-finance-manager').length) return;
  
  const csrf = $('#csrf').val();
  let currentTransaction = null;
  
  // 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;')
      .replace(/'/g, '&#039;');
  }
  
  // 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>'
    };
    return badges[type] || '<span class="badge bg-light text-dark">' + type + '</span>';
  }
  
  // Load pending transactions
  function loadPendingTransactions() {
    $.get('api/transactions.php', { action: 'list', approval_status: 'Pending', is_cancelled: 0 }, function(res) {
      const transactions = res.data || [];
      const $tbody = $('#pendingTable tbody');
      $tbody.empty();
      
      let totalPending = 0;
      let totalLKR = 0;
      
      transactions.forEach(function(txn) {
        totalPending++;
        const amount = parseFloat(txn.amount || 0);
        if (txn.bank_currency === 'LKR' || !txn.bank_currency) {
          totalLKR += amount;
        }
        
        const row = `
          <tr data-transaction='${escapeHtml(JSON.stringify(txn))}'>
            <td><code class="fw-bold text-primary">${escapeHtml(txn.voucher_number)}</code></td>
            <td>${txn.transaction_date}</td>
            <td>${getTypeBadge(txn.transaction_type)}</td>
            <td>${escapeHtml(txn.account_head)}</td>
            <td>${escapeHtml(txn.bank_account_name || '-')}</td>
            <td>${escapeHtml(txn.party_name || '-')}</td>
            <td class="text-end fw-bold">
              ${formatCurrency(amount, txn.bank_currency)}
            </td>
            <td><small>${escapeHtml(txn.entered_by_name || 'Unknown')}</small></td>
            <td class="text-center">
              <button class="btn btn-sm btn-primary btn-review" data-id="${txn.id}">
                <i class="bi bi-eye me-1"></i>Review
              </button>
            </td>
          </tr>
        `;
        $tbody.append(row);
      });
      
      // Update stats
      $('#statPending').text(totalPending);
      $('#statPendingValue').text('LKR ' + totalLKR.toLocaleString('en-LK', {minimumFractionDigits: 2}));
      $('#pendingCount').text(totalPending);
      
      // Show/hide no pending message
      if (totalPending === 0) {
        $('#pendingTable').hide();
        $('#noPendingMsg').removeClass('d-none');
      } else {
        $('#pendingTable').show();
        $('#noPendingMsg').addClass('d-none');
      }
    }).fail(function(xhr) {
      console.error('Failed to load pending transactions:', xhr);
      alert('Error loading pending transactions');
    });
  }
  
  // Load GL postings
  function loadGLPostings() {
    const today = new Date().toISOString().split('T')[0];
    
    $.get('api/transactions.php', { action: 'list_gl_entries', date_from: today, date_to: today }, function(res) {
      const entries = res.data || [];
      const $tbody = $('#glTable tbody');
      $tbody.empty();
      
      let count = 0;
      entries.forEach(function(entry) {
        count++;
        const row = `
          <tr>
            <td><code>${escapeHtml(entry.voucher_number)}</code></td>
            <td>${entry.entry_date}</td>
            <td><strong>${escapeHtml(entry.account_code)}</strong></td>
            <td>${escapeHtml(entry.account_name)}</td>
            <td class="text-end ${entry.debit_amount > 0 ? 'text-success fw-bold' : ''}">
              ${entry.debit_amount > 0 ? formatCurrency(entry.debit_amount, 'LKR') : '-'}
            </td>
            <td class="text-end ${entry.credit_amount > 0 ? 'text-danger fw-bold' : ''}">
              ${entry.credit_amount > 0 ? formatCurrency(entry.credit_amount, 'LKR') : '-'}
            </td>
            <td><small>${escapeHtml(entry.narration || '')}</small></td>
            <td><small>${escapeHtml(entry.created_by_name || '')}</small></td>
          </tr>
        `;
        $tbody.append(row);
      });
      
      $('#statGLEntries').text(count);
    }).fail(function(xhr) {
      console.error('Failed to load GL entries:', xhr);
    });
  }
  
  // Load today's approved count
  function loadTodayApproved() {
    const today = new Date().toISOString().split('T')[0];
    const userId = '<?php echo $_SESSION['user_id'] ?? 0; ?>';
    
    $.get('api/transactions.php', { 
      action: 'list', 
      date_from: today, 
      date_to: today, 
      approval_status: 'Approved',
      // We would ideally filter by approved_by, but the API doesn't support it yet
    }, function(res) {
      const count = (res.data || []).length;
      $('#statApproved').text(count);
    });
  }
  
  // Generate GL preview based on transaction type
  function generateGLPreview(transaction) {
    const $tbody = $('#glPreviewTable');
    $tbody.empty();
    
    const amount = parseFloat(transaction.amount || 0);
    const taxAmount = parseFloat(transaction.tax_amount || 0);
    const totalAmount = amount + taxAmount;
    
    // Map account heads to GL account codes
    const accountHeadMap = {
      'Sales Revenue': '4000',
      'Service Revenue': '4100',
      'Purchase Expenses': '5000',
      'Salary & Wages': '5100',
      'Rent Expense': '5200',
      'Utilities': '5300',
      'Transportation': '5400',
      'Office Supplies': '5500',
      'Marketing': '5600',
      'Maintenance': '5700',
      'Other Expenses': '5900',
      'Cash in Hand': '1000',
      'Bank Accounts': '1100',
      'Accounts Receivable': '1300',
      'Accounts Payable': '2000'
    };
    
    const bankAccountCode = '1100'; // Default bank account code
    const expenseAccountCode = accountHeadMap[transaction.account_head] || '5900';
    const incomeAccountCode = accountHeadMap[transaction.account_head] || '4000';
    
    let entries = [];
    
    switch(transaction.transaction_type) {
      case 'Receipt':
        // Receipt: Debit Bank, Credit Income
        entries = [
          { code: bankAccountCode, name: 'Bank Account', debit: totalAmount, credit: 0 },
          { code: incomeAccountCode, name: transaction.account_head, debit: 0, credit: totalAmount }
        ];
        break;
        
      case 'Payment':
        // Payment: Debit Expense, Credit Bank
        entries = [
          { code: expenseAccountCode, name: transaction.account_head, debit: totalAmount, credit: 0 },
          { code: bankAccountCode, name: 'Bank Account', debit: 0, credit: totalAmount }
        ];
        break;
        
      case 'Contra':
        // Contra: Debit Destination Bank, Credit Source Bank
        entries = [
          { code: bankAccountCode, name: 'Destination Bank Account', debit: totalAmount, credit: 0 },
          { code: bankAccountCode, name: 'Source Bank Account', debit: 0, credit: totalAmount }
        ];
        break;
        
      case 'Journal':
        // Journal: Depends on account head type
        entries = [
          { code: expenseAccountCode, name: transaction.account_head + ' (Debit)', debit: totalAmount, credit: 0 },
          { code: bankAccountCode, name: 'Bank Account (Credit)', debit: 0, credit: totalAmount }
        ];
        break;
    }
    
    entries.forEach(function(entry) {
      const row = `
        <tr>
          <td><code>${entry.code}</code></td>
          <td>${escapeHtml(entry.name)}</td>
          <td class="text-end ${entry.debit > 0 ? 'text-success fw-bold' : ''}">
            ${entry.debit > 0 ? formatCurrency(entry.debit, 'LKR') : '-'}
          </td>
          <td class="text-end ${entry.credit > 0 ? 'text-danger fw-bold' : ''}">
            ${entry.credit > 0 ? formatCurrency(entry.credit, 'LKR') : '-'}
          </td>
        </tr>
      `;
      $tbody.append(row);
    });
  }
  
  // Open review modal
  $(document).on('click', '.btn-review', function() {
    const txnData = $(this).closest('tr').data('transaction');
    currentTransaction = txnData;
    
    $('#reviewTransactionId').val(txnData.id);
    $('#reviewVoucher').text(txnData.voucher_number);
    $('#reviewAmount').text(formatCurrency(txnData.amount, txnData.bank_currency));
    $('#reviewType').html(getTypeBadge(txnData.transaction_type));
    $('#reviewAccountHead').text(txnData.account_head);
    $('#reviewBankAccount').text((txnData.bank_account_name || '') + ' - ' + (txnData.bank_account_number || ''));
    $('#reviewParty').text(txnData.party_name || txnData.party_type || '-');
    $('#reviewNarration').text(txnData.narration || '-');
    $('#reviewDocRef').text(txnData.document_reference || '-');
    $('#reviewPaymentMode').text(txnData.mode_of_payment || '-');
    
    // Generate GL preview
    generateGLPreview(txnData);
    
    // Reset form
    $('#managerAction').val('');
    $('#managerRemarks').val('');
    $('#btnConfirmAction').prop('disabled', true);
    
    // Show modal
    new bootstrap.Modal(document.getElementById('approvalModal')).show();
  });
  
  // Enable confirm button when action selected
  $('#managerAction').on('change', function() {
    $('#btnConfirmAction').prop('disabled', !$(this).val());
    
    const action = $(this).val();
    if (action === 'Approved') {
      $('#btnConfirmAction').removeClass('btn-danger').addClass('btn-success')
        .html('<i class="bi bi-check-lg me-1"></i>Approve & Post GL');
    } else if (action === 'Rejected') {
      $('#btnConfirmAction').removeClass('btn-success').addClass('btn-danger')
        .html('<i class="bi bi-x-lg me-1"></i>Reject Transaction');
    }
  });
  
  // Confirm approval/rejection
  $('#btnConfirmAction').on('click', function() {
    const action = $('#managerAction').val();
    const transactionId = $('#reviewTransactionId').val();
    const remarks = $('#managerRemarks').val();
    
    if (!action) {
      alert('Please select an action');
      return;
    }
    
    if (action === 'Rejected' && !remarks) {
      alert('Please provide a reason for rejection');
      $('#managerRemarks').focus();
      return;
    }
    
    const btn = $(this);
    const originalText = btn.html();
    btn.prop('disabled', true).html('<i class="bi bi-hourglass-split me-1"></i>Processing...');
    
    const formData = new FormData();
    formData.append('action', 'approve');
    formData.append('id', transactionId);
    formData.append('status', action);
    formData.append('reason', remarks);
    formData.append('csrf', csrf);
    
    $.ajax({
      url: 'api/transactions.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(res) {
        btn.prop('disabled', false).html(originalText);
        
        if (action === 'Approved') {
          alert('Transaction approved successfully!\nGL entries have been posted.\n\nVoucher: ' + currentTransaction.voucher_number);
        } else {
          alert('Transaction rejected.\n\nVoucher: ' + currentTransaction.voucher_number);
        }
        
        $('#approvalModal').modal('hide');
        loadPendingTransactions();
        loadGLPostings();
        loadTodayApproved();
      },
      error: function(xhr) {
        btn.prop('disabled', false).html(originalText);
        const msg = xhr.responseJSON?.message || 'Failed to process transaction';
        alert('Error: ' + msg);
      }
    });
  });
  
  // Initial load
  loadPendingTransactions();
  loadGLPostings();
  loadTodayApproved();
  
  // Auto refresh every 60 seconds
  setInterval(function() {
    loadPendingTransactions();
    loadGLPostings();
  }, 60000);
})();
</script>
