<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-cash-book-entry">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4 class="mb-0"><i class="bi bi-journal-book me-2"></i>Cash Book Entry</h4>
      <div class="d-flex gap-2">
        <button id="btnReset" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-counterclockwise me-1"></i>Reset</button>
        <button id="btnSave" class="btn btn-primary btn-sm"><i class="bi bi-save me-1"></i>Save Transaction</button>
      </div>
    </div>

    <form id="cashBookForm" class="needs-validation" novalidate>
      <input type="hidden" id="csrf" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
      <input type="hidden" id="action" name="action" value="create_transaction">

      <div class="row g-3">
        <!-- Voucher Number - Read Only -->
        <div class="col-md-3">
          <label class="form-label fw-bold">Voucher Number <span class="text-muted">(Auto-generated)</span></label>
          <div class="input-group">
            <span class="input-group-text"><i class="bi bi-hash"></i></span>
            <input type="text" id="voucherNumber" class="form-control bg-light" readonly placeholder="Click to generate">
            <button type="button" id="btnGenerateVoucher" class="btn btn-outline-primary" title="Generate Voucher Number">
              <i class="bi bi-magic"></i>
            </button>
          </div>
          <div class="form-text">Format: VCH/YYYY/MMDD/XXXX</div>
        </div>

        <!-- Transaction Date - Mandatory -->
        <div class="col-md-3">
          <label class="form-label fw-bold">Transaction Date <span class="text-danger">*</span></label>
          <input type="date" id="transactionDate" name="transaction_date" class="form-control" required value="<?php echo date('Y-m-d'); ?>">
          <div class="invalid-feedback">Please select transaction date.</div>
        </div>

        <!-- Bank Account - Mandatory -->
        <div class="col-md-6">
          <label class="form-label fw-bold">Bank Account <span class="text-danger">*</span></label>
          <select id="bankAccount" name="bank_account_id" class="form-select" required>
            <option value="">Select Bank Account</option>
          </select>
          <div class="invalid-feedback">Please select a bank account.</div>
        </div>

        <!-- Transaction Type - Mandatory -->
        <div class="col-md-3">
          <label class="form-label fw-bold">Transaction Type <span class="text-danger">*</span></label>
          <select id="transactionType" name="transaction_type" class="form-select" required>
            <option value="">Select Type</option>
            <option value="Receipt">Receipt</option>
            <option value="Payment">Payment</option>
            <option value="Contra">Contra</option>
            <option value="Journal">Journal</option>
          </select>
          <div class="invalid-feedback">Please select transaction type.</div>
        </div>

        <!-- Account Head - Mandatory -->
        <div class="col-md-3">
          <label class="form-label fw-bold">Account Head <span class="text-danger">*</span></label>
          <div class="input-group">
            <select id="accountHead" name="account_head" class="form-select" required>
              <option value="">Select Account Head</option>
            </select>
            <?php if (has_role(['admin','super_admin'])): ?>
            <button type="button" class="btn btn-outline-secondary" id="btnManageAccountHeads" title="Manage Account Heads">
              <i class="bi bi-gear"></i>
            </button>
            <?php endif; ?>
          </div>
          <div class="invalid-feedback">Please select account head.</div>
        </div>

        <!-- Sub Account Head -->
        <div class="col-md-3">
          <label class="form-label">Sub Account Head</label>
          <select id="subAccountHead" name="sub_account_head" class="form-select">
            <option value="">-- None --</option>
          </select>
          <div class="form-text text-muted small" id="subAccountHeadHint">Select an Account Head first</div>
        </div>

        <!-- Cost Center -->
        <div class="col-md-3">
          <label class="form-label">Cost Center</label>
          <div class="input-group">
            <select id="costCenter" name="cost_center" class="form-select">
              <option value="">Select Cost Center</option>
            </select>
            <?php if (has_role(['admin','super_admin'])): ?>
            <button type="button" class="btn btn-outline-secondary" id="btnManageCostCenters" title="Manage Cost Centers">
              <i class="bi bi-gear"></i>
            </button>
            <?php endif; ?>
          </div>
        </div>

        <!-- Party Details -->
        <div class="col-12">
          <h6 class="mt-3 mb-2 text-primary"><i class="bi bi-person-lines-fill me-2"></i>Party Details</h6>
        </div>

        <div class="col-md-3">
          <label class="form-label">Party Type</label>
          <select id="partyType" name="party_type" class="form-select">
            <option value="">Select Party Type</option>
            <option value="Customer">Customer</option>
            <option value="Supplier">Supplier</option>
            <option value="Employee">Employee</option>
            <option value="Vendor">Vendor</option>
            <option value="Other">Other</option>
          </select>
        </div>

        <div class="col-md-5">
          <label class="form-label">Party Name</label>
          <div id="partyNameSelectWrap">
            <select id="partyNameSelect" class="form-select">
              <option value="">-- Select --</option>
            </select>
          </div>
          <div id="partyNameInputWrap" style="display:none;">
            <input type="text" id="partyNameInput" class="form-control" placeholder="Enter party name">
          </div>
          <input type="hidden" id="partyName" name="party_name">
          <?php if (has_role(['admin','super_admin'])): ?>
          <div id="partyVendorManageWrap" style="display:none;" class="mt-1">
            <button type="button" class="btn btn-outline-secondary btn-sm" id="btnManageVendors">
              <i class="bi bi-gear me-1"></i>Manage Vendors
            </button>
          </div>
          <?php endif; ?>
        </div>

        <div class="col-md-4">
          <label class="form-label">Party ID</label>
          <input type="text" id="partyId" name="party_id" class="form-control" placeholder="Auto-filled or enter manually" readonly>
        </div>

        <!-- Amount Section - Mandatory -->
        <div class="col-12">
          <h6 class="mt-3 mb-2 text-success"><i class="bi bi-currency-dollar me-2"></i>Amount Details <span class="text-danger">*</span></h6>
        </div>

        <div class="col-md-4">
          <label class="form-label fw-bold">Amount <span class="text-danger">*</span></label>
          <div class="input-group">
            <span class="input-group-text" id="currencySymbol">LKR</span>
            <input type="number" id="amount" name="amount" class="form-control text-end" required min="0.01" step="0.01" placeholder="0.00">
          </div>
          <div class="invalid-feedback">Please enter a valid amount greater than 0.</div>
        </div>

        <div class="col-md-4">
          <label class="form-label">Amount in Words</label>
          <input type="text" id="amountInWords" name="amount_in_words" class="form-control" readonly placeholder="Auto-generated">
        </div>

        <div class="col-md-4">
          <label class="form-label fw-bold">Mode of Payment <span class="text-danger">*</span></label>
          <select id="modeOfPayment" name="mode_of_payment" class="form-select" required>
            <option value="">Select Payment Mode</option>
            <option value="Cash">Cash</option>
            <option value="Cheque">Cheque</option>
            <option value="Bank Transfer">Bank Transfer</option>
            <option value="Online Payment">Online Payment</option>
            <option value="Credit Card">Credit Card</option>
            <option value="Debit Card">Debit Card</option>
            <option value="Draft">Draft</option>
            <option value="Other">Other</option>
          </select>
          <div class="invalid-feedback">Please select mode of payment.</div>
        </div>

        <!-- Cheque Details (Conditional) -->
        <div id="chequeDetails" class="row g-3 d-none">
          <div class="col-12">
            <h6 class="mt-2 mb-2 text-info"><i class="bi bi-bank me-2"></i>Cheque Details</h6>
          </div>
          <div class="col-md-4">
            <label class="form-label">Cheque Number</label>
            <input type="text" id="chequeNumber" name="cheque_number" class="form-control" placeholder="Enter cheque number">
          </div>
          <div class="col-md-4">
            <label class="form-label">Cheque Date</label>
            <input type="date" id="chequeDate" name="cheque_date" class="form-control">
          </div>
          <div class="col-md-4">
            <label class="form-label">Bank Name</label>
            <input type="text" id="chequeBankName" name="bank_name" class="form-control" placeholder="Cheque issuing bank">
          </div>
        </div>

        <!-- Tax Information -->
        <div class="col-12">
          <h6 class="mt-3 mb-2 text-warning"><i class="bi bi-receipt me-2"></i>Tax Information</h6>
        </div>

        <div class="col-md-3">
          <label class="form-label">Tax Type</label>
          <select id="taxType" name="tax_type" class="form-select">
            <option value="">No Tax</option>
            <option value="VAT">VAT</option>
            <option value="GST">GST</option>
            <option value="Income Tax">Income Tax</option>
            <option value="Withholding Tax">Withholding Tax</option>
          </select>
        </div>

        <div class="col-md-3">
          <label class="form-label">Tax Percent (%)</label>
          <input type="number" id="taxPercent" name="tax_percent" class="form-control" min="0" max="100" step="0.01" placeholder="0.00">
        </div>

        <div class="col-md-3">
          <label class="form-label">Tax Amount</label>
          <div class="input-group">
            <span class="input-group-text">LKR</span>
            <input type="number" id="taxAmount" name="tax_amount" class="form-control text-end" min="0" step="0.01" placeholder="0.00" readonly>
          </div>
        </div>

        <div class="col-md-3">
          <label class="form-label fw-bold">Total Amount</label>
          <div class="input-group">
            <span class="input-group-text bg-success text-white">LKR</span>
            <input type="number" id="totalAmount" class="form-control text-end fw-bold" readonly placeholder="0.00">
          </div>
        </div>

        <!-- Document Reference -->
        <div class="col-12">
          <h6 class="mt-3 mb-2 text-secondary"><i class="bi bi-file-earmark-text me-2"></i>Document Reference</h6>
        </div>

        <div class="col-md-4">
          <label class="form-label">Document Reference No</label>
          <input type="text" id="documentReference" name="document_reference" class="form-control" placeholder="Invoice/Bill/Receipt number">
        </div>

        <div class="col-md-4">
          <label class="form-label">Document Date</label>
          <input type="date" id="documentDate" name="document_date" class="form-control">
        </div>

        <div class="col-md-4">
          <label class="form-label">Project Code</label>
          <input type="text" id="projectCode" name="project_code" class="form-control" placeholder="Project/Job reference">
        </div>

        <!-- Narration -->
        <div class="col-12">
          <label class="form-label fw-bold">Narration/Description <span class="text-danger">*</span></label>
          <textarea id="narration" name="narration" class="form-control" rows="3" required placeholder="Enter detailed description of the transaction..."></textarea>
          <div class="invalid-feedback">Please enter narration/description.</div>
          <div class="form-text">Provide clear details about this transaction for future reference.</div>
        </div>

        <!-- Supporting Documents -->
        <div class="col-12">
          <h6 class="mt-3 mb-2 text-info"><i class="bi bi-paperclip me-2"></i>Supporting Documents</h6>
          <div class="border rounded p-3 bg-light">
            <input type="file" id="attachments" name="attachments[]" class="form-control" multiple accept=".pdf,.jpg,.jpeg,.png,.doc,.docx">
            <div class="form-text">Upload supporting documents (PDF, Images, Word). Max 5 files, 5MB each.</div>
            <div id="fileList" class="mt-2 small text-muted"></div>
          </div>
        </div>

        <!-- Summary Card -->
        <div class="col-12 mt-4">
          <div class="card border-primary">
            <div class="card-header bg-primary text-white">
              <i class="bi bi-calculator me-2"></i>Transaction Summary
            </div>
            <div class="card-body">
              <div class="row">
                <div class="col-md-4">
                  <div class="text-muted small">Voucher Number</div>
                  <div id="summaryVoucher" class="fw-bold text-primary">-</div>
                </div>
                <div class="col-md-4">
                  <div class="text-muted small">Transaction Type</div>
                  <div id="summaryType" class="fw-bold">-</div>
                </div>
                <div class="col-md-4">
                  <div class="text-muted small">Total Amount</div>
                  <div id="summaryAmount" class="fw-bold text-success fs-5">LKR 0.00</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Form Actions -->
        <div class="col-12 mt-4 d-flex gap-2 justify-content-end">
          <button type="button" id="btnDraft" class="btn btn-outline-secondary">
            <i class="bi bi-save me-1"></i>Save as Draft
          </button>
          <button type="button" id="btnSubmit" class="btn btn-success btn-lg">
            <i class="bi bi-check-circle me-1"></i>Submit Transaction
          </button>
        </div>
      </div>
    </form>
  </div>
