<?php
// Cash Book Transaction History Page
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';

if (!function_exists('is_admin_user')) {
    function is_admin_user() { return has_role(['admin', 'super_admin']); }
}

if (!has_role(['admin', 'super_admin', 'accountant', 'finance_manager', 'sales_user'])) {
    redirect('index.php?page=dashboard');
}

$user = current_user();
$isAdmin = is_admin_user();

// Company settings for voucher header
$_db = db();
$_cs = $_db->query("SELECT company_name, address_line, city_country, company_email, phone, logo_url FROM shop_settings LIMIT 1")->fetch_assoc();
$_companyName    = $_cs['company_name'] ?? 'SW Granite & Marble';
$_companyAddress = trim(($_cs['address_line'] ?? '') . ' ' . ($_cs['city_country'] ?? ''));
$_companyPhone   = $_cs['phone'] ?? '';
$_companyEmail   = $_cs['company_email'] ?? '';
$_logoUrl        = $_cs['logo_url'] ?? '';

// Get bank accounts for filter
$banks = db()->query("SELECT id, account_name, bank_name FROM bank_accounts WHERE is_active = 1 ORDER BY account_name");
?>
<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4><i class="bi bi-journal-text me-2"></i>Cash Book - Transaction History</h4>
        <a href="<?php echo url_for('index.php?page=cash_book_entry'); ?>" class="btn btn-primary btn-sm">
            <i class="bi bi-plus-lg me-1"></i>New Entry
        </a>
    </div>

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-2">
                    <label>From Date</label>
                    <input type="date" id="filterFrom" class="form-control form-control-sm">
                </div>
                <div class="col-md-2">
                    <label>To Date</label>
                    <input type="date" id="filterTo" class="form-control form-control-sm">
                </div>
                <div class="col-md-2">
                    <label>Bank Account</label>
                    <select id="filterBank" class="form-select form-select-sm">
                        <option value="">All Accounts</option>
                        <?php while ($b = $banks->fetch_assoc()): ?>
                        <option value="<?php echo $b['id']; ?>"><?php echo htmlspecialchars($b['account_name']); ?></option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label>Type</label>
                    <select id="filterType" class="form-select form-select-sm">
                        <option value="">All Types</option>
                        <option value="Receipt">Receipt (Debit)</option>
                        <option value="Payment">Payment (Credit)</option>
                        <option value="Contra">Contra</option>
                        <option value="Journal">Journal</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label>Status</label>
                    <select id="filterStatus" class="form-select form-select-sm">
                        <option value="">All Status</option>
                        <option value="Approved">Approved</option>
                        <option value="Pending">Pending</option>
                        <option value="Rejected">Rejected</option>
                    </select>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button class="btn btn-outline-secondary btn-sm w-100" onclick="loadTransactions()">
                        <i class="bi bi-search me-1"></i>Search
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Transaction Table -->
    <div class="card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover table-sm mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Voucher #</th>
                            <th>Date</th>
                            <th>Account Head</th>
                            <th>Bank Account</th>
                            <th>Narration</th>
                            <th>Reference</th>
                            <th class="text-end text-success">Debit (Receipt)</th>
                            <th class="text-end text-danger">Credit (Payment)</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="transactionTable">
                        <tr><td colspan="10" class="text-center py-4 text-muted">Loading...</td></tr>
                    </tbody>
                    <tfoot class="table-light">
                        <tr>
                            <th colspan="6" class="text-end">Totals:</th>
                            <th class="text-end text-success" id="totalDebit">0.00</th>
                            <th class="text-end text-danger" id="totalCredit">0.00</th>
                            <th colspan="2"></th>
                        </tr>
                        <tr>
                            <th colspan="6" class="text-end">Balance:</th>
                            <th colspan="2" class="text-end" id="balance">0.00</th>
                            <th colspan="2"></th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- View Transaction Modal -->
<div class="modal fade" id="viewModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Transaction Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="viewModalBody">
                <!-- Content loaded dynamically -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
const currency = '<?php echo CURRENCY; ?>';
const fmt = n => Number(n||0).toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2});

