<?php require_once __DIR__ . '/../includes/auth.php'; 
require_login(); 
?>
<div class="page-petty-cash">
  <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-wallet me-2"></i>Petty Cash Management</h4>
      <div class="d-flex gap-2">
        <span class="badge bg-secondary" id="systemBadge">Imprest System</span>
        <button class="btn btn-outline-primary btn-sm" onclick="refreshAllData()">
          <i class="bi bi-arrow-repeat me-1"></i>Refresh
        </button>
      </div>
    </div>

    <!-- Alert Banner for Low Balance -->
    <div id="lowBalanceAlert" class="alert alert-warning alert-dismissible fade show d-none" role="alert">
      <div class="d-flex align-items-center">
        <i class="bi bi-exclamation-triangle-fill fs-4 me-3"></i>
        <div>
          <strong>Low Petty Cash Balance!</strong>
          <span id="alertMessage">Current balance is below the warning threshold.</span>
          <button class="btn btn-sm btn-warning ms-3" onclick="openReplenishmentModal()">
            <i class="bi bi-plus-circle me-1"></i>Replenish Now
          </button>
        </div>
      </div>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    <!-- Section 1: Petty Cash Float Overview -->
    <div class="card shadow-sm mb-4 border-info">
      <div class="card-header bg-info text-white d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-safe me-2"></i>Petty Cash Float Status</h5>
        <button class="btn btn-sm btn-light" onclick="openFloatSetupModal()">
          <i class="bi bi-gear me-1"></i>Configure
        </button>
      </div>
      <div class="card-body">
        <div class="row g-3" id="floatStatusContainer">
          <div class="col-12 text-center py-3 text-muted">
            <div class="spinner-border spinner-border-sm me-2"></div>Loading float status...
          </div>
        </div>
      </div>
    </div>

    <!-- Section 2: Quick Actions Row -->
    <div class="row g-3 mb-4">
      <div class="col-md-4">
        <button class="btn btn-success w-100 h-100 py-3" onclick="openVoucherModal()">
          <i class="bi bi-plus-circle fs-3 d-block mb-2"></i>
          <strong>New Petty Cash Voucher</strong>
          <small class="d-block text-white-50">Record expense payment</small>
        </button>
      </div>
      <div class="col-md-4">
        <button class="btn btn-primary w-100 h-100 py-3" onclick="openReplenishmentModal()">
          <i class="bi bi-arrow-left-right fs-3 d-block mb-2"></i>
          <strong>Replenish Petty Cash</strong>
          <small class="d-block text-white-50">Transfer from bank account</small>
        </button>
      </div>
      <div class="col-md-4">
        <button class="btn btn-warning w-100 h-100 py-3" onclick="openReconciliationModal()">
          <i class="bi bi-clipboard-check fs-3 d-block mb-2"></i>
          <strong>Reconcile & Post</strong>
          <small class="d-block text-dark">Review and lock vouchers</small>
        </button>
      </div>
    </div>

    <!-- Section 3: Recent Vouchers -->
    <div class="card shadow-sm mb-4">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-receipt me-2"></i>Recent Petty Cash Vouchers</h5>
        <div class="d-flex gap-2 align-items-center">
          <input type="date" id="voucherFromDate" class="form-control form-control-sm" style="width: 130px;" placeholder="From Date" onchange="loadRecentVouchers()">
          <input type="date" id="voucherToDate" class="form-control form-control-sm" style="width: 130px;" placeholder="To Date" onchange="loadRecentVouchers()">
          <select id="voucherStatusFilter" class="form-select form-select-sm" style="width: 120px;" onchange="loadRecentVouchers()">
            <option value="">All Status</option>
            <option value="Pending">Pending</option>
            <option value="Posted">Posted</option>
            <option value="Cancelled">Cancelled</option>
          </select>
          <button class="btn btn-sm btn-outline-primary" onclick="loadRecentVouchers()">
            <i class="bi bi-arrow-repeat"></i>
          </button>
        </div>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive" style="max-height: 400px;">
          <table class="table table-sm table-hover mb-0" id="vouchersTable">
            <thead class="table-light sticky-top">
              <tr>
                <th>Voucher #</th>
                <th>Date</th>
                <th>Category</th>
                <th>Recipient</th>
                <th>Narration</th>
                <th class="text-end">Amount</th>
                <th>Receipt</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Section 4: Pending Replenishment Vouchers -->
    <div class="card shadow-sm mb-3">
      <div class="card-header bg-warning text-dark d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-hourglass-split me-2"></i>Replenishment Vouchers (Cash Book)</h5>
        <button class="btn btn-sm btn-outline-dark" onclick="loadReplenishmentVouchers()"><i class="bi bi-arrow-repeat"></i></button>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive" style="max-height:220px;">
          <table class="table table-sm table-hover mb-0" id="replenVouchersTable">
            <thead class="table-light sticky-top">
              <tr>
                <th>Date</th>
                <th>Cash Book Voucher</th>
                <th>Bank Account</th>
                <th class="text-end">Amount</th>
                <th>Reference</th>
                <th>Voucher Status</th>
                <th>Replenish Status</th>
              </tr>
            </thead>
            <tbody><tr><td colspan="7" class="text-center text-muted py-3">Loading...</td></tr></tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Section 5: Replenishment History -->
    <div class="card shadow-sm">
      <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-clock-history me-2"></i>Replenishment History (Completed)</h5>
        <div class="d-flex gap-2 align-items-center">
          <input type="date" id="replenishFromDate" class="form-control form-control-sm" style="width: 130px;" placeholder="From Date" onchange="loadReplenishmentHistory()">
          <input type="date" id="replenishToDate" class="form-control form-control-sm" style="width: 130px;" placeholder="To Date" onchange="loadReplenishmentHistory()">
          <button class="btn btn-sm btn-light" onclick="loadReplenishmentHistory()">
            <i class="bi bi-arrow-repeat"></i>
          </button>
        </div>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive" style="max-height: 250px;">
          <table class="table table-sm table-hover mb-0" id="replenishmentTable">
            <thead class="table-light sticky-top">
              <tr>
                <th>Date</th>
                <th>Contra Voucher</th>
                <th>From Bank Account</th>
                <th class="text-end">Amount</th>
                <th>Reference</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Float Setup Modal -->