</div>

<?php if (has_role(['admin','super_admin'])): ?>
<!-- Manage Vendors Modal -->
<div class="modal fade" id="vendorsModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-shop me-2"></i>Manage Vendors</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="row g-2 mb-3">
          <div class="col-md-4">
            <input type="text" id="vdNewName" class="form-control" placeholder="Vendor name (e.g. Dialog)">
          </div>
          <div class="col-md-3">
            <input type="text" id="vdNewCategory" class="form-control" placeholder="Category (e.g. Telecom)">
          </div>
          <div class="col-md-2">
            <input type="text" id="vdNewPhone" class="form-control" placeholder="Phone">
          </div>
          <div class="col-md-3">
            <button type="button" class="btn btn-success w-100" id="btnVdAdd">
              <i class="bi bi-plus-lg me-1"></i>Add
            </button>
          </div>
        </div>
        <div class="table-responsive">
          <table class="table table-sm align-middle" id="vdTable">
            <thead class="table-light">
              <tr><th>Name</th><th>Category</th><th>Phone</th><th style="width:80px">Active</th><th style="width:90px">Actions</th></tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<?php if (has_role(['admin','super_admin'])): ?>
<!-- Manage Account Heads Modal -->
<div class="modal fade" id="accountHeadsModal" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-tags me-2"></i>Manage Account Heads &amp; Sub Account Heads</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <!-- Add new parent account head -->
        <div class="card border-primary mb-3">
          <div class="card-header bg-primary text-white py-2 small fw-bold"><i class="bi bi-plus-circle me-1"></i>Add Account Head (Parent)</div>
          <div class="card-body py-2">
            <div class="row g-2">
              <div class="col-md-5">
                <input type="text" id="ahNewName" class="form-control form-control-sm" placeholder="Account head name">
              </div>
              <div class="col-md-4">
                <select id="ahNewCategory" class="form-select form-select-sm">
                  <option value="Asset">Asset</option>
                  <option value="Liability">Liability</option>
                  <option value="Income">Income</option>
                  <option value="Expense" selected>Expense</option>
                  <option value="Equity">Equity</option>
                </select>
              </div>
              <div class="col-md-3">
                <button type="button" class="btn btn-primary btn-sm w-100" id="btnAhAdd">
                  <i class="bi bi-plus-lg me-1"></i>Add Account Head
                </button>
              </div>
            </div>
          </div>
        </div>
        <!-- Tree table -->
        <div class="table-responsive">
          <table class="table table-sm align-middle" id="ahTable">
            <thead class="table-dark">
              <tr><th>Account Head / Sub Head</th><th style="width:130px">Type</th><th style="width:70px">Active</th><th style="width:110px">Actions</th></tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<?php if (has_role(['admin','super_admin'])): ?>
