<?php
/*
Supplier Payment Management System
ERP Style GUI | PHP 8.2 Compatible | Light Green Theme
Full Screen | Single File | Professional CRUD
*/

session_start();

// Database configuration
$host = 'localhost';
$dbname = 'whitetil_mount';
$username = 'whitetil_mount';
$password = 'UGeC5=E)toCtUK(j';

// Error reporting for development (disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database Connection Failed: " . $e->getMessage());
}

function formatRefNo(int $number): string {
    return 'PAY' . str_pad((string)$number, 6, '0', STR_PAD_LEFT);
}

function getLastSavedRefNo(PDO $pdo): int {
    $stmt = $pdo->query("SELECT MAX(CAST(SUBSTRING(REFNO, 4) AS UNSIGNED)) as max_ref FROM a_paymas WHERE REFNO LIKE 'PAY%'");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return (int)($row['max_ref'] ?? 0);
}

function getNextRefSequence(PDO $pdo, bool $lockCounter = false): int {
    $sql = "SELECT A FROM invpara LIMIT 1" . ($lockCounter ? " FOR UPDATE" : "");
    $stmt = $pdo->query($sql);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $lastCounter = (int)($row['A'] ?? 0);
    $lastSaved = getLastSavedRefNo($pdo);
    return max($lastCounter, $lastSaved) + 1;
}

function previewRefNo(PDO $pdo): string {
    return formatRefNo(getNextRefSequence($pdo));
}

// Allocate next ref no only when the record is actually saved
function allocateRefNo(PDO $pdo): string {
    $next = getNextRefSequence($pdo, true);
    $update = $pdo->prepare("UPDATE invpara SET A = ?");
    $update->execute([$next]);
    return formatRefNo($next);
}