function loadTransactions() {
    const params = {
        action: 'list',
        date_from: $('#filterFrom').val(),
        date_to: $('#filterTo').val(),
        bank_account_id: $('#filterBank').val(),
        transaction_type: $('#filterType').val(),
        approval_status: $('#filterStatus').val(),
        is_cancelled: 0  // Hide cancelled transactions by default
    };
    
    $.get('api/transactions.php', params, function(res) {
        const data = res.data || [];
        let html = '';
        let totalDebit = 0, totalCredit = 0;
        
        if (!data.length) {
            html = '<tr><td colspan="10" class="text-center py-4 text-muted">No transactions found</td></tr>';
        } else {
            data.forEach(t => {
                let debit = 0, credit = 0;
                if (t.transaction_type === 'Receipt' || t.transaction_type === 'Contra In') {
                    debit = parseFloat(t.amount) || 0;
                    totalDebit += debit;
                } else if (t.transaction_type === 'Payment' || t.transaction_type === 'Contra Out') {
                    credit = parseFloat(t.amount) || 0;
                    totalCredit += credit;
                }
                
                const statusBadge = t.approval_status === 'Approved' 
                    ? '<span class="badge bg-success">Approved</span>'
                    : t.approval_status === 'Pending'
                    ? '<span class="badge bg-warning text-dark">Pending</span>'
                    : '<span class="badge bg-danger">Rejected</span>';
                
                html += `<tr>
                    <td><code>${t.voucher_number}</code></td>
                    <td>${t.transaction_date}</td>
                    <td>${t.account_head}${t.sub_account_head ? '<br><small class="text-muted">' + t.sub_account_head + '</small>' : ''}</td>
                    <td>${t.bank_account_name || '-'}</td>
                    <td>${t.narration || '-'}</td>
                    <td>${t.document_reference || '-'}</td>
                    <td class="text-end text-success">${debit ? fmt(debit) : '-'}</td>
                    <td class="text-end text-danger">${credit ? fmt(credit) : '-'}</td>
                    <td>${statusBadge}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-info" onclick="viewTransaction(${t.id})" title="View">
                            <i class="bi bi-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-primary" onclick="printPaymentVoucher(${t.id})" title="Print Voucher">
                            <i class="bi bi-printer"></i>
                        </button>
                        ${t.approval_status === 'Pending' ? `
                            <button class="btn btn-sm btn-outline-success" onclick="approveTransaction(${t.id})" title="Approve">
                                <i class="bi bi-check-lg"></i>
                            </button>
                        ` : ''}
                        <?php if ($isAdmin): ?>
                        <button class="btn btn-sm btn-outline-warning" onclick="editTransaction(${t.id})" title="Edit">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteTransaction(${t.id}, '${t.voucher_number}')" title="Delete">
                            <i class="bi bi-trash"></i>
                        </button>
                        <?php endif; ?>
                    </td>
                </tr>`;
            });
        }
        
        $('#transactionTable').html(html);
        $('#totalDebit').text(fmt(totalDebit));
        $('#totalCredit').text(fmt(totalCredit));
        $('#balance').text(fmt(totalDebit - totalCredit));
    });
}

function viewTransaction(id) {
    $.get('api/transactions.php', { action: 'get', id: id }, function(res) {
        const t = res.data || {};
        let html = `
            <table class="table table-bordered table-sm">
                <tr><th width="30%">Voucher Number</th><td>${t.voucher_number}</td></tr>
                <tr><th>Transaction Date</th><td>${t.transaction_date}</td></tr>
                <tr><th>Type</th><td><span class="badge bg-primary">${t.transaction_type}</span></td></tr>
                <tr><th>Account Head</th><td>${t.account_head}</td></tr>
                <tr><th>Sub Account</th><td>${t.sub_account_head || '-'}</td></tr>
                <tr><th>Bank Account</th><td>${t.bank_account_name || '-'}</td></tr>
                <tr><th>Amount</th><td class="fw-bold">${currency} ${fmt(t.amount)}</td></tr>
                <tr><th>Amount in Words</th><td><em>${t.amount_in_words || '-'}</em></td></tr>
                <tr><th>Payment Mode</th><td>${t.mode_of_payment || '-'}</td></tr>
                <tr><th>Narration</th><td>${t.narration || '-'}</td></tr>
                <tr><th>Document Reference</th><td>${t.document_reference || '-'}</td></tr>
                <tr><th>Cost Center</th><td>${t.cost_center || '-'}</td></tr>
                <tr><th>Project Code</th><td>${t.project_code || '-'}</td></tr>
                <tr><th>Status</th><td>${t.approval_status}</td></tr>
                <tr><th>Entered By</th><td>${t.entered_by_name || '-'}</td></tr>
                ${t.approved_by ? `<tr><th>Approved By</th><td>${t.approved_by_name || '-'}</td></tr>` : ''}
            </table>
        `;
        $('#viewModalBody').html(html);
        $('#viewModal').modal('show');
    });
}