<!-- Manage Cost Centers Modal -->
<div class="modal fade" id="costCentersModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-building me-2"></i>Manage Cost Centers</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="card border-primary mb-3">
          <div class="card-header bg-primary text-white py-2 small fw-bold"><i class="bi bi-plus-circle me-1"></i>Add Cost Center</div>
          <div class="card-body py-2">
            <div class="row g-2">
              <div class="col-md-5">
                <input type="text" id="ccNewName" class="form-control form-control-sm" placeholder="Cost center name">
              </div>
              <div class="col-md-4">
                <input type="text" id="ccNewDesc" class="form-control form-control-sm" placeholder="Description (optional)">
              </div>
              <div class="col-md-3">
                <button type="button" class="btn btn-primary btn-sm w-100" id="btnCcAdd">
                  <i class="bi bi-plus-lg me-1"></i>Add
                </button>
              </div>
            </div>
          </div>
        </div>
        <div class="table-responsive">
          <table class="table table-sm align-middle" id="ccTable">
            <thead class="table-dark">
              <tr><th>Name</th><th>Description</th><th style="width:70px">Active</th><th style="width:90px">Actions</th></tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

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

  // Load bank accounts on page load
  function loadBankAccounts() {
    $.get('api/finance.php', { action: 'list_bank_accounts', is_active: 1 }, function(res) {
      const $select = $('#bankAccount');
      $select.html('<option value="">Select Bank Account</option>');
      
      (res.data || []).forEach(function(acc) {
        const defaultBadge = acc.is_default == 1 ? ' (Default)' : '';
        const balanceText = acc.currency === 'LKR' 
          ? 'LKR ' + Number(acc.current_balance || 0).toLocaleString('en-LK', {minimumFractionDigits: 2})
          : acc.currency + ' ' + Number(acc.current_balance || 0).toLocaleString('en-US', {minimumFractionDigits: 2});
        
        $select.append(`<option value="${acc.id}" data-currency="${acc.currency}" data-balance="${acc.current_balance}">
          ${acc.account_name} - ${acc.bank_name}${defaultBadge} [${balanceText}]
        </option>`);
      });
    }).fail(function(xhr) {
      alert('Failed to load bank accounts: ' + (xhr.responseJSON?.message || 'Error'));
    });
  }

  // Destination account selector for Contra transactions
  function updateDestinationAccountOptions(accounts) {
    let $destSelect = $('#destinationBankAccount');
    if (!$destSelect.length) {
      // Create the destination account dropdown if it doesn't exist
      $('#bankAccount').closest('.col-md-6').after(`
        <div class="col-md-6 d-none" id="destinationAccountDiv">
          <label class="form-label fw-bold">Destination Bank Account <span class="text-danger">*</span></label>
          <select id="destinationBankAccount" name="destination_bank_account_id" class="form-select">
            <option value="">Select Destination Account</option>
          </select>
          <div class="invalid-feedback">Please select destination bank account.</div>
        </div>
      `);
      $destSelect = $('#destinationBankAccount');
    }

    const currentSource = $('#bankAccount').val();
    $destSelect.html('<option value="">Select Destination Account</option>');

    accounts.forEach(function(acc) {
      if (acc.id != currentSource) { // Don't show the source account
        const balanceText = acc.currency === 'LKR'
          ? 'LKR ' + Number(acc.current_balance || 0).toLocaleString('en-LK', {minimumFractionDigits: 2})
          : acc.currency + ' ' + Number(acc.current_balance || 0).toLocaleString('en-US', {minimumFractionDigits: 2});

        $destSelect.append(`<option value="${acc.id}" data-currency="${acc.currency}">
          ${acc.account_name} - ${acc.bank_name} [${balanceText}]
        </option>`);
      }
    });
  }

  // Show/hide destination account based on transaction type
  function toggleDestinationAccount() {
    const type = $('#transactionType').val();
    if (type === 'Contra') {
      $('#destinationAccountDiv').removeClass('d-none');
      $('#destinationBankAccount').prop('required', true);
      // Reload destination options
      $.get('api/finance.php', { action: 'list_bank_accounts', is_active: 1 }, function(res) {
        updateDestinationAccountOptions(res.data || []);
      });
    } else {
      $('#destinationAccountDiv').addClass('d-none');
      $('#destinationBankAccount').prop('required', false).val('');
    }
  }

  // Generate voucher number
  function generateVoucherNumber() {
    const type = $('#transactionType').val();
    const date = $('#transactionDate').val();

    if (!type || !date) {
      alert('Please select Transaction Type and Date first.');
      return;
    }

    $.get('api/transactions.php', {
      action: 'generate_voucher',
      type: type,
      date: date
    }, function(res) {
      $('#voucherNumber').val(res.voucher_number);
      updateSummary();
    }).fail(function(xhr) {
      alert('Failed to generate voucher: ' + (xhr.responseJSON?.message || 'Error'));
    });
  }

  // Convert number to words (simplified)
  function numberToWords(num) {
    if (!num || num === 0) return '';
    
    const ones = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];
    const teens = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
    const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
    
    function convert(n) {
      if (n < 10) return ones[n];
      if (n < 20) return teens[n - 10];
      if (n < 100) return tens[Math.floor(n / 10)] + (n % 10 ? ' ' + ones[n % 10] : '');
      if (n < 1000) return ones[Math.floor(n / 100)] + ' Hundred' + (n % 100 ? ' and ' + convert(n % 100) : '');
      if (n < 1000000) return convert(Math.floor(n / 1000)) + ' Thousand' + (n % 1000 ? ' ' + convert(n % 1000) : '');
      return convert(Math.floor(n / 1000000)) + ' Million' + (n % 1000000 ? ' ' + convert(n % 1000000) : '');
    }
    
    const whole = Math.floor(num);
    const decimal = Math.round((num - whole) * 100);
    
    let words = convert(whole) + ' Rupees';
    if (decimal > 0) {
      words += ' and ' + convert(decimal) + ' Cents';
    }
    return words;
  }

  // Update calculations
  function updateCalculations() {
    const amount = parseFloat($('#amount').val()) || 0;
    const taxPercent = parseFloat($('#taxPercent').val()) || 0;
    
    // Calculate tax amount
    const taxAmount = (amount * taxPercent) / 100;
    $('#taxAmount').val(taxAmount.toFixed(2));
    
    // Calculate total
    const total = amount + taxAmount;
    $('#totalAmount').val(total.toFixed(2));
    
    // Update amount in words
    const currency = $('#bankAccount option:selected').data('currency') || 'LKR';
    const words = numberToWords(total);
    $('#amountInWords').val(words + ' Only');
    
    updateSummary();
  }

  // Update summary card
  function updateSummary() {
    const voucher = $('#voucherNumber').val() || '-';
    const type = $('#transactionType option:selected').text() || '-';
    const total = parseFloat($('#totalAmount').val()) || 0;
    const currency = $('#bankAccount option:selected').data('currency') || 'LKR';
    
    $('#summaryVoucher').text(voucher);
    $('#summaryType').text(type);
    $('#summaryAmount').text(currency + ' ' + total.toFixed(2));
  }

  // Toggle cheque details
  function toggleChequeDetails() {
    const mode = $('#modeOfPayment').val();
    if (mode === 'Cheque') {
      $('#chequeDetails').removeClass('d-none');
      $('#chequeNumber').prop('required', true);
      $('#chequeDate').prop('required', true);
    } else {
      $('#chequeDetails').addClass('d-none');
      $('#chequeNumber').prop('required', false).val('');
      $('#chequeDate').prop('required', false).val('');
      $('#chequeBankName').val('');
    }
  }

  // Update currency symbol
  function updateCurrencySymbol() {
    const currency = $('#bankAccount option:selected').data('currency') || 'LKR';
    $('#currencySymbol').text(currency);
    updateCalculations();
  }

  // Form validation
  function validateForm() {
    const form = document.getElementById('cashBookForm');
    
    if (!form.checkValidity()) {
      form.classList.add('was-validated');
      return false;
    }
    
    // Additional custom validations
    const voucher = $('#voucherNumber').val();
    if (!voucher) {
      alert('Please generate a Voucher Number before submitting.');
      $('#btnGenerateVoucher').focus();
      return false;
    }
    
    const amount = parseFloat($('#amount').val()) || 0;
    if (amount <= 0) {
      alert('Amount must be greater than 0.');
      $('#amount').focus();
      return false;
    }
    
    return true;
  }

  // Submit transaction
  function submitTransaction(asDraft = false) {
    if (!validateForm()) return;

    const formData = new FormData(document.getElementById('cashBookForm'));

    // Set the action for the transactions API
    formData.set('action', 'create');

    // Add draft status if saving as draft
    if (asDraft) {
      formData.append('draft', '1');
    }

    // Add CSRF token
    formData.set('csrf', $('#csrf').val());

    // Add file attachments
    const files = $('#attachments')[0].files;
    for (let i = 0; i < files.length; i++) {
      formData.append('attachments[]', files[i]);
    }

    // Show loading
    const $btn = asDraft ? $('#btnDraft') : $('#btnSubmit');
    const originalText = $btn.html();
    $btn.html('<i class="bi bi-hourglass-split me-1"></i>Processing...').prop('disabled', true);

    $.ajax({
      url: 'api/transactions.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(res) {
        $btn.html(originalText).prop('disabled', false);
        alert(asDraft ? 'Transaction saved as draft.\nVoucher: ' + res.voucher_number : 'Transaction created successfully!\nVoucher: ' + res.voucher_number + '\nStatus: ' + res.status);
        if (!asDraft) {
          resetForm();
        }
      },
      error: function(xhr) {
        $btn.html(originalText).prop('disabled', false);
        const msg = xhr.responseJSON?.message || 'Failed to save transaction.';
        alert('Error: ' + msg);
      }
    });
  }

  // Reset form
  function resetForm() {
    document.getElementById('cashBookForm').reset();
    document.getElementById('cashBookForm').classList.remove('was-validated');
    $('#chequeDetails').addClass('d-none');
    $('#amountInWords').val('');
    $('#totalAmount').val('');
    $('#summaryVoucher').text('-');
    $('#summaryType').text('-');
    $('#summaryAmount').text('LKR 0.00');
    $('#fileList').text('');
    $('#partyNameSelect').html('<option value="">-- Select --</option>');
    $('#partyNameSelectWrap').show();
    $('#partyNameInputWrap').hide();
    $('#partyVendorManageWrap').hide();
    $('#partyName').val('');
    $('#partyId').val('');
    loadBankAccounts();
  }

  // File list display
  function updateFileList() {
    const files = $('#attachments')[0].files;
    if (files.length > 0) {
      const names = Array.from(files).map(f => f.name).join(', ');
      $('#fileList').text('Selected: ' + names);
    } else {
      $('#fileList').text('');
    }
  }

  // Event handlers
  $('#btnGenerateVoucher').on('click', generateVoucherNumber);
  $('#transactionType, #transactionDate').on('change', function() {
    if ($('#voucherNumber').val() === '') {
      generateVoucherNumber();
    }
    toggleDestinationAccount();
  });

  $('#bankAccount').on('change', function() {
    updateCurrencySymbol();
    // Update destination options to exclude selected source
    $.get('api/finance.php', { action: 'list_bank_accounts', is_active: 1 }, function(res) {
      updateDestinationAccountOptions(res.data || []);
    });
  });
  $('#modeOfPayment').on('change', toggleChequeDetails);

  $('#amount, #taxPercent').on('input', updateCalculations);

  $('#transactionType, #bankAccount').on('change', updateSummary);

  $('#attachments').on('change', updateFileList);

  $('#btnSubmit').on('click', function() { submitTransaction(false); });
  $('#btnDraft').on('click', function() { submitTransaction(true); });
  $('#btnReset').on('click', resetForm);

  // ── Party Name Dynamic Loading ───────────────────────────────────────────
  function loadPartyOptions(type) {
    const $sel = $('#partyNameSelect');
    const $selWrap = $('#partyNameSelectWrap');
    const $inputWrap = $('#partyNameInputWrap');
    const $vendorManage = $('#partyVendorManageWrap');
    $sel.html('<option value="">-- Select --</option>');
    $('#partyName').val('');
    $('#partyId').val('');

    if (!type || type === 'Other') {
      $selWrap.hide(); $inputWrap.show(); $vendorManage.hide();
      $('#partyNameInput').val('');
      return;
    }

    $selWrap.show(); $inputWrap.hide();
    $vendorManage.toggle(type === 'Vendor');

    let url = '', labelFn, idFn;
    if (type === 'Customer') {
      url = 'api/customers.php'; labelFn = r => r.name || r.company_name; idFn = r => r.id;
    } else if (type === 'Supplier') {
      url = 'api/suppliers.php'; labelFn = r => r.name; idFn = r => r.id;
    } else if (type === 'Employee') {
      url = 'api/employees.php'; labelFn = r => r.full_name; idFn = r => r.id;
    } else if (type === 'Vendor') {
      url = 'api/vendors.php'; labelFn = r => r.name + (r.category ? ' ('+r.category+')' : ''); idFn = r => r.id;
    }

    $.get(url, { action: 'list' }, function(res) {
      const items = res.data || res || [];
      items.forEach(function(r) {
        $sel.append($('<option>').val(labelFn(r)).text(labelFn(r)).attr('data-id', idFn(r)));
      });
    }).fail(function() {
      $selWrap.hide(); $inputWrap.show();
    });
  }

  $('#partyType').on('change', function() {
    loadPartyOptions($(this).val());
  });

  $('#partyNameSelect').on('change', function() {
    const val = $(this).val();
    const id = $(this).find(':selected').data('id') || '';
    $('#partyName').val(val);
    $('#partyId').val(id);
  });

  $('#partyNameInput').on('input', function() {
    $('#partyName').val($(this).val());
    $('#partyId').val('');
  });

  <?php if (has_role(['admin','super_admin'])): ?>
  // ── Vendor CRUD ──────────────────────────────────────────────────────────
  function loadVdTable() {
    $.get('api/vendors.php', { action: 'list_all' }, function(res) {
      const $tb = $('#vdTable tbody').empty();
      (res.data || []).forEach(function(v) {
        const tr = `<tr data-id="${v.id}">
          <td><input type="text" class="form-control form-control-sm vd-name" value="${$('<div>').text(v.name).html()}"></td>
          <td><input type="text" class="form-control form-control-sm vd-cat" value="${$('<div>').text(v.category||'').html()}"></td>
          <td><input type="text" class="form-control form-control-sm vd-phone" value="${$('<div>').text(v.phone||'').html()}"></td>
          <td><div class="form-check form-switch ms-2">
            <input class="form-check-input vd-active" type="checkbox" ${v.is_active==1?'checked':''}>
          </div></td>
          <td>
            <button class="btn btn-sm btn-outline-primary btnVdSave me-1" title="Save"><i class="bi bi-check-lg"></i></button>
            <button class="btn btn-sm btn-outline-danger btnVdDel" title="Delete"><i class="bi bi-trash"></i></button>
          </td></tr>`;
        $tb.append(tr);
      });
    });
  }

  $('#btnManageVendors').on('click', function() {
    loadVdTable();
    new bootstrap.Modal(document.getElementById('vendorsModal')).show();
  });

  $('#btnVdAdd').on('click', function() {
    const name = $('#vdNewName').val().trim();
    const cat  = $('#vdNewCategory').val().trim();
    const phone= $('#vdNewPhone').val().trim();
    if (!name) { alert('Vendor name is required'); return; }
    $.post('api/vendors.php', { action:'create', csrf:$('#csrf').val(), name:name, category:cat, phone:phone }, function(res) {
      if (res.success) {
        $('#vdNewName,#vdNewCategory,#vdNewPhone').val('');
        loadVdTable();
        if ($('#partyType').val()==='Vendor') loadPartyOptions('Vendor');
      } else { alert(res.message || 'Error'); }
    }).fail(function(xhr){ alert(xhr.responseJSON?.message || 'Error'); });
  });

  $(document).on('click', '.btnVdSave', function() {
    const $tr  = $(this).closest('tr');
    const id   = $tr.data('id');
    const name = $tr.find('.vd-name').val().trim();
    const cat  = $tr.find('.vd-cat').val().trim();
    const phone= $tr.find('.vd-phone').val().trim();
    const act  = $tr.find('.vd-active').is(':checked') ? 1 : 0;
    if (!name) { alert('Name required'); return; }
    $.post('api/vendors.php', { action:'update', csrf:$('#csrf').val(), id:id, name:name, category:cat, phone:phone, is_active:act }, function(res) {
      if (res.success) { if ($('#partyType').val()==='Vendor') loadPartyOptions('Vendor'); }
      else { alert(res.message || 'Error'); }
    }).fail(function(xhr){ alert(xhr.responseJSON?.message || 'Error'); });
  });

  $(document).on('click', '.btnVdDel', function() {
    const $tr  = $(this).closest('tr');
    const id   = $tr.data('id');
    const name = $tr.find('.vd-name').val();
    if (!confirm('Delete vendor "' + name + '"?')) return;
    $.post('api/vendors.php', { action:'delete', csrf:$('#csrf').val(), id:id }, function(res) {
      if (res.success) { $tr.fadeOut(300, function(){ $(this).remove(); }); if ($('#partyType').val()==='Vendor') loadPartyOptions('Vendor'); }
      else { alert(res.message || 'Error'); }
    }).fail(function(xhr){ alert(xhr.responseJSON?.message || 'Error'); });
  });
  <?php endif; ?>

  // ── Account Heads ────────────────────────────────────────────────────────
  function loadAccountHeads(selectVal) {
    $.get('api/account_heads.php', { action: 'list', active_only: 1, parent_only: 1 }, function(res) {
      const cur = selectVal !== undefined ? selectVal : $('#accountHead').val();
      const $sel = $('#accountHead');
      $sel.html('<option value="">Select Account Head</option>');
      const groups = {};
      (res.data || []).forEach(function(h) {
        if (!groups[h.account_type]) groups[h.account_type] = [];
        groups[h.account_type].push(h);
      });
      Object.keys(groups).forEach(function(cat) {
        const $og = $('<optgroup>').attr('label', cat);
        groups[cat].forEach(function(h) {
          $og.append($('<option>').val(h.account_name).text(h.account_name).attr('data-id', h.id).prop('selected', h.account_name === cur));
        });
        $sel.append($og);
      });
      // Trigger sub load if a value is pre-selected
      if (cur) loadSubAccountHeads();
    });
  }

  function loadSubAccountHeads() {
    const $sel   = $('#accountHead');
    const parentId = $sel.find(':selected').data('id');
    const $sub   = $('#subAccountHead');
    const $hint  = $('#subAccountHeadHint');
    $sub.html('<option value="">-- None --</option>');
    if (!parentId) {
      $hint.text('Select an Account Head first');
      return;
    }
    $.get('api/account_heads.php', { action: 'list', active_only: 1, parent_id: parentId }, function(res) {
      const subs = res.data || [];
      if (!subs.length) {
        $hint.text('No sub account heads — add them via Manage');
        return;
      }
      subs.forEach(function(s) {
        $sub.append($('<option>').val(s.account_name).text(s.account_name));
      });
      $hint.text(subs.length + ' sub head(s) available');
    });
  }

  $('#accountHead').on('change', loadSubAccountHeads);

  <?php if (has_role(['admin','super_admin'])): ?>
  function loadAhTable() {
    $.get('api/account_heads.php', { action: 'list_with_subs' }, function(res) {
      const csrf = $('#csrf').val();
      const $tb  = $('#ahTable tbody').empty();
      const cats = ['Asset','Liability','Income','Expense','Equity'];

      (res.data || []).forEach(function(p) {
        const catOpts = cats.map(c => `<option value="${c}"${c===p.account_type?' selected':''}>${c}</option>`).join('');
        // Parent row
        $tb.append(`<tr data-id="${p.id}" class="table-light">
          <td class="fw-bold">
            <i class="bi bi-folder2 text-primary me-1"></i>
            <input type="text" class="form-control form-control-sm d-inline-block w-75 ah-name" value="${$('<div>').text(p.account_name).html()}">
          </td>
          <td><select class="form-select form-select-sm ah-cat">${catOpts}</select></td>
          <td><div class="form-check form-switch ms-1"><input class="form-check-input ah-active" type="checkbox" ${p.is_active==1?'checked':''}></div></td>
          <td>
            <button class="btn btn-xs btn-sm btn-outline-primary btnAhSave me-1" title="Save"><i class="bi bi-check-lg"></i></button>
            <button class="btn btn-xs btn-sm btn-outline-success btnAhAddSub me-1" data-id="${p.id}" data-name="${$('<div>').text(p.account_name).html()}" title="Add Sub"><i class="bi bi-plus"></i></button>
            <button class="btn btn-xs btn-sm btn-outline-danger btnAhDel" title="Delete"><i class="bi bi-trash"></i></button>
          </td>
        </tr>`);

        // Sub rows
        (p.subs || []).forEach(function(s) {
          $tb.append(`<tr data-id="${s.id}" data-parent="${p.id}">
            <td class="ps-4 text-muted">
              <i class="bi bi-arrow-return-right me-1 text-secondary"></i>
              <input type="text" class="form-control form-control-sm d-inline-block w-75 ah-name" value="${$('<div>').text(s.account_name).html()}">
            </td>
            <td><span class="badge bg-light text-dark border">${s.account_type}</span></td>
            <td><div class="form-check form-switch ms-1"><input class="form-check-input ah-active" type="checkbox" ${s.is_active==1?'checked':''}></div></td>
            <td>
              <button class="btn btn-xs btn-sm btn-outline-primary btnAhSave me-1" title="Save"><i class="bi bi-check-lg"></i></button>
              <button class="btn btn-xs btn-sm btn-outline-danger btnAhDel" title="Delete"><i class="bi bi-trash"></i></button>
            </td>
          </tr>`);
        });

        // Inline add-sub input row (hidden by default)
        $tb.append(`<tr class="ahAddSubRow d-none" data-parent="${p.id}">
          <td class="ps-4">
            <i class="bi bi-plus-circle text-success me-1"></i>
            <input type="text" class="form-control form-control-sm d-inline-block w-75 ahSubNewName" placeholder="Sub account head name">
          </td>
          <td colspan="2"><span class="text-muted small">Inherits type: <strong>${p.account_type}</strong></span></td>
          <td>
            <button class="btn btn-sm btn-success btnAhSaveSub me-1" data-parent="${p.id}"><i class="bi bi-check-lg"></i> Save</button>
            <button class="btn btn-sm btn-outline-secondary btnAhCancelSub"><i class="bi bi-x"></i></button>
          </td>
        </tr>`);
      });
    });
  }

  $('#btnManageAccountHeads').on('click', function() {
    loadAhTable();
    new bootstrap.Modal(document.getElementById('accountHeadsModal')).show();
  });

  // Add parent account head
  $('#btnAhAdd').on('click', function() {
    const name = $('#ahNewName').val().trim();
    const cat  = $('#ahNewCategory').val();
    if (!name) { alert('Name is required'); return; }
    $.post('api/account_heads.php', { action:'create', csrf:$('#csrf').val(), name:name, category:cat }, function(res) {
      if (res.success) {
        $('#ahNewName').val('');
        loadAhTable();
        loadAccountHeads();
      } else { alert(res.message || 'Error'); }
    }).fail(function(xhr){ alert(xhr.responseJSON?.message || 'Error'); });
  });

  // Show inline add-sub row
  $(document).on('click', '.btnAhAddSub', function() {
    const pid = $(this).data('id');
    $('.ahAddSubRow').addClass('d-none'); // hide others
    $(`.ahAddSubRow[data-parent="${pid}"]`).removeClass('d-none').find('.ahSubNewName').val('').focus();
  });

  // Cancel add-sub
  $(document).on('click', '.btnAhCancelSub', function() {
    $(this).closest('tr').addClass('d-none');
  });

  // Save new sub
  $(document).on('click', '.btnAhSaveSub', function() {
    const pid  = $(this).data('parent');
    const name = $(this).closest('tr').find('.ahSubNewName').val().trim();
    if (!name) { alert('Sub account head name is required'); return; }
    $.post('api/account_heads.php', { action:'create', csrf:$('#csrf').val(), name:name, category:'Expense', parent_id:pid }, function(res) {
      if (res.success) {
        loadAhTable();
        loadAccountHeads();
        // Reload subs in main form if current parent matches
        const curId = $('#accountHead').find(':selected').data('id');
        if (curId == pid) loadSubAccountHeads();
      } else { alert(res.message || 'Error'); }
    }).fail(function(xhr){ alert(xhr.responseJSON?.message || 'Error'); });
  });

  // Save existing (parent or sub)
  $(document).on('click', '.btnAhSave', function() {
    const $tr  = $(this).closest('tr');
    const id   = $tr.data('id');
    const name = $tr.find('.ah-name').val().trim();
    const cat  = $tr.find('.ah-cat').val() || $tr.find('.badge').text().trim();
    const act  = $tr.find('.ah-active').is(':checked') ? 1 : 0;
    if (!name) { alert('Name required'); return; }
    $.post('api/account_heads.php', { action:'update', csrf:$('#csrf').val(), id:id, name:name, category:cat, is_active:act }, function(res) {
      if (res.success) { loadAccountHeads(); loadSubAccountHeads(); }
      else { alert(res.message || 'Error'); }
    }).fail(function(xhr){ alert(xhr.responseJSON?.message || 'Error'); });
  });

  // Delete (parent or sub)
  $(document).on('click', '.btnAhDel', function() {
    const $tr  = $(this).closest('tr');
    const id   = $tr.data('id');
    const name = $tr.find('.ah-name').val();
    const isParent = !$tr.data('parent');
    const msg  = isParent
      ? `Delete account head "${name}"?\nAll sub account heads under it will also be deleted.`
      : `Delete sub account head "${name}"?`;
    if (!confirm(msg)) return;
    $.post('api/account_heads.php', { action:'delete', csrf:$('#csrf').val(), id:id }, function(res) {
      if (res.success) {
        if (isParent) {
          // Remove parent row + all subs + add-sub row
          $tr.nextUntil('tr.table-light').addBack().fadeOut(300, function(){ $(this).remove(); });
        } else {
          $tr.fadeOut(300, function(){ $(this).remove(); });
        }
        loadAccountHeads();
        loadSubAccountHeads();
      } else { alert(res.message || 'Error'); }
    }).fail(function(xhr){ alert(xhr.responseJSON?.message || 'Error'); });
  });
  <?php endif; ?>

  // ── Cost Centers ─────────────────────────────────────────────────────────
  function loadCostCenters(selectVal) {
    $.get('api/cost_centers.php', { action: 'list', active_only: 1 }, function(res) {
      const cur = selectVal !== undefined ? selectVal : $('#costCenter').val();
      const $sel = $('#costCenter');
      $sel.html('<option value="">Select Cost Center</option>');
      (res.data || []).forEach(function(c) {
        $sel.append($('<option>').val(c.name).text(c.name).prop('selected', c.name === cur));
      });
    });
  }

  <?php if (has_role(['admin','super_admin'])): ?>
  function loadCcTable() {
    $.get('api/cost_centers.php', { action: 'list', active_only: 0 }, function(res) {
      const $tb = $('#ccTable tbody').empty();
      (res.data || []).forEach(function(c) {
        $tb.append(`<tr data-id="${c.id}">
          <td><input type="text" class="form-control form-control-sm cc-name" value="${$('<div>').text(c.name).html()}"></td>
          <td><input type="text" class="form-control form-control-sm cc-desc" value="${$('<div>').text(c.description||'').html()}"></td>
          <td><div class="form-check form-switch ms-1"><input class="form-check-input cc-active" type="checkbox" ${c.is_active==1?'checked':''}></div></td>
          <td>
            <button class="btn btn-sm btn-outline-primary btnCcSave me-1" title="Save"><i class="bi bi-check-lg"></i></button>
            <button class="btn btn-sm btn-outline-danger btnCcDel" title="Delete"><i class="bi bi-trash"></i></button>
          </td>
        </tr>`);
      });
    });
  }

  $('#btnManageCostCenters').on('click', function() {
    loadCcTable();
    new bootstrap.Modal(document.getElementById('costCentersModal')).show();
  });

  $('#btnCcAdd').on('click', function() {
    const name = $('#ccNewName').val().trim();
    const desc = $('#ccNewDesc').val().trim();
    if (!name) { alert('Name is required'); return; }
    $.post('api/cost_centers.php', { action:'create', csrf:$('#csrf').val(), name:name, description:desc }, function(res) {
      if (res.success) {
        $('#ccNewName,#ccNewDesc').val('');
        loadCcTable();
        loadCostCenters();
      } else { alert(res.message || 'Error'); }
    }).fail(function(xhr){ alert(xhr.responseJSON?.message || 'Error'); });
  });

  $(document).on('click', '.btnCcSave', function() {
    const $tr  = $(this).closest('tr');
    const id   = $tr.data('id');
    const name = $tr.find('.cc-name').val().trim();
    const desc = $tr.find('.cc-desc').val().trim();
    const act  = $tr.find('.cc-active').is(':checked') ? 1 : 0;
    if (!name) { alert('Name required'); return; }
    $.post('api/cost_centers.php', { action:'update', csrf:$('#csrf').val(), id:id, name:name, description:desc, is_active:act }, function(res) {
      if (res.success) { loadCostCenters(); }
      else { alert(res.message || 'Error'); }
    }).fail(function(xhr){ alert(xhr.responseJSON?.message || 'Error'); });
  });

  $(document).on('click', '.btnCcDel', function() {
    const $tr = $(this).closest('tr');
    const id  = $tr.data('id');
    const nm  = $tr.find('.cc-name').val();
    if (!confirm('Delete cost center "' + nm + '"?')) return;
    $.post('api/cost_centers.php', { action:'delete', csrf:$('#csrf').val(), id:id }, function(res) {
      if (res.success) { $tr.fadeOut(300, function(){ $(this).remove(); }); loadCostCenters(); }
      else { alert(res.message || 'Error'); }
    }).fail(function(xhr){ alert(xhr.responseJSON?.message || 'Error'); });
  });
  <?php endif; ?>

  // Initialize
  loadBankAccounts();
  loadAccountHeads();
  loadCostCenters();
  toggleChequeDetails();
  toggleDestinationAccount();
})();
</script>