<div class="modal fade" id="floatSetupModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-info text-white">
        <h5 class="modal-title"><i class="bi bi-gear me-2"></i>Configure Petty Cash Float</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
        <input type="hidden" id="floatId">
        
        <div class="mb-3">
          <label class="form-label">Float Name</label>
          <input type="text" id="floatName" class="form-control" value="Main Petty Cash">
        </div>
        
        <div class="mb-3">
          <label class="form-label">Float Limit (Max Balance) <span class="text-danger">*</span></label>
          <div class="input-group">
            <span class="input-group-text">LKR</span>
            <input type="number" id="floatLimit" class="form-control" value="25000" min="1000" step="100">
          </div>
          <div class="form-text">Maximum amount petty cash can hold</div>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Warning Threshold <span class="text-danger">*</span></label>
          <div class="input-group">
            <span class="input-group-text">LKR</span>
            <input type="number" id="warningThreshold" class="form-control" value="5000" min="500" step="100">
          </div>
          <div class="form-text">Alert when balance drops below this amount</div>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Linked Bank Account (for replenishment)</label>
          <select id="linkedBankAccount" class="form-select">
            <option value="">-- Select Default Bank --</option>
          </select>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Cost Center</label>
          <select id="costCenter" class="form-select">
            <option value="Head Office">Head Office</option>
            <option value="Yakkala Branch">Yakkala Branch</option>
            <option value="Negambo Branch">Negambo Branch</option>
          </select>
        </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-info text-white" onclick="saveFloatSetup()">Save Configuration</button>
      </div>
    </div>
  </div>
</div>

<!-- Replenishment Modal -->
<div class="modal fade" id="replenishmentModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title"><i class="bi bi-arrow-left-right me-2"></i>Replenish Petty Cash (Imprest)</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="alert alert-info">
          <i class="bi bi-info-circle me-2"></i>
          This creates a <strong>Payment cash book voucher</strong> under <em>Petty Cash Top Up</em> account head. Once the voucher is <strong>approved</strong> in the Cash Book, petty cash will be replenished automatically.
        </div>
        
        <div class="mb-3">
          <label class="form-label">Current Petty Cash Balance</label>
          <div class="form-control bg-light fw-bold" id="currentBalanceDisplay">LKR 0.00</div>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Float Limit</label>
          <div class="form-control bg-light" id="floatLimitDisplay">LKR 25,000.00</div>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Replenishment Amount <span class="text-danger">*</span></label>
          <div class="input-group">
            <span class="input-group-text">LKR</span>
            <input type="number" id="replenishmentAmount" class="form-control" min="1" step="100">
          </div>
          <div class="form-text text-success" id="replenishmentSuggestion"></div>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Source Bank Account <span class="text-danger">*</span></label>
          <select id="sourceBankAccount" class="form-select" required>
            <option value="">-- Select Bank Account --</option>
          </select>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Date</label>
          <input type="date" id="replenishmentDate" class="form-control" value="<?php echo date('Y-m-d'); ?>">
        </div>
        
        <div class="mb-3">
          <label class="form-label">Reference Number</label>
          <input type="text" id="referenceNo" class="form-control" placeholder="Cheque number, transfer ref, etc.">
        </div>
        
        <div class="mb-3">
          <label class="form-label">Narration</label>
          <textarea id="replenishmentNarration" class="form-control" rows="2">Petty cash replenishment</textarea>
        </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" onclick="createReplenishmentVoucher()">
          <i class="bi bi-receipt me-1"></i>Create Cash Book Voucher
        </button>
      </div>
    </div>
  </div>
</div>