function approveTransaction(id) {
    if (!confirm('Approve this transaction?')) return;
    $.post('api/transactions.php', { 
        action: 'approve', 
        id: id, 
        status: 'Approved',
        csrf: '<?php echo $_SESSION['csrf_token']; ?>' 
    }, function(res) {
        alert(res.message);
        loadTransactions();
    });
}

// Print Payment Voucher
function printPaymentVoucher(id) {
    $.get('api/transactions.php', { action: 'get', id: id }, function(res) {
        const t = res.data || {};
        
        // Populate print modal
        $('#printVoucherNumber').text(t.voucher_number || '-');
        $('#printVoucherDate').text(t.transaction_date || '-');
        $('#printPayee').text(t.party_name || '-');
        $('#printAccountHead').text(t.account_head || '-');
        $('#printSubAccount').text(t.sub_account_head || '-');
        $('#printBankAccount').text(t.bank_account_name || '-');
        $('#printNarration').text(t.narration || '-');
        $('#printAmountWords').text(t.amount_in_words || '-');
        $('#printAmount').text(fmt(t.amount || 0));
        $('#printTotalAmount').text(fmt(t.amount || 0));
        $('#printMode').text(t.mode_of_payment || '-');
        $('#printReference').text(t.document_reference || '-');
        $('#printCostCenter').text(t.cost_center || '-');
        // Update title bar label based on type
        const typeLabel = (t.transaction_type || 'Payment').toUpperCase() + ' VOUCHER';
        $('#printVoucherType').text(typeLabel);
        $('.vchr-title-bar').text(typeLabel);
        
        new bootstrap.Modal(document.getElementById('printVoucherModal')).show();
    });
}