// Handle AJAX requests
if (isset($_POST['ajax_action'])) {
    header('Content-Type: application/json');
    $response = ['success' => false, 'message' => ''];
    
    try {
        switch ($_POST['ajax_action']) {
            case 'get_new_refno':
                $response['success'] = true;
                $response['refno'] = previewRefNo($pdo);
                break;

            case 'get_outstanding':
                $cuscode = $_POST['cuscode'] ?? '';
                $stmt = $pdo->prepare("
                    SELECT 
                        c.REFNO as c_bal_no, 
                        c.SDATE as c_bal_date, 
                        c.CUSCODE, 
                        c.AMOUNT as c_bal_amount, 
                        c.totpay, 
                        c.Balance, 
                        c.payment_date,
                        p.ORDNO,
                        p.blno
                    FROM c_bal c
                    LEFT JOIN s_purmas p ON c.REFNO = p.REFNO
                    WHERE c.BALANCE > 0 AND c.CUSCODE = ?
                ");
                $stmt->execute([$cuscode]);
                $response['data'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
                $response['success'] = true;
                break;
                
            case 'save_payment':
                $pdo->beginTransaction();

                $isEdit = !empty($_POST['is_edit']) && $_POST['is_edit'] === '1';
                $postedRefNo = trim($_POST['refno'] ?? '');
                $gridData = json_decode($_POST['grid_data'] ?? '[]', true);

                if (!is_array($gridData)) {
                    throw new Exception('Invalid payment details');
                }

                if ($isEdit) {
                    if ($postedRefNo === '') {
                        throw new Exception('Reference number is required for update');
                    }

                    $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM a_paymas WHERE REFNO = ?");
                    $checkStmt->execute([$postedRefNo]);
                    if ((int)$checkStmt->fetchColumn() === 0) {
                        throw new Exception('Payment record not found');
                    }

                    $refno = $postedRefNo;

                    $reverseStmt = $pdo->prepare("SELECT c_bal_no, cur_paid FROM c_bal_sttr WHERE refno = ?");
                    $reverseStmt->execute([$refno]);
                    foreach ($reverseStmt->fetchAll(PDO::FETCH_ASSOC) as $oldRow) {
                        $undoStmt = $pdo->prepare("UPDATE c_bal SET totpay = totpay - ?, balance = balance + ? WHERE REFNO = ?");
                        $undoStmt->execute([$oldRow['cur_paid'], $oldRow['cur_paid'], $oldRow['c_bal_no']]);
                    }

                    $deleteStmt = $pdo->prepare("DELETE FROM c_bal_sttr WHERE refno = ?");
                    $deleteStmt->execute([$refno]);

                    $stmt = $pdo->prepare("UPDATE a_paymas SET BDATE = ?, entdate = ?, NAME = ?, VEN_CODE = ?, bank_name = ?, CHENO = ?, Barer = ?, HEADING = ?, NARATION = ?, AMOUNT = ?, Type = ?, VOUNO = ?, VOUDATE = ?, AC_Payee = ?, COMPANY = ?, chqdt = ?, PAY_TYPE = ? WHERE REFNO = ?");
                    $stmt->execute([
                        $_POST['bdate'],
                        $_POST['entdate'],
                        $_POST['name'],
                        $_POST['ven_code'],
                        $_POST['bank_name'],
                        $_POST['cheno'],
                        $_POST['barer'],
                        $_POST['heading'],
                        $_POST['naration'],
                        $_POST['amount'],
                        $_POST['type'],
                        $_POST['vouno'],
                        $_POST['voudate'],
                        $_POST['ac_payee'],
                        $_POST['company'],
                        $_POST['chqdt'],
                        $_POST['pay_type'],
                        $refno
                    ]);

                    $actionText = 'Updated';
                } else {
                    $refno = allocateRefNo($pdo);

                    $stmt = $pdo->prepare("INSERT INTO a_paymas (REFNO, BDATE, entdate, NAME, VEN_CODE, bank_name, CHENO, Barer, HEADING, NARATION, AMOUNT, Type, VOUNO, VOUDATE, AC_Payee, COMPANY, chqdt, PAY_TYPE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([
                        $refno,
                        $_POST['bdate'],
                        $_POST['entdate'],
                        $_POST['name'],
                        $_POST['ven_code'],
                        $_POST['bank_name'],
                        $_POST['cheno'],
                        $_POST['barer'],
                        $_POST['heading'],
                        $_POST['naration'],
                        $_POST['amount'],
                        $_POST['type'],
                        $_POST['vouno'],
                        $_POST['voudate'],
                        $_POST['ac_payee'],
                        $_POST['company'],
                        $_POST['chqdt'],
                        $_POST['pay_type']
                    ]);

                    $actionText = 'Saved';
                }

                foreach ($gridData as $row) {
                    if (!empty($row['cur_paid']) && $row['cur_paid'] > 0) {
                        // Insert into c_bal_sttr
                        $stmt2 = $pdo->prepare("INSERT INTO c_bal_sttr (refno, sdate, c_bal_no, c_bal_date, c_bal_amount, VEN_CODE, NAME, cur_paid, che_no, che_date, che_bank) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        $stmt2->execute([
                            $refno,
                            date('Y-m-d'),
                            $row['c_bal_no'],
                            $row['c_bal_date'],
                            $row['c_bal_amount'],
                            $_POST['ven_code'],
                            $_POST['name'],
                            $row['cur_paid'],
                            $_POST['cheno'],
                            $_POST['chqdt'],
                            $_POST['bank_name']
                        ]);
                        
                        // Update c_bal
                        $stmt3 = $pdo->prepare("UPDATE c_bal SET totpay = totpay + ?, balance = balance - ? WHERE REFNO = ?");
                        $stmt3->execute([$row['cur_paid'], $row['cur_paid'], $row['c_bal_no']]);
                    }
                }
                
                $pdo->commit();
                $response['success'] = true;
                $response['refno'] = $refno;
                $response['message'] = "$actionText Successfully! Ref No: $refno";
                break;
                
            case 'find_payment':
                $search = $_POST['search'] . '%';
                $stmt = $pdo->prepare("SELECT REFNO, entdate, BDATE, Barer FROM a_paymas WHERE REFNO LIKE ? OR Barer LIKE ? LIMIT 50");
                $stmt->execute([$search, $search]);
                $response['data'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
                $response['success'] = true;
                break;
                
            case 'load_payment':
                $refno = $_POST['refno'];
                $stmt = $pdo->prepare("SELECT * FROM a_paymas WHERE REFNO = ?");
                $stmt->execute([$refno]);
                $response['header'] = $stmt->fetch(PDO::FETCH_ASSOC);
                
                $stmt2 = $pdo->prepare("SELECT c_bal_no, c_bal_date, c_bal_amount, cur_paid as paid FROM c_bal_sttr WHERE refno = ?");
                $stmt2->execute([$refno]);
                $response['details'] = $stmt2->fetchAll(PDO::FETCH_ASSOC);
                $response['success'] = true;
                break;
        }
    } catch (Exception $e) {
        if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
        $response['message'] = $e->getMessage();
    }
    
    echo json_encode($response);
    exit;
}

// Get vendors for combo box
$vendors = [];
$stmt = $pdo->query("SELECT code as VEN_CODE, name as name FROM vendor WHERE cat='S' OR cat='B' ORDER BY name");
$vendors = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get current date for default values
$today = date('Y-m-d');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>Supplier Payment Manager | ERP System</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
            height: 100vh;
            overflow: hidden;
            color: #1a3a1a;
        }
        
        /* Full Screen Container */
        .app-container {
            height: 100vh;
            display: flex;
            flex-direction: column;
            padding: 12px;
            gap: 12px;
        }
        
        /* Button Bar */
        .button-bar {
            background: #2e5c2e;
            padding: 10px 15px;
            border-radius: 20px;
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            backdrop-filter: blur(2px);
        }
        
        .btn {
            padding: 8px 18px;
            border: none;
            border-radius: 40px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 12px;
            letter-spacing: 0.5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            color: #1e2a1e;
        }
        
        .btn-primary { background: #ffd966; border-bottom: 3px solid #b8860b; }
        .btn-primary:hover { background: #ffedb3; transform: translateY(-1px); }
        .btn-success { background: #81c784; border-bottom: 3px solid #2e7d32; }
        .btn-success:hover { background: #a5d6a7; }
        .btn-warning { background: #ffb74d; border-bottom: 3px solid #f57c00; }
        .btn-danger { background: #e57373; border-bottom: 3px solid #c62828; }
        .btn-info { background: #64b5f6; border-bottom: 3px solid #1565c0; }
        .btn-secondary { background: #bdbdbd; border-bottom: 3px solid #616161; }
        
        /* Main Content Grid */
        .main-grid {
            display: flex;
            gap: 12px;
            flex: 1;
            min-height: 0;
        }
        
        /* Left Panel - Input Form */
        .form-panel {
            flex: 0 0 380px;
            background: rgba(255,255,240,0.92);
            border-radius: 20px;
            padding: 12px 15px;
            overflow-y: auto;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            backdrop-filter: blur(4px);
        }
        
        .form-row {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            gap: 12px;
        }
        
        .form-row label {
            width: 95px;
            font-weight: 600;
            font-size: 11px;
            color: #2c5e2c;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }
        
        .form-row input, .form-row select {
            flex: 1;
            padding: 6px 8px;
            border: 1px solid #b9f6ca;
            border-radius: 20px;
            font-size: 12px;
            background: #fffff0;
            transition: all 0.2s;
            color: #1e3a1e;
        }
        
        .form-row input:focus, .form-row select:focus {
            outline: none;
            border-color: #4caf50;
            box-shadow: 0 0 0 2px rgba(76,175,80,0.2);
        }
        
        /* Right Panel - Grid */
        .grid-panel {
            flex: 1;
            background: rgba(255,255,245,0.92);
            border-radius: 20px;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }
        
        .grid-header {
            background: #3c6e3c;
            padding: 10px 12px;
            color: white;
            font-weight: bold;
            font-size: 13px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .grid-container {
            flex: 1;
            overflow: auto;
            padding: 8px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 11px;
        }
        
        th, td {
            padding: 8px 6px;
            text-align: left;
            border-bottom: 1px solid #c8e6c9;
        }
        
        th {
            background: #dcedc8;
            color: #1b5e1b;
            position: sticky;
            top: 0;
            font-weight: 600;
        }
        
        .paid-input {
            width: 90px;
            padding: 4px 6px;
            border-radius: 20px;
            border: 1px solid #81c784;
            text-align: right;
            font-size: 11px;
        }
        
        /* Status Bar */
        .status-bar {
            background: #2e5c2e;
            padding: 6px 15px;
            border-radius: 30px;
            font-size: 11px;
            color: #f5f5dc;
            display: flex;
            justify-content: space-between;
        }
        
        /* Scrollbar */
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: #d0e8d0; border-radius: 10px; }
        ::-webkit-scrollbar-thumb { background: #5a9e5a; border-radius: 10px; }
        
        /* Loading Overlay */
        .loading {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            color: white;
            font-size: 24px;
        }
        
        .shortcut-hint {
            font-size: 9px;
            margin-left: 5px;
            opacity: 0.7;
        }
        
        button:active { transform: scale(0.97); }
    </style>
</head>
<body>
<div class="app-container">
    <div class="button-bar">
        <button class="btn btn-primary" id="btnNew" accesskey="N">📄 New (Alt+N)</button>
        <button class="btn btn-success" id="btnSave" accesskey="S">💾 Save (Alt+S)</button>
        <button class="btn btn-info" id="btnPrint" accesskey="P">🖨️ Print (Alt+P)</button>
        <button class="btn btn-warning" id="btnFind" accesskey="F">🔍 Find (Alt+F)</button>
        <button class="btn btn-danger" id="btnCancel" accesskey="C">❌ Cancel (Alt+C)</button>
        <!-- Modified Report Button to open ac_report.php in a new tab -->
        <button class="btn btn-secondary" id="btnReport" accesskey="R">📊 Report Center (Alt+R)</button>
        <button class="btn btn-secondary" id="btnExit" accesskey="E">🚪 Exit (Alt+E)</button>
    </div>
    
    <div class="main-grid">
        <!-- Left Form Panel -->
        <div class="form-panel">
            <div class="form-row"><label>REFNO</label><input type="text" id="REFNO" readonly style="background:#e0f2e0;"></div>
            <div class="form-row"><label>BDATE</label><input type="date" id="BDATE" value="<?= $today ?>"></div>
            <div class="form-row"><label>ENTDATE</label><input type="date" id="ENTDATE" value="<?= $today ?>"></div>
            <div class="form-row"><label>VENDOR</label>
                <select id="VEN_CODE">
                    <option value="">-- Select Vendor --</option>
                    <?php foreach($vendors as $v): ?>
                        <option value="<?= htmlspecialchars($v['VEN_CODE']) ?>"><?= htmlspecialchars($v['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-row"><label>NAME</label><input type="text" id="NAME" placeholder="Vendor Name"></div>
            <div class="form-row"><label>BANK NAME</label><input type="text" id="bank_name"></div>
            <div class="form-row"><label>CHEQUE NO</label><input type="text" id="CHENO"></div>
            <div class="form-row"><label>BARER</label><input type="text" id="Barer"></div>
            <div class="form-row"><label>HEADING</label><input type="text" id="HEADING"></div>
            <div class="form-row"><label>NARRATION</label><input type="text" id="NARATION"></div>
            <div class="form-row"><label>AMOUNT</label><input type="number" step="0.01" id="AMOUNT"></div>
            <div class="form-row"><label>VOUNO</label><input type="text" id="VOUNO"></div>
            <div class="form-row"><label>VOUDATE</label><input type="date" id="VOUDATE" value="<?= $today ?>"></div>
            <div class="form-row"><label>CHQ DATE</label><input type="date" id="chqdt" value="<?= $today ?>"></div>
            <div class="form-row"><label>PAY TYPE</label><input type="text" id="PAY_TYPE" placeholder="Cheque/Cash"></div>
            <div class="form-row"><label>TYPE</label><input type="text" id="Type" value="SUPPLIER"></div>
            <div class="form-row"><label>AC PAYEE</label><input type="text" id="AC_Payee"></div>
            <div class="form-row"><label>COMPANY</label><input type="text" id="COMPANY" value="MAIN"></div>
        </div>
        
        <!-- Right Grid Panel -->
        <div class="grid-panel">
            <div class="grid-header">
                <span>OUTSTANDING INVOICES (Double-click to set paid amount)</span>
                <span id="vendorNameDisplay"></span>
            </div>
            <div class="grid-container">
                <table id="outstandingGrid">
                    <thead>
                        <tr>
                            <th>ARN No</th>
                            <th>PO No</th>
                            <th>Bill No</th>
                            <th>Date</th>
                            <th style="text-align:right;">Amount</th>
                            <th style="text-align:right;">Paid</th>
                            <th style="text-align:right;">Balance</th>
                            <th>Payment</th>
                        </tr>
                    </thead>
                    <tbody id="gridBody">
                        <!-- Rows will be inserted here by JavaScript -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <div class="status-bar">
        <span>✅ Ready | ERP Payment Module</span>
        <span>🔑 Tab Key Navigation | Enter = Next Field</span>
    </div>
</div>
<div class="loading" id="loadingOverlay">⏳ Processing...</div>

<script>
    // DOM Elements
    const formElements = {
        REFNO: document.getElementById('REFNO'),
        BDATE: document.getElementById('BDATE'),
        ENTDATE: document.getElementById('ENTDATE'),
        VEN_CODE: document.getElementById('VEN_CODE'),
        NAME: document.getElementById('NAME'),
        bank_name: document.getElementById('bank_name'),
        CHENO: document.getElementById('CHENO'),
        Barer: document.getElementById('Barer'),
        HEADING: document.getElementById('HEADING'),
        NARATION: document.getElementById('NARATION'),
        AMOUNT: document.getElementById('AMOUNT'),
        VOUNO: document.getElementById('VOUNO'),
        VOUDATE: document.getElementById('VOUDATE'),
        chqdt: document.getElementById('chqdt'),
        PAY_TYPE: document.getElementById('PAY_TYPE'),
        Type: document.getElementById('Type'),
        AC_Payee: document.getElementById('AC_Payee'),
        COMPANY: document.getElementById('COMPANY')
    };
    
    let currentOutstanding = [];
    let isEditMode = false;
    
    // Loading overlay
    function showLoading(show) {
        document.getElementById('loadingOverlay').style.display = show ? 'flex' : 'none';
    }
    
    // Fetch outstanding based on vendor code
    async function loadOutstanding(vendorCode, vendorName) {
        if (!vendorCode) {
            document.getElementById('gridBody').innerHTML = '<tr><td colspan="6" style="text-align:center">Select a vendor to load outstanding</td></tr>';
            currentOutstanding = [];
            return;
        }
        document.getElementById('vendorNameDisplay').innerText = vendorName;
        showLoading(true);
        try {
            const formData = new FormData();
            formData.append('ajax_action', 'get_outstanding');
            formData.append('cuscode', vendorCode);
            const resp = await fetch('', { method: 'POST', body: formData });
            const data = await resp.json();
            if (data.success) {
                currentOutstanding = data.data;
                renderGrid();
            } else {
                alert('Error loading outstanding');
            }
        } catch(e) { console.error(e); alert('Network error'); }
        finally { showLoading(false); }
    }
    
    function renderGrid() {
        const gridBody = document.getElementById('gridBody');
        let html = '';
        
        currentOutstanding.forEach(row => {
            html += `
                <tr>
                    <td>${escapeHtml(row.c_bal_no)}</td>
                    <td>${escapeHtml(row.ORDNO || '')}</td>
                    <td>${escapeHtml(row.blno || '')}</td>
                    <td>${escapeHtml(row.c_bal_date)}</td>
                    <td style="text-align:right;">${parseFloat(row.c_bal_amount).toFixed(2)}</td>
                    <td style="text-align:right;">${parseFloat(row.totpay).toFixed(2)}</td>
                    <td style="text-align:right;">${parseFloat(row.Balance).toFixed(2)}</td>
                    <td><input type="number" class="paid-input" data-refno="${escapeHtml(row.c_bal_no)}" value="${row.cur_paid || ''}" step="0.01"></td>
                </tr>
            `;
        });
        
        gridBody.innerHTML = html;
        
        // Add event listeners to the new input fields
        gridBody.querySelectorAll('.paid-input').forEach(input => {
            input.addEventListener('input', function() {
                const refno = this.dataset.refno;
                const value = this.value;
                const invoice = currentOutstanding.find(inv => inv.c_bal_no === refno);
                if (invoice) {
                    invoice.cur_paid = parseFloat(value) || 0;
                }
            });
        });
    }
    
    function escapeHtml(str) { return String(str).replace(/[&<>]/g, function(m){if(m==='&') return '&amp;'; if(m==='<') return '&lt;'; if(m==='>') return '&gt;'; return m;}); }
    
    // Save Payment
    async function savePayment() {
        // Validation
        if (!formElements.VEN_CODE.value) { alert('Select Vendor'); formElements.VEN_CODE.focus(); return; }
        const paidEntries = currentOutstanding.filter(inv => inv.cur_paid && inv.cur_paid > 0);
        if (paidEntries.length === 0) { alert('Please enter at least one payment amount in the grid'); return; }

        const totalPaid = currentOutstanding.reduce((sum, inv) => sum + (parseFloat(inv.cur_paid) || 0), 0);
        const amount = parseFloat(formElements.AMOUNT.value) || 0;

        if (totalPaid.toFixed(2) !== amount.toFixed(2)) {
            alert('Total paid amount in the grid must match the Amount field.');
            return;
        }
        
        const gridData = currentOutstanding.filter(inv => inv.cur_paid > 0).map(inv => ({
            c_bal_no: inv.c_bal_no,
            c_bal_date: inv.c_bal_date,
            c_bal_amount: inv.c_bal_amount,
            cur_paid: inv.cur_paid
        }));
        
        showLoading(true);
        const formData = new FormData();
        formData.append('ajax_action', 'save_payment');
        formData.append('bdate', formElements.BDATE.value);
        formData.append('entdate', formElements.ENTDATE.value);
        formData.append('ven_code', formElements.VEN_CODE.value);
        formData.append('name', formElements.NAME.value);
        formData.append('bank_name', formElements.bank_name.value);
        formData.append('cheno', formElements.CHENO.value);
        formData.append('barer', formElements.Barer.value);
        formData.append('heading', formElements.HEADING.value);
        formData.append('naration', formElements.NARATION.value);
        formData.append('amount', formElements.AMOUNT.value);
        formData.append('vouno', formElements.VOUNO.value);
        formData.append('voudate', formElements.VOUDATE.value);
        formData.append('chqdt', formElements.chqdt.value);
        formData.append('pay_type', formElements.PAY_TYPE.value);
        formData.append('type', formElements.Type.value);
        formData.append('ac_payee', formElements.AC_Payee.value);
        formData.append('company', formElements.COMPANY.value);
        formData.append('refno', formElements.REFNO.value);
        formData.append('is_edit', isEditMode ? '1' : '0');
        formData.append('grid_data', JSON.stringify(gridData));
        
        try {
            const resp = await fetch('', { method: 'POST', body: formData });
            const data = await resp.json();
            if (data.success) {
                const savedRefNo = data.refno || formElements.REFNO.value;
                alert(data.message);
                if (savedRefNo) {
                    formElements.REFNO.value = savedRefNo;
                    await printVoucher(savedRefNo);
                }
                await newPayment();
            } else {
                alert('Error: ' + data.message);
            }
        } catch(e) { alert('Save failed'); }
        finally { showLoading(false); }
    }
    
    async function printVoucher(refno) {
        // Print via window print simulation - open new window with report
        const win = window.open('', '_blank');
        win.document.write('<html><head><title>Payment Voucher ' + refno + '</title><style>body{font-family:monospace; padding:20px;} table{border-collapse:collapse; width:100%} th,td{border:1px solid #ccc; padding:6px}</style></head><body>');
        win.document.write('<h2>SUPPLIER PAYMENT VOUCHER</h2><hr>');
        // fetch details via ajax
        const formData = new FormData();
        formData.append('ajax_action', 'load_payment');
        formData.append('refno', refno);
        const resp = await fetch('', { method: 'POST', body: formData });
        const data = await resp.json();
        if (data.success && data.header) {
            win.document.write('<p><strong>Ref No:</strong> ' + data.header.REFNO + '</p>');
            win.document.write('<p><strong>Date:</strong> ' + data.header.BDATE + ' | Vendor: ' + data.header.NAME + '</p>');
            win.document.write('<p><strong>Bank:</strong> ' + data.header.bank_name + ' | Cheque: ' + data.header.CHENO + '</p>');
            win.document.write('<h3>Payment Details</h3><table><tr><th>Invoice No</th><th>Date</th><th>Amount</th><th>Paid</th></tr>');
            let totalPaid = 0;
            if (data.details) {
                data.details.forEach(d => {
                    win.document.write(`<tr><td>${d.c_bal_no}</td><td>${d.c_bal_date}</td><td>${parseFloat(d.c_bal_amount).toFixed(2)}</td><td>${parseFloat(d.paid).toFixed(2)}</td></tr>`);
                    totalPaid += parseFloat(d.paid);
                });
            }
            win.document.write(`<tr style="font-weight:bold"><td colspan="3">Total Paid</td><td>${totalPaid.toFixed(2)}</td></tr></table>`);
            win.document.write('<p><strong>Narration:</strong> ' + data.header.NARATION + '</p>');
            win.document.write('<hr><p>Authorized Signature</p>');
        }
        win.document.write('</body></html>');
        win.document.close();
        win.print();
    }
    
    // Find Payment
    async function findPayment() {
        let search = prompt("Enter Reference No or Barer Name:", "");
        if (!search) return;
        showLoading(true);
        const formData = new FormData();
        formData.append('ajax_action', 'find_payment');
        formData.append('search', search);
        const resp = await fetch('', { method: 'POST', body: formData });
        const data = await resp.json();
        showLoading(false);
        if (data.success && data.data.length) {
            let list = data.data.map(p => `${p.REFNO} | ${p.BDATE} | ${p.Barer}`).join('\n');
            let selected = prompt("Select Payment (Copy Ref No):\n" + list, data.data[0].REFNO);
            if (selected) loadPaymentForEdit(selected.trim());
        } else {
            alert("No records found");
        }
    }
    
    async function loadPaymentForEdit(refno) {
        showLoading(true);
        const formData = new FormData();
        formData.append('ajax_action', 'load_payment');
        formData.append('refno', refno);
        const resp = await fetch('', { method: 'POST', body: formData });
        const data = await resp.json();
        showLoading(false);
        if (data.success && data.header) {
            isEditMode = true;
            formElements.REFNO.value = data.header.REFNO;
            formElements.BDATE.value = data.header.BDATE;
            formElements.ENTDATE.value = data.header.entdate;
            formElements.VEN_CODE.value = data.header.VEN_CODE;
            formElements.NAME.value = data.header.NAME;
            formElements.bank_name.value = data.header.bank_name;
            formElements.CHENO.value = data.header.CHENO;
            formElements.Barer.value = data.header.Barer;
            formElements.HEADING.value = data.header.HEADING;
            formElements.NARATION.value = data.header.NARATION;
            formElements.AMOUNT.value = data.header.AMOUNT;
            formElements.VOUNO.value = data.header.VOUNO;
            formElements.VOUDATE.value = data.header.VOUDATE;
            formElements.chqdt.value = data.header.chqdt;
            formElements.PAY_TYPE.value = data.header.PAY_TYPE;
            formElements.Type.value = data.header.Type;
            formElements.AC_Payee.value = data.header.AC_Payee;
            formElements.COMPANY.value = data.header.COMPANY;
            document.getElementById('vendorNameDisplay').innerText = data.header.NAME || 'Select Vendor';
            currentOutstanding = [];
            // load grid from details
            if (data.details) {
                currentOutstanding = data.details.map(d => ({
                    c_bal_no: d.c_bal_no,
                    c_bal_date: d.c_bal_date,
                    c_bal_amount: d.c_bal_amount,
                    totpay: 0,
                    Balance: d.c_bal_amount,
                    cur_paid: d.paid
                }));
            }
            renderGrid();
        } else alert("Cannot load payment");
    }
    
    async function fetchNewRefNo() {
        const formData = new FormData();
        formData.append('ajax_action', 'get_new_refno');
        try {
            const resp = await fetch('', { method: 'POST', body: formData });
            const data = await resp.json();
            if (data.success && data.refno) {
                formElements.REFNO.value = data.refno;
            } else {
                formElements.REFNO.value = 'AUTO-GEN';
                alert('Unable to load new reference number');
            }
        } catch(e) {
            formElements.REFNO.value = 'AUTO-GEN';
            alert('Network error while getting reference number');
        }
    }

    async function newPayment() {
        isEditMode = false;
        clearForm();
        formElements.BDATE.value = '<?= $today ?>';
        formElements.ENTDATE.value = '<?= $today ?>';
        formElements.VOUDATE.value = '<?= $today ?>';
        formElements.chqdt.value = '<?= $today ?>';
        await fetchNewRefNo();
        if (formElements.VEN_CODE.value) loadOutstanding(formElements.VEN_CODE.value, formElements.NAME.value);
        else document.getElementById('gridBody').innerHTML = '<tr><td colspan="6">Select vendor first</td></tr>';
    }
    
    function clearForm() {
        isEditMode = false;
        for(let key in formElements) {
            if (formElements[key] && formElements[key].tagName === 'INPUT' && formElements[key].type !== 'button')
                formElements[key].value = '';
            if (formElements[key] && formElements[key].tagName === 'SELECT')
                formElements[key].value = '';
        }
        formElements.BDATE.value = '<?= $today ?>';
        formElements.ENTDATE.value = '<?= $today ?>';
        formElements.VOUDATE.value = '<?= $today ?>';
        formElements.chqdt.value = '<?= $today ?>';
        currentOutstanding = [];
        document.getElementById('vendorNameDisplay').innerText = 'Select Vendor';
        renderGrid();
    }
    
    function cancelEdit() { newPayment(); alert("Form reset"); }
    
    // Modified Report Center function - opens ac_report.php in new tab
    function openReportCenter() {
        // Open the report center in a new tab/window
        window.open('ac_report.php', '_blank');
    }
    
    function exitApp() { 
        if (confirm('Are you sure you want to exit?')) {
            window.close(); 
        }
    }
    
    // Vendor selection change
    formElements.VEN_CODE.addEventListener('change', async function() {
        let code = this.value;
        let name = this.options[this.selectedIndex]?.text || '';
        formElements.NAME.value = name;
        if (code) await loadOutstanding(code, name);
        else document.getElementById('gridBody').innerHTML = '<tr><td colspan="6">Select vendor</td></tr>';
    });

    // Enter as Tab: capture keydown on inputs
    document.querySelectorAll('input, select, button').forEach(el => {
        el.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                const focusable = Array.from(document.querySelectorAll('input, select, button'));
                let idx = focusable.indexOf(this);
                if (idx !== -1 && focusable[idx + 1]) focusable[idx + 1].focus();
                else if (idx !== -1 && idx === focusable.length-1) focusable[0].focus();
            }
        });
    });
    
    // Button Events
    document.getElementById('btnNew').addEventListener('click', newPayment);
    document.getElementById('btnSave').addEventListener('click', savePayment);
    document.getElementById('btnPrint').addEventListener('click', () => { if(formElements.REFNO.value && formElements.REFNO.value !== 'AUTO-GEN') printVoucher(formElements.REFNO.value); else alert('Save first to print'); });
    document.getElementById('btnFind').addEventListener('click', findPayment);
    document.getElementById('btnCancel').addEventListener('click', cancelEdit);
    
    // Modified Report Button - opens ac_report.php in new tab
    document.getElementById('btnReport').addEventListener('click', openReportCenter);
    
    document.getElementById('btnExit').addEventListener('click', exitApp);
    
    // Initial load
    newPayment();
    
    // shortcut hint overlay
    console.log("Ready - Tab navigation active");
</script>
</body>
</html>