<!-- New Voucher Modal -->
<div class="modal fade" id="voucherModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title"><i class="bi bi-receipt me-2"></i>New Petty Cash Voucher</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="voucherForm" enctype="multipart/form-data">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          
          <div class="row g-3">
            <!-- Balance Warning -->
            <div class="col-12">
              <div class="alert d-none" id="voucherBalanceAlert" role="alert">
                <i class="bi bi-exclamation-triangle-fill me-2"></i>
                <span id="voucherAlertMessage"></span>
              </div>
            </div>
            
            <div class="col-md-4">
              <label class="form-label">Voucher Number <span class="text-muted">(Auto)</span></label>
              <input type="text" id="voucherNumber" class="form-control bg-light" readonly placeholder="PCV/YYYY/MMDD/XXXX">
            </div>
            
            <div class="col-md-4">
              <label class="form-label">Date <span class="text-danger">*</span></label>
              <input type="date" name="voucher_date" id="voucherDate" class="form-control" required value="<?php echo date('Y-m-d'); ?>">
            </div>
            
            <div class="col-md-4">
              <label class="form-label">Petty Cash Float <span class="text-danger">*</span></label>
              <select name="float_id" id="voucherFloatId" class="form-select" required onchange="checkVoucherBalance()">
                <option value="">-- Select Float --</option>
              </select>
            </div>
            
            <div class="col-md-6">
              <label class="form-label">Expense Category <span class="text-danger">*</span></label>
              <select name="expense_account_head" id="expenseCategory" class="form-select" required onchange="updateAccountHead()">
                <option value="">-- Select Category --</option>
              </select>
            </div>
            
            <div class="col-md-6">
              <label class="form-label">Account Head</label>
              <input type="text" name="sub_account_head" id="accountHead" class="form-control" readonly>
            </div>
            
            <div class="col-md-6">
              <label class="form-label">Amount (LKR) <span class="text-danger">*</span></label>
              <div class="input-group">
                <span class="input-group-text">LKR</span>
                <input type="number" name="amount" id="voucherAmount" class="form-control" min="1" step="0.01" required oninput="checkVoucherBalance()">
              </div>
              <div class="form-text text-danger d-none" id="amountError">
                <i class="bi bi-x-circle"></i> Amount exceeds available balance!
              </div>
            </div>
            
            <div class="col-md-6">
              <label class="form-label">Cost Center</label>
              <select name="cost_center" id="voucherCostCenter" class="form-select">
                <option value="Head Office">Head Office</option>
                <option value="Yakkala Branch">Yakkala Branch</option>
                <option value="Negambo Branch">Negambo Branch</option>
              </select>
            </div>
            
            <div class="col-md-6">
              <label class="form-label">Recipient Name <span class="text-danger">*</span></label>
              <input type="text" name="recipient_name" id="recipientName" class="form-control" required placeholder="Who received the cash">
            </div>
            
            <div class="col-md-6">
              <label class="form-label">Recipient ID/Contact</label>
              <input type="text" name="recipient_contact" id="recipientContact" class="form-control" placeholder="Phone or ID number">
            </div>
            
            <div class="col-12">
              <label class="form-label">Narration / Description <span class="text-danger">*</span></label>
              <textarea name="narration" id="voucherNarration" class="form-control" rows="2" required placeholder="Describe the expense..."></textarea>
            </div>
            
            <div class="col-12">
              <label class="form-label">Receipt Image <span class="text-muted">(Optional but recommended)</span></label>
              <input type="file" name="receipt_image" id="receiptImage" class="form-control" accept="image/*,.pdf">
              <div class="form-text">Upload receipt photo or scanned document</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-success" id="btnSubmitVoucher" onclick="submitVoucher()">
          <i class="bi bi-check-circle me-1"></i>Create Voucher
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Reconciliation Modal -->
<div class="modal fade" id="reconciliationModal" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header bg-warning">
        <h5 class="modal-title"><i class="bi bi-clipboard-check me-2"></i>Petty Cash Reconciliation</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="row mb-3">
          <div class="col-md-4">
            <label class="form-label">Petty Cash Float</label>
            <select id="reconFloatId" class="form-select" onchange="loadReconciliationData()">
              <option value="">-- Select --</option>
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label">From Date</label>
            <input type="date" id="reconDateFrom" class="form-control" value="<?php echo date('Y-m-01'); ?>">
          </div>
          <div class="col-md-3">
            <label class="form-label">To Date</label>
            <input type="date" id="reconDateTo" class="form-control" value="<?php echo date('Y-m-d'); ?>">
          </div>
          <div class="col-md-2">
            <label class="form-label">&nbsp;</label>
            <button class="btn btn-warning w-100" onclick="loadReconciliationData()">
              <i class="bi bi-search"></i> Load
            </button>
          </div>
        </div>

        <!-- Summary Cards -->
        <div class="row g-2 mb-3">
          <div class="col-md-3">
            <div class="card bg-light">
              <div class="card-body text-center py-2">
                <small class="text-muted">Float Limit</small>
                <div class="fw-bold" id="reconFloatLimit">LKR 0.00</div>
              </div>
            </div>
          </div>
          <div class="col-md-3">
            <div class="card bg-light">
              <div class="card-body text-center py-2">
                <small class="text-muted">Current Balance</small>
                <div class="fw-bold" id="reconCurrentBalance">LKR 0.00</div>
              </div>
            </div>
          </div>
          <div class="col-md-3">
            <div class="card bg-info text-white">
              <div class="card-body text-center py-2">
                <small>Total Posted</small>
                <div class="fw-bold" id="reconPostedTotal">LKR 0.00</div>
              </div>
            </div>
          </div>
          <div class="col-md-3">
            <div class="card bg-success text-white">
              <div class="card-body text-center py-2">
                <small>Replenishment Needed</small>
                <div class="fw-bold" id="reconReplenishmentNeeded">LKR 0.00</div>
              </div>
            </div>
          </div>
        </div>

        <!-- Pending Vouchers -->
        <div class="card border-warning mb-3">
          <div class="card-header bg-warning text-dark d-flex justify-content-between">
            <strong><i class="bi bi-clock-history me-2"></i>Pending Vouchers (To be Posted)</strong>
            <button class="btn btn-sm btn-dark" id="btnPostAll" onclick="postAllPending()" disabled>
              <i class="bi bi-check-all me-1"></i>Post All
            </button>
          </div>
          <div class="card-body p-0">
            <div class="table-responsive" style="max-height: 250px;">
              <table class="table table-sm table-hover mb-0" id="pendingVouchersTable">
                <thead class="table-light sticky-top">
                  <tr>
                    <th><input type="checkbox" id="selectAllPending" onchange="toggleSelectAll()"></th>
                    <th>Voucher #</th>
                    <th>Date</th>
                    <th>Category</th>
                    <th>Recipient</th>
                    <th>Narration</th>
                    <th class="text-end">Amount</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>

        <!-- Posted Vouchers -->
        <div class="card border-success">
          <div class="card-header bg-success text-white">
            <strong><i class="bi bi-check-circle me-2"></i>Posted Vouchers (Locked)</strong>
          </div>
          <div class="card-body p-0">
            <div class="table-responsive" style="max-height: 200px;">
              <table class="table table-sm table-hover mb-0" id="postedVouchersTable">
                <thead class="table-light sticky-top">
                  <tr>
                    <th>Voucher #</th>
                    <th>Date</th>
                    <th>Category</th>
                    <th>Recipient</th>
                    <th>Narration</th>
                    <th class="text-end">Amount</th>
                    <th>Posted By</th>
                    <th>Posted At</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">Close</button>
        <button type="button" class="btn btn-primary" onclick="openReplenishmentModal()">
          <i class="bi bi-plus-circle me-1"></i>Replenish Now
        </button>
      </div>
    </div>
  </div>
