<?php
require 'auth_check.php';
require_once 'db.php';

$action = $_GET['action'] ?? 'add';
$id     = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if ($action === 'edit' && !$id) { header('Location: transaction_details.php'); exit; }

$tx = [];
if ($action === 'edit') {
    $stmt = $pdo->prepare("SELECT * FROM transactions WHERE id = ?");
    $stmt->execute([$id]);
    $tx = $stmt->fetch();
    if (!$tx) { header('Location: transaction_details.php'); exit; }
}

function v(string $field, array $tx, string $default = ''): string {
    return htmlspecialchars($tx[$field] ?? $default);
}
function sel(string $field, string $val, array $tx): string {
    return ($tx[$field] ?? '') === $val ? 'selected' : '';
}

$departments = $pdo->query("SELECT name FROM departments ORDER BY name")->fetchAll(PDO::FETCH_COLUMN);
$vendors     = $pdo->query("SELECT DISTINCT vendor FROM transactions WHERE vendor <> '' ORDER BY vendor")->fetchAll(PDO::FETCH_COLUMN);
$items       = $pdo->query("SELECT DISTINCT item FROM transactions WHERE item <> '' ORDER BY item")->fetchAll(PDO::FETCH_COLUMN);
$contacts    = $pdo->query("SELECT DISTINCT contact FROM transactions WHERE contact IS NOT NULL AND contact <> '' ORDER BY contact")->fetchAll(PDO::FETCH_COLUMN);
$emails      = $pdo->query("SELECT DISTINCT email FROM transactions WHERE email IS NOT NULL AND email <> '' ORDER BY email")->fetchAll(PDO::FETCH_COLUMN);