function doPrintVoucher() {
    const printContents = document.getElementById('voucherPrintArea').innerHTML;
    const w = window.open('', '_blank', 'width=900,height=700');
    w.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8">
      <title>Voucher Print</title>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
      <style>
        body { margin: 0; font-family: Arial, sans-serif; }
        @page { size: A4; margin: 12mm; }
      </style>
      <style>
        #voucherPrintArea{font-family:Arial,sans-serif;font-size:13px;background:#fff;padding:10mm;}
        .vchr-header{display:flex;justify-content:space-between;align-items:flex-start;padding-bottom:12px;border-bottom:3px solid #1a3a6b;margin-bottom:4px;}
        .vchr-logo{max-height:70px;max-width:180px;object-fit:contain;}
        .vchr-co-name{font-size:18px;font-weight:700;color:#1a3a6b;margin:0 0 2px;}
        .vchr-co-sub{font-size:11px;color:#555;margin:1px 0;}
        .vchr-title-bar{background:#1a3a6b;color:#fff;text-align:center;padding:7px 0;font-size:15px;font-weight:700;letter-spacing:2px;margin-bottom:16px;}
        .vchr-meta{width:100%;border-collapse:collapse;margin-bottom:14px;font-size:12.5px;}
        .vchr-meta td{padding:4px 6px;}
        .vchr-fields{width:100%;border-collapse:collapse;margin-bottom:14px;font-size:12.5px;}
        .vchr-fields td{padding:7px 8px;border-bottom:1px solid #e0e0e0;}
        .vchr-fields .lbl{width:28%;font-weight:600;color:#1a3a6b;}
        .vchr-fields .val{border-bottom:1px dotted #aaa;}
        .vchr-amt-table{width:100%;border-collapse:collapse;margin-bottom:14px;font-size:12.5px;}
        .vchr-amt-table th{background:#1a3a6b;color:#fff;padding:8px 10px;}
        .vchr-amt-table td{border:1px solid #ccc;padding:10px;}
        .vchr-amt-table tfoot td{background:#f0f4fa;font-weight:700;}
        .vchr-words{border:1px solid #bbb;background:#f8f9fc;padding:10px 14px;margin-bottom:14px;font-size:12px;}
        .vchr-sign{width:100%;border-collapse:collapse;margin-top:36px;}
        .vchr-sign td{width:33%;text-align:center;padding:0 10px;}
        .vchr-sign .sig-line{border-top:1px solid #333;margin-top:44px;padding-top:5px;font-size:11px;color:#444;}
        .vchr-footer{margin-top:18px;padding-top:8px;border-top:1px solid #ccc;text-align:center;font-size:10px;color:#888;}
      </style>
    </head><body onload="window.print(); window.close();">
      <div style="max-width:800px; margin:0 auto;">${printContents}</div>
    </body></html>`);
    w.document.close();
}

<?php if ($isAdmin): ?>
function editTransaction(id) {
    $.get('api/transactions.php', { action: 'get', id: id }, function(res) {
        const t = res.data || {};
        $('#editTxId').val(t.id);
        $('#editTxDate').val(t.transaction_date);
        $('#editTxAmount').val(t.amount);
        $('#editTxMode').val(t.mode_of_payment || '');
        $('#editTxAccountHead').val(t.account_head || '');
        $('#editTxSubHead').val(t.sub_account_head || '');
        $('#editTxParty').val(t.party_name || '');
        $('#editTxNarration').val(t.narration || '');
        $('#editTxReference').val(t.document_reference || '');
        $('#editTxCostCenter').val(t.cost_center || '');
        $('#editTxType').text(t.transaction_type);
        $('#editTxVoucher').text(t.voucher_number);
        $('#editTxStatus').text(t.approval_status);
        new bootstrap.Modal(document.getElementById('editTxModal')).show();
    });
}

function saveTransaction() {
    const id = $('#editTxId').val();
    const btn = $('#btnSaveTx');
    btn.prop('disabled', true).html('<i class="bi bi-hourglass-split"></i> Saving...');
    $.post('api/transactions.php', {
        action: 'update',
        csrf: '<?php echo $_SESSION['csrf_token']; ?>',
        id: id,
        transaction_date: $('#editTxDate').val(),
        amount: $('#editTxAmount').val(),
        mode_of_payment: $('#editTxMode').val(),
        account_head: $('#editTxAccountHead').val(),
        sub_account_head: $('#editTxSubHead').val(),
        party_name: $('#editTxParty').val(),
        narration: $('#editTxNarration').val(),
        document_reference: $('#editTxReference').val(),
        cost_center: $('#editTxCostCenter').val()
    }, function(res) {
        btn.prop('disabled', false).html('<i class="bi bi-check-lg me-1"></i>Save Changes');
        if (res.success) {
            bootstrap.Modal.getInstance(document.getElementById('editTxModal')).hide();
            loadTransactions();
            showToast('Transaction updated successfully', 'success');
        } else {
            showToast(res.message || 'Update failed', 'danger');
        }
    }).fail(function(xhr) {
        btn.prop('disabled', false).html('<i class="bi bi-check-lg me-1"></i>Save Changes');
        const err = xhr.responseJSON?.message || 'Update failed';
        showToast(err, 'danger');
    });
}

function deleteTransaction(id, voucherNo) {
    if (!confirm(`DELETE transaction ${voucherNo}?\n\nThis will REVERSE all bank balance changes, GL entries and petty cash effects.\nThis action CANNOT be undone!`)) return;
    $.post('api/transactions.php', {
        action: 'delete',
        csrf: '<?php echo $_SESSION['csrf_token']; ?>',
        id: id
    }, function(res) {
        if (res.success) {
            loadTransactions();
            showToast('Transaction deleted and all effects reversed', 'success');
        } else {
            showToast(res.message || 'Delete failed', 'danger');
        }
    }).fail(function(xhr) {
        showToast(xhr.responseJSON?.message || 'Delete failed', 'danger');
    });
}
<?php endif; ?>

function showToast(msg, type) {
    const t = $(`<div class="toast align-items-center text-bg-${type} border-0 show" role="alert" style="min-width:260px">
        <div class="d-flex"><div class="toast-body">${msg}</div>
        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button></div></div>`);
    if (!$('#toastContainer').length) $('body').append('<div id="toastContainer" class="toast-container position-fixed bottom-0 end-0 p-3"></div>');
    $('#toastContainer').append(t);
    setTimeout(() => t.remove(), 4000);
}

// Load on page load
$(document).ready(function() {
    // Set default date range (current month)
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    $('#filterFrom').val(firstDay.toISOString().split('T')[0]);
    $('#filterTo').val(today.toISOString().split('T')[0]);
    
    loadTransactions();
});
</script>

<?php if ($isAdmin): ?>
<!-- Edit Transaction Modal -->
<div class="modal fade" id="editTxModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-warning-subtle">
        <h5 class="modal-title"><i class="bi bi-pencil-square me-2"></i>Edit Transaction
          <small class="ms-2 text-muted fs-6" id="editTxVoucher"></small>
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="alert alert-warning py-2 mb-3">
          <i class="bi bi-exclamation-triangle-fill me-1"></i>
          <strong>Admin Edit:</strong> Saving will reverse old bank/GL effects and re-apply new values. &nbsp;
          Type: <span class="badge bg-primary" id="editTxType"></span> &nbsp; Status: <span class="badge bg-secondary" id="editTxStatus"></span>
        </div>
        <input type="hidden" id="editTxId">
        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label">Date <span class="text-danger">*</span></label>
            <input type="date" id="editTxDate" class="form-control form-control-sm" required>
          </div>
          <div class="col-md-4">
            <label class="form-label">Amount <span class="text-danger">*</span></label>
            <input type="number" id="editTxAmount" class="form-control form-control-sm" step="0.01" min="0.01" required>
          </div>
          <div class="col-md-4">
            <label class="form-label">Payment Mode</label>
            <select id="editTxMode" class="form-select form-select-sm">
              <option value="">-- Select --</option>
              <option value="Cash">Cash</option>
              <option value="Bank Transfer">Bank Transfer</option>
              <option value="Cheque">Cheque</option>
              <option value="Online">Online</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Account Head</label>
            <select id="editTxAccountHead" class="form-select form-select-sm">
              <option value="">Select Account Head</option>
              <optgroup label="Assets">
                <option value="Cash in Hand">Cash in Hand</option>
                <option value="Bank Accounts">Bank Accounts</option>
                <option value="Petty Cash Top Up">Petty Cash Top Up</option>
                <option value="Accounts Receivable">Accounts Receivable</option>
                <option value="Inventory">Inventory</option>
                <option value="Fixed Assets">Fixed Assets</option>
              </optgroup>
              <optgroup label="Liabilities">
                <option value="Accounts Payable">Accounts Payable</option>
                <option value="Loans">Loans</option>
                <option value="Taxes Payable">Taxes Payable</option>
              </optgroup>
              <optgroup label="Income">
                <option value="Sales Revenue">Sales Revenue</option>
                <option value="Service Revenue">Service Revenue</option>
                <option value="Interest Income">Interest Income</option>
                <option value="Other Income">Other Income</option>
              </optgroup>
              <optgroup label="Expenses">
                <option value="Purchase Expenses">Purchase Expenses</option>
                <option value="Salary &amp; Wages">Salary &amp; Wages</option>
                <option value="Rent Expense">Rent Expense</option>
                <option value="Utilities">Utilities</option>
                <option value="Transportation">Transportation</option>
                <option value="Office Supplies">Office Supplies</option>
                <option value="Marketing">Marketing</option>
                <option value="Maintenance">Maintenance</option>
                <option value="Bank Charges">Bank Charges</option>
                <option value="Other Expenses">Other Expenses</option>
              </optgroup>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Sub Account Head</label>
            <input type="text" id="editTxSubHead" class="form-control form-control-sm">
          </div>
          <div class="col-md-6">
            <label class="form-label">Payee / Party Name</label>
            <input type="text" id="editTxParty" class="form-control form-control-sm">
          </div>
          <div class="col-md-6">
            <label class="form-label">Cost Center</label>
            <input type="text" id="editTxCostCenter" class="form-control form-control-sm">
          </div>
          <div class="col-md-6">
            <label class="form-label">Document Reference</label>
            <input type="text" id="editTxReference" class="form-control form-control-sm">
          </div>
          <div class="col-md-12">
            <label class="form-label">Narration</label>
            <textarea id="editTxNarration" class="form-control form-control-sm" rows="2"></textarea>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-warning btn-sm" id="btnSaveTx" onclick="saveTransaction()">
          <i class="bi bi-check-lg me-1"></i>Save Changes
        </button>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<!-- Print Payment 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>Payment Voucher</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <style>
          #voucherPrintArea { font-family: Arial, sans-serif; font-size: 13px; background: #fff; }
          .vchr-header { display: flex; justify-content: space-between; align-items: flex-start; padding-bottom: 12px; border-bottom: 3px solid #1a3a6b; margin-bottom: 4px; }
          .vchr-logo { max-height: 70px; max-width: 180px; object-fit: contain; }
          .vchr-co-name { font-size: 18px; font-weight: 700; color: #1a3a6b; margin: 0 0 2px; }
          .vchr-co-sub { font-size: 11px; color: #555; margin: 1px 0; }
          .vchr-title-bar { background: #1a3a6b; color: #fff; text-align: center; padding: 7px 0; font-size: 15px; font-weight: 700; letter-spacing: 2px; margin-bottom: 16px; }
          .vchr-meta { width: 100%; border-collapse: collapse; margin-bottom: 14px; font-size: 12.5px; }
          .vchr-meta td { padding: 4px 6px; }
          .vchr-fields { width: 100%; border-collapse: collapse; margin-bottom: 14px; font-size: 12.5px; }
          .vchr-fields td { padding: 7px 8px; border-bottom: 1px solid #e0e0e0; }
          .vchr-fields .lbl { width: 28%; font-weight: 600; color: #1a3a6b; }
          .vchr-fields .val { border-bottom: 1px dotted #aaa; }
          .vchr-amt-table { width: 100%; border-collapse: collapse; margin-bottom: 14px; font-size: 12.5px; }
          .vchr-amt-table th { background: #1a3a6b; color: #fff; padding: 8px 10px; }
          .vchr-amt-table td { border: 1px solid #ccc; padding: 10px; }
          .vchr-amt-table tfoot td { background: #f0f4fa; font-weight: 700; }
          .vchr-words { border: 1px solid #bbb; background: #f8f9fc; padding: 10px 14px; margin-bottom: 14px; font-size: 12px; }
          .vchr-sign { width: 100%; border-collapse: collapse; margin-top: 36px; }
          .vchr-sign td { width: 33%; text-align: center; padding: 0 10px; }
          .vchr-sign .sig-line { border-top: 1px solid #333; margin-top: 44px; padding-top: 5px; font-size: 11px; color: #444; }
          .vchr-footer { margin-top: 18px; padding-top: 8px; border-top: 1px solid #ccc; text-align: center; font-size: 10px; color: #888; }
          @media print {
            body > * { display: none !important; }
            .modal { display: block !important; position: absolute; left:0; top:0; width:100%; }
            .modal-dialog { max-width:100%; margin:0; }
            .modal-content { border:none; box-shadow:none; }
            .modal-header, .modal-footer, .no-print { display: none !important; }
            .modal-body { padding: 0; }
            #voucherPrintArea { padding: 10mm; }
          }
        </style>
        <div id="voucherPrintArea" style="padding: 24px; background:#fff;">
          <!-- Company Header (payslip-style) -->
          <div class="vchr-header">
            <div style="display:flex; align-items:center; gap:14px;">
              <?php if (!empty($_logoUrl)): ?>
              <img src="<?= htmlspecialchars($_logoUrl) ?>" alt="Logo" class="vchr-logo">
              <?php endif; ?>
              <div>
                <p class="vchr-co-name"><?= htmlspecialchars($_companyName) ?></p>
                <?php if (!empty($_companyAddress)): ?>
                <p class="vchr-co-sub"><i class="bi bi-geo-alt-fill"></i> <?= htmlspecialchars($_companyAddress) ?></p>
                <?php endif; ?>
                <?php if (!empty($_companyPhone)): ?>
                <p class="vchr-co-sub"><i class="bi bi-telephone-fill"></i> <?= htmlspecialchars($_companyPhone) ?></p>
                <?php endif; ?>
                <?php if (!empty($_companyEmail)): ?>
                <p class="vchr-co-sub"><i class="bi bi-envelope-fill"></i> <?= htmlspecialchars($_companyEmail) ?></p>
                <?php endif; ?>
              </div>
            </div>
            <div style="text-align:right; font-size:11px; color:#555;">
              <span id="printVoucherType" style="display:inline-block; background:#1a3a6b; color:#fff; padding:3px 12px; border-radius:3px; font-size:11px; font-weight:600; letter-spacing:1px;">PAYMENT VOUCHER</span>
            </div>
          </div>
          <!-- Blue title bar -->
          <div class="vchr-title-bar">PAYMENT VOUCHER</div>
          
          <!-- Voucher Meta -->
          <table class="vchr-meta">
            <tr>
              <td style="width:50%;"><strong style="color:#1a3a6b;">Voucher No:</strong>&nbsp;<span id="printVoucherNumber">-</span></td>
              <td style="width:50%; text-align:right;"><strong style="color:#1a3a6b;">Date:</strong>&nbsp;<span id="printVoucherDate">-</span></td>
            </tr>
            <tr>
              <td><strong style="color:#1a3a6b;">Payment Mode:</strong>&nbsp;<span id="printMode">-</span></td>
              <td style="text-align:right;"><strong style="color:#1a3a6b;">Reference:</strong>&nbsp;<span id="printReference">-</span></td>
            </tr>
          </table>

          <hr style="border-color:#d0d8e8; margin:10px 0 14px;">

          <!-- Payee & Account Fields -->
          <table class="vchr-fields">
            <tr><td class="lbl">Payee Name</td><td class="val"><span id="printPayee">-</span></td></tr>
            <tr><td class="lbl">Bank Account</td><td class="val"><span id="printBankAccount">-</span></td></tr>
            <tr><td class="lbl">Account Head</td><td class="val"><span id="printAccountHead">-</span></td></tr>
            <tr><td class="lbl">Sub Account</td><td class="val"><span id="printSubAccount">-</span></td></tr>
            <tr><td class="lbl">Cost Center</td><td class="val"><span id="printCostCenter">-</span></td></tr>
          </table>

          <!-- Description & Amount -->
          <table class="vchr-amt-table">
            <thead>
              <tr>
                <th style="text-align:left; width:70%;">Description</th>
                <th style="text-align:right; width:30%;">Amount (Rs.)</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td style="vertical-align:top;"><span id="printNarration">-</span></td>
                <td style="text-align:right; vertical-align:top; font-weight:700;"><span id="printAmount">0.00</span></td>
              </tr>
            </tbody>
            <tfoot>
              <tr>
                <td style="text-align:right; border:1px solid #ccc;"><strong>Total:</strong></td>
                <td style="text-align:right; font-size:14px; border:1px solid #ccc;"><span id="printTotalAmount">0.00</span></td>
              </tr>
            </tfoot>
          </table>

          <!-- Amount in Words -->
          <div class="vchr-words">
            <strong style="color:#1a3a6b;">Amount in Words:</strong><br>
            <span id="printAmountWords" style="font-style:italic;">-</span>
          </div>

          <!-- Signatures -->
          <table class="vchr-sign">
            <tr>
              <td><div class="sig-line">Prepared By</div></td>
              <td><div class="sig-line">Authorized By</div></td>
              <td><div class="sig-line">Received By</div></td>
            </tr>
          </table>

          <!-- Footer -->
          <div class="vchr-footer">This is a computer generated voucher &mdash; <?= htmlspecialchars($_companyName) ?></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="doPrintVoucher()">
          <i class="bi bi-printer me-1"></i>Print Voucher
        </button>
      </div>
    </div>
  </div>
</div>