</div>

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

  const csrf = $('#csrf').val();
  let currentFloats = [];
  let expenseCategories = [];
  let bankAccounts = [];

  // 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 float status
  function loadFloatStatus() {
    $.get('api/petty_cash.php', { action: 'get_float_status' }, function(res) {
      currentFloats = res.data || [];
      const $container = $('#floatStatusContainer');
      $container.empty();

      let hasLowBalance = false;
      let lowBalanceMessage = '';

      // Update dropdowns
      updateFloatDropdowns();

      if (currentFloats.length === 0) {
        $container.html('<div class="col-12 text-center py-3 text-muted">No petty cash floats configured. Click Configure to set up.</div>');
        return;
      }

      currentFloats.forEach(function(float) {
        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');
        
        if (float.balance_status === 'CRITICAL' || float.balance_status === 'LOW') {
          hasLowBalance = true;
          lowBalanceMessage = `Petty cash balance (${formatCurrency(float.current_balance)}) is below threshold (${formatCurrency(float.warning_threshold)})`;
        }

        const utilizationWidth = Math.min(100, float.utilization_percent);
        const progressClass = float.utilization_percent > 80 ? 'bg-danger' : 
                             (float.utilization_percent > 50 ? 'bg-warning' : 'bg-success');

        const card = `
          <div class="col-md-6 col-lg-4">
            <div class="card h-100 ${balanceStatusClass} border-2">
              <div class="card-header d-flex justify-content-between align-items-center">
                <strong>${escapeHtml(float.float_name)}</strong>
                <span class="badge ${float.is_active ? 'bg-success' : 'bg-secondary'}">${float.is_active ? 'Active' : 'Inactive'}</span>
              </div>
              <div class="card-body">
                <div class="mb-3">
                  <div class="d-flex justify-content-between mb-1">
                    <small class="text-muted">Current Balance</small>
                    <small class="${balanceTextClass} fw-bold">${float.balance_status}</small>
                  </div>
                  <h4 class="${balanceTextClass} mb-0">${formatCurrency(float.current_balance)}</h4>
                </div>
                
                <div class="mb-3">
                  <div class="d-flex justify-content-between">
                    <small class="text-muted">Float Limit</small>
                    <small>${formatCurrency(float.float_limit)}</small>
                  </div>
                  <div class="progress" style="height: 8px;">
                    <div class="progress-bar ${progressClass}" style="width: ${utilizationWidth}%"></div>
                  </div>
                </div>
                
                <div class="row g-2 text-center">
                  <div class="col-6">
                    <small class="text-muted d-block">Warning At</small>
                    <strong>${formatCurrency(float.warning_threshold)}</strong>
                  </div>
                  <div class="col-6">
                    <small class="text-muted d-block">Replenish Need</small>
                    <strong class="${float.replenishment_needed > 0 ? 'text-success' : 'text-muted'}">
                      ${formatCurrency(float.replenishment_needed)}
                    </strong>
                  </div>
                </div>
                
                ${float.linked_bank_name ? `
                  <div class="mt-2 pt-2 border-top">
                    <small class="text-muted">Linked: ${escapeHtml(float.linked_bank_name)}</small>
                  </div>
                ` : ''}
              </div>
            </div>
          </div>
        `;
        $container.append(card);
      });

      // Show/hide low balance alert
      if (hasLowBalance) {
        $('#lowBalanceAlert').removeClass('d-none');
        $('#alertMessage').text(lowBalanceMessage);
      } else {
        $('#lowBalanceAlert').addClass('d-none');
      }
    }).fail(function(xhr) {
      $('#floatStatusContainer').html('<div class="col-12 text-center text-danger py-3">Failed to load float status</div>');
    });
  }

  // Update all float dropdowns
  function updateFloatDropdowns() {
    const options = currentFloats.map(f => `<option value="${f.id}">${escapeHtml(f.float_name)} - ${formatCurrency(f.current_balance)}</option>`).join('');
    
    $('#voucherFloatId').html('<option value="">-- Select Float --</option>' + options);
    $('#reconFloatId').html('<option value="">-- Select --</option>' + options);
  }

  // Load bank accounts for dropdowns
  function loadBankAccounts() {
    $.get('api/finance.php', { action: 'list_bank_accounts', is_active: 1 }, function(res) {
      bankAccounts = res.data || [];
      const options = bankAccounts.map(ba => `<option value="${ba.id}">${escapeHtml(ba.account_name)} - ${formatCurrency(ba.current_balance, ba.currency)}</option>`).join('');
      
      $('#linkedBankAccount').html('<option value="">-- Select Default Bank --</option>' + options);
      $('#sourceBankAccount').html('<option value="">-- Select Bank Account --</option>' + options);
    });
  }

  // Load expense categories
  function loadExpenseCategories() {
    $.get('api/petty_cash.php', { action: 'get_expense_categories' }, function(res) {
      expenseCategories = res.data || [];
      const options = expenseCategories.map(cat => `<option value="${cat.category_name}" data-head="${cat.account_head}">${escapeHtml(cat.category_name)}</option>`).join('');
      
      $('#expenseCategory').html('<option value="">-- Select Category --</option>' + options);
    });
  }

  // Update account head based on category selection
  function updateAccountHead() {
    const selected = $('#expenseCategory option:selected');
    const accountHead = selected.data('head') || '';
    $('#accountHead').val(accountHead);
  }

  // Check voucher balance before submission
  function checkVoucherBalance() {
    const floatId = $('#voucherFloatId').val();
    const amount = parseFloat($('#voucherAmount').val()) || 0;
    
    if (!floatId) return;
    
    const float = currentFloats.find(f => f.id == floatId);
    if (!float) return;
    
    const available = parseFloat(float.current_balance);
    
    if (amount > available) {
      $('#amountError').removeClass('d-none');
      $('#btnSubmitVoucher').prop('disabled', true);
    } else {
      $('#amountError').addClass('d-none');
      $('#btnSubmitVoucher').prop('disabled', false);
    }
    
    // Show warning if balance is low
    if (available <= float.warning_threshold) {
      $('#voucherBalanceAlert').removeClass('d-none alert-info').addClass('alert-warning');
      $('#voucherAlertMessage').text(`Low balance warning: Only ${formatCurrency(available)} available. Replenishment recommended.`);
    } else {
      $('#voucherBalanceAlert').addClass('d-none');
    }
  }

  // Load recent vouchers
  function loadRecentVouchers() {
    const status = $('#voucherStatusFilter').val();
    const fromDate = $('#voucherFromDate').val();
    const toDate = $('#voucherToDate').val();
    
    $.get('api/petty_cash.php', { action: 'list_vouchers', status: status, from_date: fromDate, to_date: toDate }, function(res) {
      const $tbody = $('#vouchersTable tbody');
      $tbody.empty();
      
      (res.data || []).forEach(function(voucher) {
        const statusBadge = voucher.status === 'Posted' ? 'bg-success' : 
                           (voucher.status === 'Pending' ? 'bg-warning' : 
                           (voucher.status === 'Cancelled' ? 'bg-danger' : 'bg-secondary'));
        
        const row = `
          <tr>
            <td><code class="fw-bold">${escapeHtml(voucher.voucher_number)}</code></td>
            <td>${voucher.voucher_date}</td>
            <td>${escapeHtml(voucher.expense_account_head)}</td>
            <td>${escapeHtml(voucher.recipient_name)}</td>
            <td><small>${escapeHtml(voucher.narration)}</small></td>
            <td class="text-end fw-bold">${formatCurrency(voucher.amount)}</td>
            <td class="text-center">
              ${voucher.has_receipt ? '<i class="bi bi-paperclip text-success" title="Has receipt"></i>' : '<i class="bi bi-dash text-muted"></i>'}
            </td>
            <td><span class="badge ${statusBadge}">${voucher.status}</span></td>
            <td>
              <button class="btn btn-sm btn-outline-primary me-1" onclick="printVoucher(${voucher.id})" title="Print">
                <i class="bi bi-printer"></i>
              </button>
              ${voucher.status === 'Pending' ? `
                <button class="btn btn-sm btn-danger" onclick="cancelVoucher(${voucher.id})">
                  <i class="bi bi-x-circle"></i>
                </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 vouchers found</td></tr>');
      }
    });
  }

  // Load replenishment history
  function loadReplenishmentHistory() {
    const floatId = currentFloats.length > 0 ? currentFloats[0].id : 0;
    const fromDate = $('#replenishFromDate').val();
    const toDate = $('#replenishToDate').val();
    
    $.ajax({
      url: 'api/petty_cash.php',
      method: 'GET',
      data: { action: 'list_replenishments', float_id: floatId, from_date: fromDate, to_date: toDate, limit: 20 },
      success: function(res) {
        const replenishments = res.data || [];
        const $tbody = $('#replenishmentTable tbody');
        $tbody.empty();
        
        if (replenishments.length === 0) {
          $tbody.html('<tr><td colspan="6" class="text-center text-muted py-3">No replenishments recorded</td></tr>');
          return;
        }
        
        replenishments.forEach(function(r) {
          const row = `
            <tr>
              <td>${formatDate(r.replenishment_date)}</td>
              <td>${r.contra_voucher_number || '-'}</td>
              <td>${r.source_bank || '-'}<br><small class="text-muted">${r.source_bank_name || ''}</small></td>
              <td class="text-end fw-bold text-success">${formatCurrency(r.amount)}</td>
              <td>${r.reference_no || '-'}</td>
              <td>${r.performed_by_name || '-'}</td>
            </tr>
          `;
          $tbody.append(row);
        });
      },
      error: function(xhr) {
        $('#replenishmentTable tbody').html('<tr><td colspan="6" class="text-center text-danger py-3">Failed to load replenishments</td></tr>');
      }
    });
  }
  
  // Helper to format date
  function formatDate(dateStr) {
    if (!dateStr) return '-';
    const d = new Date(dateStr);
    return d.toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' });
  }

  // Modal functions
  function openFloatSetupModal() {
    if (currentFloats.length > 0) {
      const float = currentFloats[0];
      $('#floatId').val(float.id);
      $('#floatName').val(float.float_name);
      $('#floatLimit').val(float.float_limit);
      $('#warningThreshold').val(float.warning_threshold);
      $('#linkedBankAccount').val(float.linked_bank_account_id || '');
      $('#costCenter').val(float.cost_center);
    }
    new bootstrap.Modal(document.getElementById('floatSetupModal')).show();
  }

  function openReplenishmentModal() {
    if (currentFloats.length === 0) {
      alert('Please configure petty cash float first');
      return;
    }
    
    const float = currentFloats[0];
    $('#currentBalanceDisplay').text(formatCurrency(float.current_balance));
    $('#floatLimitDisplay').text(formatCurrency(float.float_limit));
    
    // Calculate suggested replenishment
    const needed = float.float_limit - float.current_balance;
    $('#replenishmentAmount').val(needed > 0 ? needed : '');
    $('#replenishmentSuggestion').text(needed > 0 ? `Suggested: ${formatCurrency(needed)} to reach float limit` : 'Float is at maximum');
    
    new bootstrap.Modal(document.getElementById('replenishmentModal')).show();
  }

  function openVoucherModal() {
    if (currentFloats.length === 0) {
      alert('Please configure petty cash float first');
      return;
    }
    
    // Generate voucher number preview
    const today = new Date();
    const nextNum = '0001'; // This would ideally come from the server
    $('#voucherNumber').val(`PCV/${today.getFullYear()}/${String(today.getMonth()+1).padStart(2,'0')}${String(today.getDate()).padStart(2,'0')}/${nextNum}`);
    
    new bootstrap.Modal(document.getElementById('voucherModal')).show();
  }

  function openReconciliationModal() {
    new bootstrap.Modal(document.getElementById('reconciliationModal')).show();
    if ($('#reconFloatId').val()) {
      loadReconciliationData();
    }
  }

  // Save float setup
  function saveFloatSetup() {
    const formData = new FormData();
    formData.append('action', 'update_float');
    formData.append('csrf', csrf);
    formData.append('float_id', $('#floatId').val());
    formData.append('float_name', $('#floatName').val());
    formData.append('float_limit', $('#floatLimit').val());
    formData.append('warning_threshold', $('#warningThreshold').val());
    formData.append('linked_bank_account_id', $('#linkedBankAccount').val());
    formData.append('cost_center', $('#costCenter').val());
    
    $.ajax({
      url: 'api/petty_cash.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(res) {
        $('#floatSetupModal').modal('hide');
        alert('Float configuration saved!');
        loadFloatStatus();
      },
      error: function(xhr) {
        alert('Error: ' + (xhr.responseJSON?.message || 'Failed to save'));
      }
    });
  }

  // Create replenishment cash book voucher (new flow)
  function createReplenishmentVoucher() {
    const amount = parseFloat($('#replenishmentAmount').val());
    const bankId = $('#sourceBankAccount').val();
    
    if (!amount || amount <= 0) {
      alert('Please enter a valid amount');
      return;
    }
    
    if (!bankId) {
      alert('Please select a source bank account');
      return;
    }
    
    const formData = new FormData();
    formData.append('action', 'create_replenishment_voucher');
    formData.append('csrf', csrf);
    formData.append('float_id', currentFloats[0]?.id || 1);
    formData.append('bank_account_id', bankId);
    formData.append('amount', amount);
    formData.append('voucher_date', $('#replenishmentDate').val());
    formData.append('reference_no', $('#referenceNo').val());
    formData.append('narration', $('#replenishmentNarration').val() || 'Petty Cash Top Up');
    
    $.ajax({
      url: 'api/petty_cash.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(res) {
        $('#replenishmentModal').modal('hide');
        alert(`Cash book voucher created!\nVoucher No: ${res.voucher_number}\nStatus: Pending Approval\n\nGo to Cash Book to approve this voucher. Once approved, petty cash will be replenished automatically.`);
        loadReplenishmentVouchers();
        loadReplenishmentHistory();
      },
      error: function(xhr) {
        alert('Error: ' + (xhr.responseJSON?.message || 'Failed to create voucher'));
      }
    });
  }

  // Load replenishment cash book vouchers
  function loadReplenishmentVouchers() {
    const floatId = currentFloats.length > 0 ? currentFloats[0].id : 0;
    $.get('api/petty_cash.php', { action: 'list_replenishment_vouchers', float_id: floatId }, function(res) {
      const rows = res.data || [];
      const $tbody = $('#replenVouchersTable tbody');
      $tbody.empty();
      if (!rows.length) {
        $tbody.html('<tr><td colspan="7" class="text-center text-muted py-3">No replenishment vouchers found</td></tr>');
        return;
      }
      rows.forEach(function(r) {
        const vStatus = r.voucher_status || '-';
        const vBadge = vStatus === 'Approved' ? 'bg-success' : vStatus === 'Rejected' ? 'bg-danger' : 'bg-warning text-dark';
        const rStatus = r.status || '-';
        const rBadge = rStatus === 'Completed' ? 'bg-success' : rStatus === 'Pending' ? 'bg-warning text-dark' : 'bg-secondary';
        $tbody.append(`
          <tr>
            <td>${formatDate(r.replenishment_date)}</td>
            <td><code>${escapeHtml(r.cash_book_voucher || r.contra_voucher_number || '-')}</code></td>
            <td>${escapeHtml(r.bank_name || '-')}</td>
            <td class="text-end fw-bold">${formatCurrency(r.amount)}</td>
            <td>${escapeHtml(r.reference_no ? r.reference_no.replace(/^TXN:\d+\|?/, '').replace(/^REF:/, '') : '-')}</td>
            <td><span class="badge ${vBadge}">${vStatus}</span></td>
            <td><span class="badge ${rBadge}">${rStatus}</span></td>
          </tr>
        `);
      });
    }).fail(function() {
      $('#replenVouchersTable tbody').html('<tr><td colspan="7" class="text-center text-danger py-3">Failed to load</td></tr>');
    });
  }

  // Submit voucher
  function submitVoucher() {
    const formData = new FormData($('#voucherForm')[0]);
    formData.append('action', 'create_voucher');
    formData.append('csrf', csrf);
    formData.append('float_id', $('#voucherFloatId').val());
    formData.append('sub_account_head', $('#accountHead').val());
    
    $.ajax({
      url: 'api/petty_cash.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(res) {
        $('#voucherModal').modal('hide');
        alert(`Voucher created!\nNumber: ${res.voucher_number}\nRemaining Balance: ${formatCurrency(res.remaining_balance)}`);
        $('#voucherForm')[0].reset();
        loadFloatStatus();
        loadRecentVouchers();
      },
      error: function(xhr) {
        const resp = xhr.responseJSON;
        if (resp?.error_type === 'INSUFFICIENT_BALANCE') {
          alert(`Insufficient petty cash balance!\nAvailable: ${formatCurrency(resp.current_balance)}\nShortfall: ${formatCurrency(resp.shortfall)}`);
        } else {
          alert('Error: ' + (resp?.message || 'Failed to create voucher'));
        }
      }
    });
  }

  // Cancel voucher
  function cancelVoucher(voucherId) {
    if (!confirm('Cancel this voucher? The amount will be restored to petty cash.')) return;
    
    const formData = new FormData();
    formData.append('action', 'cancel_voucher');
    formData.append('csrf', csrf);
    formData.append('voucher_id', voucherId);
    formData.append('reason', 'User cancelled');
    
    $.ajax({
      url: 'api/petty_cash.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function() {
        alert('Voucher cancelled successfully');
        loadFloatStatus();
        loadRecentVouchers();
      },
      error: function(xhr) {
        alert('Error: ' + (xhr.responseJSON?.message || 'Failed to cancel'));
      }
    });
  }

  // Load reconciliation data
  function loadReconciliationData() {
    const floatId = $('#reconFloatId').val();
    if (!floatId) return;
    
    $.get('api/petty_cash.php', {
      action: 'get_reconciliation_data',
      float_id: floatId,
      date_from: $('#reconDateFrom').val(),
      date_to: $('#reconDateTo').val()
    }, function(res) {
      const data = res.data;
      
      // Update summary
      $('#reconFloatLimit').text(formatCurrency(data.float.float_limit));
      $('#reconCurrentBalance').text(formatCurrency(data.float.current_balance));
      $('#reconPostedTotal').text(formatCurrency(data.posted_total));
      $('#reconReplenishmentNeeded').text(formatCurrency(data.replenishment_needed));
      
      // Pending vouchers
      const $pendingBody = $('#pendingVouchersTable tbody');
      $pendingBody.empty();
      
      data.pending_vouchers.forEach(function(v) {
        const row = `
          <tr>
            <td><input type="checkbox" class="pending-checkbox" value="${v.id}"></td>
            <td><code>${escapeHtml(v.voucher_number)}</code></td>
            <td>${v.voucher_date}</td>
            <td>${escapeHtml(v.expense_account_head)}</td>
            <td>${escapeHtml(v.recipient_name)}</td>
            <td><small>${escapeHtml(v.narration)}</small></td>
            <td class="text-end fw-bold">${formatCurrency(v.amount)}</td>
            <td>
              <button class="btn btn-sm btn-success" onclick="postVoucher(${v.id})">
                <i class="bi bi-check"></i> Post
              </button>
            </td>
          </tr>
        `;
        $pendingBody.append(row);
      });
      
      if (data.pending_vouchers.length === 0) {
        $pendingBody.append('<tr><td colspan="8" class="text-center text-muted py-3">No pending vouchers</td></tr>');
      }
      
      $('#btnPostAll').prop('disabled', data.pending_vouchers.length === 0);
      
      // Posted vouchers
      const $postedBody = $('#postedVouchersTable tbody');
      $postedBody.empty();
      
      data.posted_vouchers.forEach(function(v) {
        const row = `
          <tr class="table-success">
            <td><code>${escapeHtml(v.voucher_number)}</code></td>
            <td>${v.voucher_date}</td>
            <td>${escapeHtml(v.expense_account_head)}</td>
            <td>${escapeHtml(v.recipient_name)}</td>
            <td><small>${escapeHtml(v.narration)}</small></td>
            <td class="text-end fw-bold">${formatCurrency(v.amount)}</td>
            <td><small>${escapeHtml(v.posted_by_name || '')}</small></td>
            <td><small>${v.posted_at}</small></td>
          </tr>
        `;
        $postedBody.append(row);
      });
      
      if (data.posted_vouchers.length === 0) {
        $postedBody.append('<tr><td colspan="8" class="text-center text-muted py-3">No posted vouchers</td></tr>');
      }
    });
  }

  // Post single voucher
  function postVoucher(voucherId) {
    const formData = new FormData();
    formData.append('action', 'post_voucher');
    formData.append('csrf', csrf);
    formData.append('voucher_id', voucherId);
    
    $.ajax({
      url: 'api/petty_cash.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function() {
        alert('Voucher posted successfully');
        loadReconciliationData();
        loadRecentVouchers();
      },
      error: function(xhr) {
        alert('Error: ' + (xhr.responseJSON?.message || 'Failed to post'));
      }
    });
  }

  // Post all selected
  function postAllPending() {
    const selected = $('.pending-checkbox:checked').map(function() { return $(this).val(); }).get();
    
    if (selected.length === 0) {
      alert('Please select at least one voucher');
      return;
    }
    
    if (!confirm(`Post ${selected.length} vouchers?`)) return;
    
    let completed = 0;
    selected.forEach(function(id) {
      const formData = new FormData();
      formData.append('action', 'post_voucher');
      formData.append('csrf', csrf);
      formData.append('voucher_id', id);
      
      $.ajax({
        url: 'api/petty_cash.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function() {
          completed++;
          if (completed === selected.length) {
            alert('All selected vouchers posted!');
            loadReconciliationData();
            loadRecentVouchers();
          }
        }
      });
    });
  }

  // Toggle select all
  function toggleSelectAll() {
    const checked = $('#selectAllPending').prop('checked');
    $('.pending-checkbox').prop('checked', checked);
  }

  // Refresh all data
  function refreshAllData() {
    loadFloatStatus();
    loadRecentVouchers();
    loadReplenishmentHistory();
    loadReplenishmentVouchers();
  }

  // Event handlers
  $('#replenishmentAmount').on('input', function() {
    const val = parseFloat($(this).val()) || 0;
    if (val > 0) {
      $('#replenishmentSuggestion').text('Manual amount entered');
    }
  });

  // Set default date range to current month
  const today = new Date();
  const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
  const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
  
  const formatDateInput = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };
  
  // Set voucher date filters
  $('#voucherFromDate').val(formatDateInput(firstDay));
  $('#voucherToDate').val(formatDateInput(lastDay));
  
  // Set replenishment date filters
  $('#replenishFromDate').val(formatDateInput(firstDay));
  $('#replenishToDate').val(formatDateInput(lastDay));
  
  // Initialize
  loadFloatStatus();
  loadBankAccounts();
  loadExpenseCategories();
  loadRecentVouchers();
  loadReplenishmentHistory();
  loadReplenishmentVouchers();

  // Print voucher function
  window.printVoucher = function(voucherId) {
    $.get('api/petty_cash.php', { action: 'get_voucher', id: voucherId }, function(res) {
      const v = res.data;
      if (!v) return;
      
      // Populate print modal
      $('#printVoucherNumber').text(v.voucher_number || '-');
      $('#printVoucherDate').text(v.voucher_date || '-');
      $('#printCostCenter').text(v.cost_center || '-');
      $('#printCategory').text(v.expense_account_head || '-');
      $('#printRecipient').text(v.recipient_name || '-');
      $('#printDescription').text(v.narration || '-');
      $('#printAmountWords').text(v.amount_in_words || '-');
      $('#printAmount').text(formatCurrency(v.amount || 0));
      $('#printTotalAmount').text(formatCurrency(v.amount || 0));
      $('#printStatus').text(v.status || '-');
      $('#printVoucherId').val(v.id);
      
      // Show modal
      new bootstrap.Modal(document.getElementById('printVoucherModal')).show();
    });
  };

  window.doPrintVoucher = function() {
    const printContents = document.getElementById('voucherPrintArea').innerHTML;
    const originalContents = document.body.innerHTML;
    
    document.body.innerHTML = `
      <div style="max-width: 800px; margin: 20px auto; font-family: Arial, sans-serif;">
        ${printContents}
      </div>
    `;
    window.print();
    document.body.innerHTML = originalContents;
    location.reload();
  };

  // Expose functions globally
  window.refreshAllData = refreshAllData;
  window.openFloatSetupModal = openFloatSetupModal;
  window.openReplenishmentModal = openReplenishmentModal;
  window.openVoucherModal = openVoucherModal;
  window.openReconciliationModal = openReconciliationModal;
  window.saveFloatSetup = saveFloatSetup;
  window.processReplenishment = processReplenishment;
  window.submitVoucher = submitVoucher;
  window.updateAccountHead = updateAccountHead;
  window.checkVoucherBalance = checkVoucherBalance;
  window.cancelVoucher = cancelVoucher;
  window.loadReconciliationData = loadReconciliationData;
  window.postVoucher = postVoucher;
  window.postAllPending = postAllPending;
  window.toggleSelectAll = toggleSelectAll;
})();
</script>