$isEdit    = $action === 'edit';
$pageTitle = $isEdit ? 'Edit Transaction' : 'New Transaction';
$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">
<title><?= $pageTitle ?> | Mei Hotel Penang</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="assets/style.css">
<style>
*, *::before, *::after { box-sizing: border-box; }
html, body { height: 100%; margin: 0; background: #f1f5f9; font-family: Inter, system-ui, sans-serif; overflow: hidden; }

/* ── Shell: sidebar + content ── */
.shell { display: flex; height: 100vh; overflow: hidden; }
.content { flex: 1; min-width: 0; display: flex; flex-direction: column; overflow: hidden; }

/* ── Top bar ── */
.topbar {
    flex-shrink: 0;
    display: flex; align-items: center; justify-content: space-between;
    padding: 0 28px;
    height: 56px;
    background: #fff;
    border-bottom: 1px solid #e5e7eb;
    gap: 16px;
}
.topbar-left  { display: flex; align-items: center; gap: 10px; }
.topbar-title { font-size: 16px; font-weight: 700; color: #111827; }
.topbar-sub   { font-size: 12px; color: #9ca3af; }
.topbar-right { display: flex; align-items: center; gap: 10px; }
.btn-cancel {
    padding: 7px 18px; border: 1.5px solid #e5e7eb; border-radius: 7px;
    font-size: 13px; font-weight: 500; color: #6b7280; background: #fff;
    cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 6px;
    transition: background .15s, border-color .15s;
}
.btn-cancel:hover { background: #f9fafb; border-color: #d1d5db; }
.btn-save {
    padding: 7px 20px; border: none; border-radius: 7px;
    font-size: 13px; font-weight: 600; color: #fff;
    background: <?= $isEdit ? '#059669' : '#2563eb' ?>;
    cursor: pointer; display: inline-flex; align-items: center; gap: 7px;
    transition: background .15s; white-space: nowrap;
}
.btn-save:hover   { background: <?= $isEdit ? '#047857' : '#1d4ed8' ?>; }
.btn-save:disabled { background: #94a3b8; cursor: not-allowed; }

/* ── Scrollable form area ── */
.form-area { flex: 1; overflow-y: auto; padding: 24px 28px; }

/* ── Two-column layout: 70/30 ── */
.two-col {
    display: grid;
    grid-template-columns: 70fr 30fr;
    gap: 20px;
    align-items: start;
}

/* ── Single combined card ── */
.form-card {
    background: #fff;
    border-radius: 10px;
    border: 1px solid #e5e7eb;
    overflow: visible;
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 18px;
}

/* ── Section divider inside card ── */
.sec-divider {
    display: flex; align-items: center; gap: 8px;
    font-size: 11px; font-weight: 700; letter-spacing: .07em;
    text-transform: uppercase; color: #9ca3af;
    margin-bottom: 10px;
}
.sec-divider::after {
    content: ''; flex: 1; height: 1px; background: #f1f5f9;
}

/* ── Field rows ── */
.row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.row-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px; }
.row-4 { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 12px; }

/* ── Individual field ── */
.f { display: flex; flex-direction: column; gap: 4px; }
.f label {
    font-size: 11px; font-weight: 600; color: #6b7280;
    text-transform: uppercase; letter-spacing: .05em;
}
.f label .req { color: #ef4444; margin-left: 2px; }
.f input, .f select, .f textarea {
    width: 100%; padding: 7px 10px; font-size: 13px; color: #111827;
    border: 1.5px solid #e5e7eb; border-radius: 7px; outline: none;
    transition: border-color .15s, box-shadow .15s;
    background: #fff; font-family: inherit;
}
.f input:focus, .f select:focus, .f textarea:focus {
    border-color: #6366f1; box-shadow: 0 0 0 3px rgba(99,102,241,.1);
}
.f input.ro { background: #f0fdf4; border-color: #86efac; color: #166534; font-weight: 600; }
.f textarea  { resize: none; height: 72px; }

/* ── Autocomplete ── */
.ac-wrap { position: relative; }
.ac-drop {
    position: absolute; top: calc(100% + 3px); left: 0; right: 0; z-index: 300;
    background: #fff; border: 1.5px solid #e5e7eb; border-radius: 8px;
    box-shadow: 0 8px 24px rgba(0,0,0,.1); max-height: 160px; overflow-y: auto; display: none;
}
.ac-drop div { padding: 7px 12px; font-size: 13px; color: #374151; cursor: pointer; }
.ac-drop div:hover, .ac-drop div.hi { background: #eef2ff; color: #4f46e5; }

/* ── Upload zone ── */
.upload-zone {
    border: 2px dashed #e5e7eb; border-radius: 8px; padding: 14px;
    text-align: center; cursor: pointer; transition: border-color .15s, background .15s;
    font-size: 12px; color: #9ca3af;
}
.upload-zone:hover { border-color: #6366f1; background: #fafafe; }
.upload-zone input { display: none; }
.upload-name { color: #4f46e5; font-weight: 500; font-size: 12px; margin-top: 4px; }

/* ── Toast ── */
#toast {
    position: fixed; bottom: 20px; right: 24px; z-index: 9999;
    padding: 11px 18px; border-radius: 9px; font-size: 13px; font-weight: 500;
    box-shadow: 0 4px 20px rgba(0,0,0,.13); display: none; align-items: center; gap: 8px;
}
#toast.success { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; display: flex; }
#toast.error   { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; display: flex; }
</style>
</head>
<body>
<div id="toast"></div>

<div class="shell">

    <!-- Sidebar -->
    <?php include 'sidebar.php'; ?>

    <!-- Main content -->
    <div class="content">

        <!-- Top bar -->
        <div class="topbar">
            <div class="topbar-left">
                <a href="transaction_details.php" style="color:#6366f1;font-size:18px;text-decoration:none;line-height:1;">←</a>
                <div>
                    <div class="topbar-title"><?= $pageTitle ?></div>
                    <?php if ($isEdit): ?>
                    <div class="topbar-sub">ID #<?= $id ?></div>
                    <?php endif; ?>
                </div>
                <?php if ($isEdit): ?>
                <span style="background:#fef3c7;color:#92400e;font-size:11px;font-weight:600;padding:3px 10px;border-radius:99px;">Editing</span>
                <?php else: ?>
                <span style="background:#dbeafe;color:#1e40af;font-size:11px;font-weight:600;padding:3px 10px;border-radius:99px;">New</span>
                <?php endif; ?>
            </div>
            <div class="topbar-right">
                <span id="savingMsg" style="font-size:12px;color:#9ca3af;display:none;">Saving…</span>
                <a href="transaction_details.php" class="btn-cancel">Cancel</a>
                <button type="submit" form="txForm" class="btn-save" id="saveBtn">
                    <svg xmlns="http://www.w3.org/2000/svg" style="width:14px;height:14px" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5"
                              d="<?= $isEdit ? 'M5 13l4 4L19 7' : 'M12 4v16m8-8H4' ?>"/>
                    </svg>
                    <?= $isEdit ? 'Save Changes' : 'Add Transaction' ?>
                </button>
            </div>
        </div>

        <!-- Form area (scrollable) -->
        <div class="form-area">
        <form id="txForm" method="POST" enctype="multipart/form-data" autocomplete="off"
              action="<?= $isEdit ? 'update_transaction.php' : 'add_transaction.php' ?>">

            <?php if ($isEdit): ?><input type="hidden" name="id" value="<?= $id ?>"><?php endif; ?>
            <!-- Honeypots: fool Chrome autofill detection so it doesn't pre-fill any field -->
            <input type="text"     name="_trap_user"  style="display:none" tabindex="-1" aria-hidden="true">
            <input type="email"    name="_trap_email" style="display:none" tabindex="-1" aria-hidden="true">
            <input type="password" name="_trap_pass"  style="display:none" tabindex="-1" aria-hidden="true">

            <div class="two-col">

                <!-- ══ LEFT COLUMN (70%) — single combined card ══ -->
                <div class="form-card">

                    <!-- Reference -->
                    <div>
                        <div class="sec-divider">📋 Purchase Reference</div>
                        <div class="row-4">
                            <div class="f"><label>PO Date</label>
                                <input type="date" name="po_date" value="<?= v('po_date',$tx) ?>"></div>
                            <div class="f"><label>PO Number</label>
                                <input type="text" name="po_number" value="<?= v('po_number',$tx) ?>" placeholder="PO-2026-001"></div>
                            <div class="f"><label>INV Date <span class="req">*</span></label>
                                <input type="date" name="inv_date" value="<?= v('inv_date',$tx,$today) ?>" required></div>
                            <div class="f"><label>INV / PI / CN No <span class="req">*</span></label>
                                <input type="text" name="inv_number" value="<?= v('inv_number',$tx) ?>" placeholder="Invoice number" required></div>
                        </div>
                    </div>

                    <!-- Vendor & Item -->
                    <div>
                        <div class="sec-divider">🏪 Vendor & Item</div>
                        <div class="row-2">
                            <div class="f"><label>Vendor <span class="req">*</span></label>
                                <div class="ac-wrap">
                                    <input type="text" name="vendor" id="vendorInput" value="<?= v('vendor',$tx) ?>" autocomplete="off" placeholder="Search vendor…" required>
                                    <div class="ac-drop" id="vendorDrop"></div>
                                </div>
                            </div>
                            <div class="f"><label>Item Description <span class="req">*</span></label>
                                <div class="ac-wrap">
                                    <input type="text" name="item" id="itemInput" value="<?= v('item',$tx) ?>" autocomplete="off" placeholder="Search item…" required>
                                    <div class="ac-drop" id="itemDrop"></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Department -->
                    <div>
                        <div class="sec-divider">🏢 Department</div>
                        <div class="row-2">
                            <div class="f"><label>Department <span class="req">*</span></label>
                                <div class="ac-wrap">
                                    <input type="text" name="department" id="deptInput" value="<?= v('department',$tx) ?>" autocomplete="off" placeholder="Select department…" required>
                                    <div class="ac-drop" id="deptDrop"></div>
                                </div>
                            </div>
                            <div class="f"><label>Department Remarks</label>
                                <input type="text" name="department_remarks" value="<?= v('department_remarks',$tx) ?>" placeholder="Optional remarks">
                            </div>
                        </div>
                    </div>

                    <!-- Pricing -->
                    <div>
                        <div class="sec-divider">💰 Pricing</div>
                        <div class="row-4" style="margin-bottom:12px;">
                            <div class="f"><label>Unit <span class="req">*</span></label>
                                <input type="text" name="unit" id="unitInput" value="<?= v('unit',$tx) ?>" placeholder="0" required></div>
                            <div class="f"><label>UOM</label>
                                <input type="text" name="uom" value="<?= v('uom',$tx) ?>" placeholder="PCS"></div>
                            <div class="f"><label>Unit Price (RM) <span class="req">*</span></label>
                                <input type="text" name="price" id="priceInput" value="<?= v('price',$tx) ?>" placeholder="0.00" required></div>
                            <div class="f"><label>Price Remarks</label>
                                <input type="text" name="row_remarks" value="<?= v('row_remarks',$tx) ?>" placeholder="Optional"></div>
                        </div>
                        <div class="row-3">
                            <div class="f"><label>SST (%)</label>
                                <input type="text" name="sst" id="sstInput" value="<?= v('sst',$tx,'0') ?>" placeholder="0"></div>
                            <div class="f"><label>Total Price (RM)</label>
                                <input type="text" name="total_price" id="totalInput" value="<?= v('total_price',$tx) ?>" class="ro" readonly placeholder="Auto"></div>
                            <div class="f"><label>Min. Delivery (RM)</label>
                                <input type="text" name="min_amount_for_delivery" value="<?= v('min_amount_for_delivery',$tx) ?>" placeholder="0"></div>
                        </div>
                    </div>

                    <!-- Payment & Contact -->
                    <div>
                        <div class="sec-divider">💳 Payment & Contact</div>
                        <div class="row-3" style="margin-bottom:12px;">
                            <div class="f"><label>Contact</label>
                                <div class="ac-wrap">
                                    <input type="text" name="contact" id="contactInput" value="<?= v('contact',$tx) ?>" autocomplete="off" placeholder="Phone number">
                                    <div class="ac-drop" id="contactDrop"></div>
                                </div>
                            </div>
                            <div class="f"><label>Email</label>
                                <div class="ac-wrap">
                                    <input type="text" name="__eml__" id="emailInput" value="<?= v('email',$tx) ?>" autocomplete="new-password" placeholder="vendor@example.com" data-realname="email">
                                    <div class="ac-drop" id="emailDrop"></div>
                                </div>
                            </div>
                            <div class="f"><label>Person In Charge</label>
                                <input type="text" name="person_in_charge" value="<?= v('person_in_charge',$tx) ?>" placeholder="Staff name">
                            </div>
                        </div>
                        <div class="row-2">
                            <div class="f"><label>Terms <span class="req">*</span></label>
                                <select name="terms" required>
                                    <option value="Cash"            <?= sel('terms','Cash',$tx) ?>>Cash</option>
                                    <option value="Cash - Ms. Wong" <?= sel('terms','Cash - Ms. Wong',$tx) ?>>Cash — Ms. Wong</option>
                                    <option value="Terms"           <?= sel('terms','Terms',$tx) ?>>Terms</option>
                                </select>
                            </div>
                            <div class="f"><label>Payment Remarks</label>
                                <input type="text" name="payment_remarks" value="<?= v('payment_remarks',$tx) ?>" placeholder="Optional">
                            </div>
                        </div>
                    </div>

                </div><!-- /left column -->

                <!-- ══ RIGHT COLUMN (30%) — Remarks + Attachment ══ -->
                <div class="form-card">

                    <!-- Remarks (both modes) -->
                    <div>
                        <div class="sec-divider">📝 Remarks</div>
                        <div class="f">
                            <textarea name="remarks" placeholder="Any additional notes…" style="height:120px;"><?= v('remarks',$tx) ?></textarea>
                        </div>
                    </div>

                    <!-- File upload — add mode only -->
                    <?php if (!$isEdit): ?>
                    <div>
                        <div class="sec-divider">📎 Invoice Files</div>
                        <div class="f">
                            <div class="upload-zone" id="uploadZone">
                                <input type="file" name="invoice_file[]" id="invoiceFile"
                                       accept=".pdf,.jpg,.jpeg,.png" multiple style="display:none">
                                <div style="font-size:28px;margin-bottom:6px;">📄</div>
                                <div style="font-size:13px;color:#374151;font-weight:500;">Drop files to upload</div>
                                <div style="font-size:12px;color:#6366f1;margin-top:2px;">
                                    or <span id="browseLink" style="cursor:pointer;text-decoration:underline;">click to browse</span>
                                </div>
                                <div style="font-size:11px;color:#c4c9d4;margin-top:4px;">PDF, JPG, PNG · up to 10MB each</div>
                            </div>
                            <div id="fileList"></div>
                        </div>
                    </div>
                    <?php endif; ?>

                </div><!-- /right column -->

            </div><!-- /two-col -->
        </form>
        </div><!-- /form-area -->

    </div><!-- /content -->
</div><!-- /shell -->

<script>
// ══ AUTOCOMPLETE ══════════════════════════════════════════
const AC_DATA = {
    vendor:  <?= json_encode($vendors,     JSON_HEX_TAG) ?>,
    item:    <?= json_encode($items,       JSON_HEX_TAG) ?>,
    dept:    <?= json_encode($departments, JSON_HEX_TAG) ?>,
    contact: <?= json_encode($contacts,    JSON_HEX_TAG) ?>,
    email:   <?= json_encode($emails,      JSON_HEX_TAG) ?>,
};

const openDrops = new Set();

function closeDrop(drop) { drop.style.display = 'none'; openDrops.delete(drop); }

function initAC(inputId, dropId, dataKey) {
    const input = document.getElementById(inputId);
    const drop  = document.getElementById(dropId);
    const list  = AC_DATA[dataKey] || [];
    if (!input || !drop) return;
    let active = -1;

    function renderDrop(filtered) {
        drop.innerHTML = ''; active = -1;
        if (!filtered.length) { closeDrop(drop); return; }
        filtered.slice(0, 60).forEach(item => {
            const d = document.createElement('div');
            d.textContent = item;
            d.addEventListener('mousedown', e => {
                e.preventDefault();
                input.value = item;
                closeDrop(drop);
                moveToNext(input);
            });
            drop.appendChild(d);
        });
        drop.style.display = 'block';
        openDrops.add(drop);
    }

    function openDrop() {
        const q = input.value.toLowerCase();
        renderDrop(q ? list.filter(x => x.toLowerCase().includes(q)) : list.slice(0, 20));
    }

    input.addEventListener('input',  openDrop);
    input.addEventListener('blur',   () => setTimeout(() => closeDrop(drop), 120));
    document.addEventListener('click', e => {
        if (!input.contains(e.target) && !drop.contains(e.target)) closeDrop(drop);
    });

    input.addEventListener('keydown', e => {
        const items = Array.from(drop.querySelectorAll('div'));
        const isOpen = drop.style.display === 'block';
        if (e.key === 'Escape') { closeDrop(drop); return; }
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            if (!isOpen) { if (input.value) openDrop(); return; }
            active = Math.min(active + 1, items.length - 1);
            items.forEach((d,i) => d.classList.toggle('hi', i === active));
            items[active]?.scrollIntoView({ block:'nearest' });
            return;
        }
        if (e.key === 'ArrowUp') {
            e.preventDefault();
            active = Math.max(active - 1, 0);
            items.forEach((d,i) => d.classList.toggle('hi', i === active));
            items[active]?.scrollIntoView({ block:'nearest' });
            return;
        }
        if (e.key === 'Enter') {
            e.preventDefault();
            if (isOpen) {
                const pick = active >= 0 ? items[active] : items[0];
                if (pick) input.value = pick.textContent;
                closeDrop(drop);
            }
            moveToNext(input);
        }
        if (e.key === 'Tab') closeDrop(drop);
    });
}

function getAllFields() {
    return Array.from(document.querySelectorAll(
        '#txForm input:not([type=hidden]):not([readonly]):not([type=file]), #txForm select, #txForm textarea'
    )).filter(el => !el.disabled && el.offsetParent !== null);
}
function moveToNext(current) {
    const els = getAllFields();
    const i = els.indexOf(current);
    if (i >= 0 && i < els.length - 1) {
        const next = els[i + 1];
        next.focus();
        // Select all existing text so user can immediately overwrite
        if (next.select) next.select();
    }
}

// Suppress browser autofill — autocomplete="new-password" is the only value
// Chrome reliably honours even on non-password fields
getAllFields().forEach(el => {
    el.setAttribute('autocomplete', 'new-password');
    el.setAttribute('autocorrect', 'off');
    el.setAttribute('autocapitalize', 'off');
    el.setAttribute('spellcheck', 'false');
});

// Select-all only when navigating via keyboard (Enter/Tab), not mouse click
let _mouseActive = false;
document.addEventListener('mousedown', () => { _mouseActive = true; });
document.addEventListener('keydown',   () => { _mouseActive = false; });

getAllFields().forEach(el => {
    el.addEventListener('focus', function() {
        if (!_mouseActive && this.select && this.type !== 'date') {
            const self = this;
            setTimeout(() => self.select(), 0);
        }
    });
});


initAC('vendorInput',  'vendorDrop',  'vendor');
initAC('itemInput',    'itemDrop',    'item');
initAC('deptInput',    'deptDrop',    'dept');
initAC('contactInput', 'contactDrop', 'contact');
initAC('emailInput',   'emailDrop',   'email');

// ══ PRICE CALCULATION ════════════════════════════════════
function parseNum(v) { return parseFloat(String(v).replace(/,/g,'')) || 0; }
function calcTotal() {
    const unit  = parseNum(document.getElementById('unitInput').value);
    const price = parseNum(document.getElementById('priceInput').value);
    const sst   = parseNum(document.getElementById('sstInput').value);
    const sub   = unit * price;
    const total = sub * (1 + sst / 100);
    document.getElementById('totalInput').value = total.toFixed(2);
}
['unitInput','priceInput','sstInput'].forEach(id => {
    const el = document.getElementById(id);
    if (!el) return;
    el.addEventListener('input', calcTotal);
    el.addEventListener('keydown', e => {
        if (!['Backspace','Delete','ArrowLeft','ArrowRight','Tab','.'].includes(e.key) && !/[0-9]/.test(e.key))
            e.preventDefault();
    });
});

// ══ UPLOAD (add mode only) ════════════════════════════════
const zone       = document.getElementById('uploadZone');
const browseLink = document.getElementById('browseLink');
const fileInput  = document.getElementById('invoiceFile');
const fileList   = document.getElementById('fileList');

if (zone && fileInput) {
    // Accumulate files across multiple picks/drops using DataTransfer
    const dt = new DataTransfer();

    function formatSize(b) {
        if (b < 1024) return b + ' B';
        if (b < 1024*1024) return Math.round(b/1024) + 'KB';
        return (b/1024/1024).toFixed(1) + 'MB';
    }

    function addFiles(incoming) {
        const allowed = ['pdf','jpg','jpeg','png'];
        Array.from(incoming).forEach(f => {
            const ext = f.name.split('.').pop().toLowerCase();
            if (!allowed.includes(ext)) return;
            // Skip duplicates by name+size
            const already = Array.from(dt.files).some(x => x.name === f.name && x.size === f.size);
            if (!already) dt.items.add(f);
        });
        // Sync back to input so the form submits them
        fileInput.files = dt.files;
        renderList();
    }

    function removeFile(idx) {
        const remaining = Array.from(dt.files).filter((_, i) => i !== idx);
        dt.clearData();
        // DataTransfer.clearData doesn't clear files — recreate
        const dt2 = new DataTransfer();
        remaining.forEach(f => dt2.items.add(f));
        fileInput.files = dt2.files;
        // Rebuild dt to match
        dt.items.clear?.();
        remaining.forEach(f => dt.items.add(f));
        renderList();
    }

    function renderList() {
        if (!dt.files.length) { fileList.innerHTML = ''; return; }
        fileList.innerHTML = Array.from(dt.files).map((f, i) => {
            const ext = f.name.split('.').pop().toUpperCase();
            return `<div style="display:flex;align-items:center;gap:10px;background:#f0f4ff;border:1px solid #e0e7ff;border-radius:8px;padding:9px 12px;margin-top:8px;">
                <div style="background:#c7d2fe;color:#3730a3;font-size:10px;font-weight:700;padding:3px 7px;border-radius:5px;flex-shrink:0;">${ext}</div>
                <div style="flex:1;min-width:0;">
                    <div style="font-size:13px;font-weight:600;color:#1e1b4b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${f.name}</div>
                    <div style="font-size:11px;color:#6b7280;">${formatSize(f.size)}</div>
                </div>
                <button type="button" onclick="removeFile(${i})"
                    style="background:none;border:none;cursor:pointer;color:#9ca3af;font-size:16px;line-height:1;padding:0 2px;"
                    title="Remove">×</button>
            </div>`;
        }).join('');
    }

    // Expose removeFile globally so inline onclick works
    window.removeFile = removeFile;

    // Browse click — opens file picker without resetting existing files
    zone.addEventListener('click', e => {
        if (e.target === browseLink || e.target === zone ||
            e.target.closest('#uploadZone') && !e.target.closest('#fileList')) {
            // Reset input value so change fires even if same file re-picked
            fileInput.value = '';
            fileInput.click();
        }
    });
    browseLink?.addEventListener('click', e => { e.stopPropagation(); fileInput.value = ''; fileInput.click(); });

    fileInput.addEventListener('change', () => { if (fileInput.files.length) addFiles(fileInput.files); });

    zone.addEventListener('dragover',  e => { e.preventDefault(); zone.style.borderColor='#6366f1'; zone.style.background='#fafafe'; });
    zone.addEventListener('dragleave', () => { zone.style.borderColor=''; zone.style.background=''; });
    zone.addEventListener('drop', e => {
        e.preventDefault();
        zone.style.borderColor = '';
        zone.style.background  = '';
        if (e.dataTransfer.files.length) addFiles(e.dataTransfer.files);
    });
}

// ══ SUBMIT ════════════════════════════════════════════════
const toast   = document.getElementById('toast');
const saveBtn = document.getElementById('saveBtn');

function showToast(msg, type) {
    toast.textContent = msg;
    toast.className   = type;
    setTimeout(() => { toast.className = ''; toast.style.display = 'none'; }, 3500);
}

document.getElementById('txForm').addEventListener('submit', function(e) {
    e.preventDefault();
    // Restore any disguised field names so the server receives the correct POST keys
    document.querySelectorAll('[data-realname]').forEach(el => { el.name = el.dataset.realname; });
    const deptVal = document.getElementById('deptInput').value.trim();
    if (AC_DATA.dept.length && !AC_DATA.dept.includes(deptVal)) {
        showToast('⚠ Please select a valid department from the list.', 'error');
        document.getElementById('deptInput').focus();
        return;
    }
    saveBtn.disabled = true;
    document.getElementById('savingMsg').style.display = 'inline';
    fetch(this.action, { method:'POST', body: new FormData(this) })
        .then(r => r.text())
        .then(resp => {
            const ok = resp.includes('success') || resp === 'success';
            if (ok) {
                showToast('<?= $isEdit ? "✓ Transaction updated!" : "✓ Transaction added!" ?>', 'success');
                setTimeout(() => window.location.href = 'transaction_details.php', 1200);
            } else throw new Error(resp);
        })
        .catch(() => {
            showToast('❌ Failed to save. Please try again.', 'error');
            saveBtn.disabled = false;
            document.getElementById('savingMsg').style.display = 'none';
        });
});

// ══ ENTER → next field, never submit ═════════════════════
document.getElementById('txForm').addEventListener('keydown', function(e) {
    if (e.key !== 'Enter') return;
    if (e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT') return;
    e.preventDefault();
    for (const d of openDrops) if (d.style.display === 'block') return;
    moveToNext(e.target);
}, true);
</script>
</body>
</html>