<!-- Print Voucher Modal -->
<div class="modal fade" id="printVoucherModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-printer me-2"></i>Petty Cash Voucher</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div id="voucherPrintArea" style="border: 2px solid #333; padding: 30px; background: #fff; font-family: 'Times New Roman', serif;">
          <!-- Company Header -->
          <div style="text-align: center; border-bottom: 3px double #333; padding-bottom: 15px; margin-bottom: 20px;">
            <h2 style="margin: 0; font-size: 24px; font-weight: bold;">PETTY CASH VOUCHER</h2>
            <p style="margin: 5px 0; font-size: 14px; color: #666;">SW Granite & Marble</p>
          </div>
          
          <!-- Voucher Info -->
          <table style="width: 100%; margin-bottom: 20px; font-size: 13px;">
            <tr>
              <td style="width: 50%; padding: 5px 0;"><strong>Voucher No:</strong> <span id="printVoucherNumber">-</span></td>
              <td style="width: 50%; padding: 5px 0; text-align: right;"><strong>Date:</strong> <span id="printVoucherDate">-</span></td>
            </tr>
            <tr>
              <td style="padding: 5px 0;"><strong>Status:</strong> <span id="printStatus">-</span></td>
              <td style="padding: 5px 0; text-align: right;"><strong>Cost Center:</strong> <span id="printCostCenter">-</span></td>
            </tr>
          </table>
          
          <!-- Payee & Category -->
          <table style="width: 100%; margin: 20px 0; font-size: 13px;">
            <tr style="border-bottom: 1px solid #ddd;">
              <td style="padding: 10px 0; width: 30%;"><strong>Paid To:</strong></td>
              <td style="padding: 10px 0; border-bottom: 1px dotted #999;"><span id="printRecipient">-</span></td>
            </tr>
            <tr style="border-bottom: 1px solid #ddd;">
              <td style="padding: 10px 0;"><strong>Expense Category:</strong></td>
              <td style="padding: 10px 0; border-bottom: 1px dotted #999;"><span id="printCategory">-</span></td>
            </tr>
          </table>
          
          <!-- Description and Amount Table -->
          <table style="width: 100%; margin: 20px 0; font-size: 13px; border-collapse: collapse; border: 1px solid #333;">
            <thead>
              <tr style="background: #f0f0f0;">
                <th style="border: 1px solid #333; padding: 10px; text-align: left; width: 70%;">Description</th>
                <th style="border: 1px solid #333; padding: 10px; text-align: right; width: 30%;">Amount (Rs.)</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td style="border: 1px solid #333; padding: 15px 10px; vertical-align: top;">
                  <span id="printDescription">-</span>
                </td>
                <td style="border: 1px solid #333; padding: 15px 10px; text-align: right; vertical-align: top; font-weight: bold;">
                  <span id="printAmount">0.00</span>
                </td>
              </tr>
            </tbody>
            <tfoot>
              <tr style="background: #f9f9f9;">
                <td style="border: 1px solid #333; padding: 10px; text-align: right;"><strong>Total:</strong></td>
                <td style="border: 1px solid #333; padding: 10px; text-align: right; font-weight: bold; font-size: 14px;">
                  <span id="printTotalAmount">0.00</span>
                </td>
              </tr>
            </tfoot>
          </table>
          
          <!-- Amount in Words -->
          <div style="border: 1px solid #999; padding: 15px; margin: 20px 0; background: #fafafa;">
            <strong>Amount in Words:</strong><br>
            <span id="printAmountWords" style="font-style: italic;">-</span>
          </div>
          
          <!-- Signature Section -->
          <div style="margin-top: 40px;">
            <table style="width: 100%;">
              <tr>
                <td style="width: 33%; text-align: center; padding: 10px;">
                  <div style="border-top: 1px solid #333; margin-top: 50px; padding-top: 5px;">
                    <small>Prepared By</small>
                  </div>
                </td>
                <td style="width: 33%; text-align: center; padding: 10px;">
                  <div style="border-top: 1px solid #333; margin-top: 50px; padding-top: 5px;">
                    <small>Authorized By</small>
                  </div>
                </td>
                <td style="width: 33%; text-align: center; padding: 10px;">
                  <div style="border-top: 1px solid #333; margin-top: 50px; padding-top: 5px;">
                    <small>Received By</small>
                  </div>
                </td>
              </tr>
            </table>
          </div>
          
          <!-- Footer -->
          <div style="margin-top: 30px; padding-top: 10px; border-top: 1px solid #ccc; text-align: center; font-size: 11px; color: #666;">
            <p style="margin: 0;">This is a computer generated voucher. No signature required unless stamped.</p>
            <p style="margin: 5px 0 0 0;">Generated on: <span id="printGeneratedDate"></span></p>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <input type="hidden" id="printVoucherId">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" onclick="doPrintVoucher()">
          <i class="bi bi-printer me-1"></i>Print Voucher
        </button>
      </div>
    </div>
  </div>
</div>

<script>
  // Set generated date when modal opens
  document.getElementById('printVoucherModal')?.addEventListener('show.bs.modal', function () {
    document.getElementById('printGeneratedDate').textContent = new Date().toLocaleDateString('en-GB');
  });
</script>
