

<?php $__env->startSection('page-title', 'Add Expenses'); ?>
<?php $__env->startSection('page-subtitle', 'Log your expenses in a clean sheet layout'); ?>

<?php $__env->startSection('content'); ?>


<div class="mb-6 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
    <div>
        <h2 class="text-xl md:text-2xl font-extrabold tracking-tight">Add Expenses</h2>
        <p class="text-sm text-[color:var(--emp-muted)] mt-1">
            Use this sheet to enter your expenses (one row = one expense).
        </p>
        <p class="text-xs text-[color:var(--emp-muted)] mt-1">
            Submitting to
            <span class="font-semibold text-[color:var(--emp-text)]">
                <?php echo e($activeSession->name ?? '-'); ?>

            </span>
            (<?php echo e(optional($activeSession)->start_date?->format('d M Y') ?? ''); ?>

            – <?php echo e(optional($activeSession)->end_date?->format('d M Y') ?? ''); ?>).
        </p>
    </div>

    <div class="flex flex-col items-stretch gap-2 md:items-end">
        <a href="<?php echo e(route('employee.expense-groups.index')); ?>"
           class="inline-flex items-center justify-center px-3 py-2 rounded-xl border border-[color:var(--emp-border)] bg-[color:var(--emp-surface)] text-[11px] md:text-xs font-semibold text-[color:var(--emp-text)] hover:bg-slate-50 transition">
            Manage Expense Groups
        </a>

        <div class="text-xs md:text-sm text-[color:var(--emp-muted)] bg-[color:var(--emp-surface)] border border-[color:var(--emp-border)] rounded-2xl px-4 py-3 max-w-md">
            <div class="font-semibold text-[11px] uppercase tracking-[0.16em] mb-1">Instructions</div>
            <ul class="space-y-1.5">
                <li>• One row = one expense.</li>
                <li>• Choose a <span class="font-semibold">Group</span> for better reporting.</li>
                <li>• Click <span class="font-semibold">Attached</span> to add files (PNG / JPG / PDF). Max 5MB each.</li>
                <li>• Amount is in ₹ (rupees).</li>
            </ul>
        </div>
    </div>
</div>


<div class="rounded-3xl bg-[color:var(--emp-surface)] border border-[color:var(--emp-border)] shadow-sm p-5 mb-6">
    
    <div class="mb-4 flex flex-col md:flex-row md:items-center md:justify-between gap-3">
        <div>
            <h3 class="text-lg md:text-xl font-semibold">Expense Entries</h3>
            <p class="text-xs md:text-sm text-[color:var(--emp-muted)] mt-1">
                Keep your entries clear and complete. You can add multiple rows in one go.
            </p>
        </div>
        <button id="addRowBtn"
                type="button"
                class="inline-flex items-center gap-1 px-4 py-2 rounded-xl bg-[color:var(--emp-brand)] text-white text-sm font-semibold hover:bg-blue-700 transition shadow-sm">
            + Add Row
        </button>
    </div>

    
    <div id="cardBannerContainer" class="mb-4 hidden"></div>

    
    <form id="expenseForm" method="POST" action="<?php echo e(route('employee.expenses.store')); ?>" enctype="multipart/form-data">
        <?php echo csrf_field(); ?>
        <input type="hidden" name="save_mode" id="saveModeInput" value="final">
        <input type="hidden" name="financial_session_id" value="<?php echo e($activeSession->id ?? ''); ?>">

        
        <div class="rounded-2xl border border-[color:var(--emp-border)] bg-white overflow-hidden">
            <div class="max-h-[420px] overflow-y-auto">
                <table class="w-full text-[13px] table-fixed responsive-table">
                    <thead class="sticky top-0 z-10 bg-slate-50 text-[11px] uppercase tracking-wide text-[color:var(--emp-muted)]">
                        <tr>
                            <th class="p-2 md:p-3 text-left font-semibold w-[7rem]">Date</th>
                            <th class="p-2 md:p-3 text-left font-semibold w-[8rem]">Group</th>
                            <th class="p-2 md:p-3 text-left font-semibold w-[10rem]">Party Name</th>
                            <th class="p-2 md:p-3 text-left font-semibold">Purpose</th>
                            <th class="p-2 md:p-3 text-right font-semibold w-[7rem]">Amount (₹)</th>
                            <th class="p-2 md:p-3 text-left font-semibold w-[14rem]">Attached</th>
                            <th class="p-2 md:p-3 text-center font-semibold w-[3rem]"></th>
                        </tr>
                    </thead>
                    <tbody id="expense-rows" class="divide-y divide-[color:var(--emp-border)]">
                        
                    </tbody>
                </table>
            </div>

            
            <div class="border-t border-[color:var(--emp-border)] bg-slate-50">
                <div class="flex items-center justify-end gap-3 p-3 text-sm">
                    <span class="text-[color:var(--emp-muted)] font-semibold">
                        Total:
                    </span>
                    <span id="totalAmountCell" class="font-extrabold text-[color:var(--emp-brand)] text-base">
                        ₹ 0.00
                    </span>
                </div>
            </div>
        </div>

        
        <div class="mt-4 flex flex-col md:flex-row md:items-center md:justify-between gap-3">
            <div class="text-[11px] md:text-xs text-[color:var(--emp-muted)]">
                • <span class="font-semibold">Save Draft</span> saves as draft. • <span class="font-semibold">Submit Expenses</span> submits final entries for admin review.
            </div>
            <div class="flex gap-2">
                <button type="button"
                        id="saveDraftBtn"
                        class="px-4 py-2.5 rounded-xl bg-[color:var(--emp-bg-soft)] text-[color:var(--emp-text)] text-xs md:text-sm font-semibold border border-[color:var(--emp-border)] hover:bg-slate-100 transition">
                    Save Draft
                </button>
                <button type="submit"
                        class="px-4 py-2.5 rounded-xl bg-[color:var(--emp-brand)] text-white text-xs md:text-sm font-semibold hover:bg-blue-700 transition shadow-sm"
                        id="submitBtn">
                    Submit Expenses
                </button>
            </div>
        </div>
    </form>
</div>


<div class="rounded-3xl bg-[color:var(--emp-surface)] border border-[color:var(--emp-border)] shadow-sm p-5">
    <h4 class="text-sm font-semibold mb-2">Tips</h4>
    <ul class="text-xs text-[color:var(--emp-muted)] space-y-1.5">
        <li>• Click <strong>Attached</strong> to pick files. You may select multiple files per row.</li>
        <li>• Files allowed: PNG, JPG, PDF. Max 5MB each.</li>
        <li>• Admin will review and approve/reject expenses.</li>
    </ul>
</div>


<template id="expense-row-tpl">
    <tr data-row-type="main">
        <td data-label="Date" class="p-2 md:p-3 align-top">
            <div class="md:hidden mobile-label">Date</div>
            <div class="field-wrap">
                <input type="date" name="__NAME__[expense_date]"
                       class="w-full border border-[color:var(--emp-border)] rounded-xl px-2.5 py-1.5 text-[13px] focus:outline-none focus:ring-2 focus:ring-[color:var(--emp-brand)]">
            </div>
        </td>

        <td data-label="Group" class="p-2 md:p-3 align-top">
            <div class="md:hidden mobile-label">Group</div>
            <div class="field-wrap">
                <select name="__NAME__[expense_group_id]"
                        class="w-full border border-[color:var(--emp-border)] rounded-xl px-2.5 py-1.5 text-[13px] bg-white focus:outline-none focus:ring-2 focus:ring-[color:var(--emp-brand)]">
                    <option value="">Select group</option>
                    <?php $__currentLoopData = $expenseGroups; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $group): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($group->id); ?>"><?php echo e($group->name); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
            </div>
        </td>

        <td data-label="Party Name" class="p-2 md:p-3 align-top">
            <div class="md:hidden mobile-label">Party Name</div>
            <div class="field-wrap">
                <input type="text" name="__NAME__[party_name]" placeholder="Vendor / Party"
                       class="w-full border border-[color:var(--emp-border)] rounded-xl px-2.5 py-1.5 text-[13px]">
            </div>
        </td>

        <td data-label="Purpose" class="p-2 md:p-3 align-top">
            <div class="md:hidden mobile-label">Purpose</div>
            <div class="field-wrap">
                <input type="text" name="__NAME__[purpose]" placeholder="Purpose of expense"
                       class="w-full border border-[color:var(--emp-border)] rounded-xl px-2.5 py-1.5 text-[13px]">
            </div>
        </td>

        <td data-label="Amount" class="p-2 md:p-3 text-right align-top">
            <div class="md:hidden mobile-label">Amount (₹)</div>
            <div class="field-wrap">
                <input type="number" step="0.01" min="0" name="__NAME__[amount]" data-field="amount" placeholder="0.00"
                       class="w-full text-right border border-[color:var(--emp-border)] rounded-xl px-2.5 py-1.5 text-[13px]" oninput="recalcTotal()">
            </div>
        </td>

        <td data-label="Attached" class="p-2 md:p-3 align-top">
            <div class="md:hidden mobile-label">Attached</div>
            <div class="field-wrap">
                <div class="flex items-center gap-3">
                    <button type="button" class="attached-btn px-3 py-1.5 rounded-xl bg-white border text-sm">Attached (<span class="file-count">0</span>)</button>
                    <div class="text-xs text-[color:var(--emp-muted)] file-summary truncate">No files</div>
                </div>
                <input type="file" name="__NAME__[proof][]" accept=".png,.jpg,.jpeg,.pdf" multiple class="hidden file-input">
            </div>
        </td>

        <td data-label="Remove" class="p-2 md:p-3 align-top text-center">
            <div class="md:hidden mobile-label">Remove</div>
            <div class="field-wrap">
                <button type="button" class="text-[11px] text-rose-500 hover:text-rose-700 remove-row-btn">✕</button>
            </div>
        </td>

        <!-- hidden placeholders -->
        <input type="hidden" name="__NAME__[return_amount]" data-field="return_amount">
        <input type="hidden" name="__NAME__[return_remarks]" data-field="return_remarks">
    </tr>
</template>


<style>
    /* Ensure consistent sizing of inputs/selects across browsers */
    .responsive-table input[type="text"],
    .responsive-table input[type="number"],
    .responsive-table input[type="date"],
    .responsive-table select,
    .responsive-table textarea {
        box-sizing: border-box;
        height: 44px;                /* consistent height */
        padding-top: 0.35rem;
        padding-bottom: 0.35rem;
        padding-left: 0.6rem;
        padding-right: 0.6rem;
        line-height: 1.2;
    }
    .responsive-table textarea { height: 44px; min-height:44px; padding-top:0.35rem; padding-bottom:0.35rem; }

    /* Checkbox small remains small */
    .responsive-table input[type="checkbox"] { height: auto; width: auto; }

    /* Responsive table: on small screens convert rows to labelled blocks */
    @media (max-width: 767px) {
        .responsive-table thead { display: none; }
        .responsive-table, .responsive-table tbody, .responsive-table tr, .responsive-table td {
            display: block;
            width: 100%;
        }
        .responsive-table tr {
            margin-bottom: 0.75rem;
            padding: 0.75rem;
            border-radius: 0.75rem;
            background: white;
            box-shadow: 0 1px 0 rgba(0,0,0,0.03);
        }
        .responsive-table td {
            padding: 0.35rem 0;
            display: block;
            gap: 0.5rem;
            border-bottom: 0;
        }

        /* Mobile-only label (inserted above input) */
        .mobile-label { display: block; font-size: 11px; color: rgba(30,41,59,0.6); font-weight: 600; margin-bottom: 0.35rem; }
        .responsive-table td .field-wrap { display: block; width: 100%; }
        .responsive-table td .field-wrap input,
        .responsive-table td .field-wrap select,
        .responsive-table td .field-wrap textarea { width: 100%; }

        .responsive-table td.actions { display: flex; justify-content: flex-end; }
    }

    /* Card banner helper */
    .card-banner-success {
        background-color: #ecfdf5;
        border: 1px solid #bbf7d0;
        color: #065f46;
        padding: 0.6rem 0.9rem;
        border-radius: 0.75rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        font-weight: 600;
    }
    .card-banner-error {
        background-color: #fff1f2;
        border: 1px solid #fecaca;
        color: #9f1239;
        padding: 0.6rem 0.9rem;
        border-radius: 0.75rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        font-weight: 600;
    }

    /* GLOBAL FLOATING BANNER (mobile-friendly toast) */
    #globalBanner {
        position: fixed;
        left: 50%;
        transform: translateX(-50%) translateY(-12px);
        top: 1rem;
        z-index: 80;
        width: calc(100% - 2rem);
        max-width: 640px;
        pointer-events: none;
        transition: transform .22s ease, opacity .22s ease;
        opacity: 0;
    }
    #globalBanner.show {
        transform: translateX(-50%) translateY(0);
        opacity: 1;
    }
    #globalBannerInner {
        pointer-events: auto;
        border-radius: 1rem;
        padding: 0.6rem 0.9rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        box-shadow: 0 10px 30px rgba(2,6,23,0.12);
    }
    #globalBannerInner .gb-message { flex: 1; font-weight: 600; font-size: 14px; }
    #globalBannerInner .gb-close { font-size: 13px; margin-left: 8px; }

    @media (min-width: 768px) {
        #globalBanner { top: 1.5rem; width: auto; left: auto; right: 1.5rem; transform: none; }
        #globalBannerInner { max-width: 360px; }
    }
</style>


<div id="globalBanner" class="z-60" role="status" aria-live="polite" aria-hidden="true">
    <div id="globalBannerInner" class="mx-auto max-w-3xl rounded-2xl px-4 py-3 shadow-lg text-sm font-medium flex items-start gap-3">
        <!-- dynamic content inserted here by JS -->
    </div>
</div>

<script>
    // config
    const ALLOWED = ['image/png','image/jpeg','application/pdf'];
    const MAX_BYTES = 5 * 1024 * 1024; // 5MB

    let rowCounter = 0;
    const rowsContainer = document.getElementById('expense-rows');
    const tpl = document.getElementById('expense-row-tpl').content;
    const totalAmountCell = document.getElementById('totalAmountCell');
    const form = document.getElementById('expenseForm');
    const submitBtn = document.getElementById('submitBtn');
    const saveDraftBtn = document.getElementById('saveDraftBtn');
    const saveModeInput = document.getElementById('saveModeInput');
    const cardBannerContainer = document.getElementById('cardBannerContainer');

    // Global banner elements
    const globalBanner = document.getElementById('globalBanner');
    const globalBannerInner = document.getElementById('globalBannerInner');
    let bannerTimeout = null;

    function formatCurrency(v) {
        const n = Number(v) || 0;
        return '₹ ' + n.toFixed(2);
    }

    function recalcTotal() {
        let total = 0;
        document.querySelectorAll('input[data-field="amount"]').forEach(inp => {
            const val = parseFloat(inp.value || '0');
            if (!isNaN(val)) total += val;
        });
        totalAmountCell.textContent = formatCurrency(total);
    }

    // Show in-card banner (desktop) and also show global mobile toast when on phone
    function showCardBanner(message, type = 'success', persist = false) {
        // in-card
        cardBannerContainer.innerHTML = '';
        cardBannerContainer.classList.remove('hidden');

        const div = document.createElement('div');
        div.className = (type === 'error') ? 'card-banner-error' : 'card-banner-success';
        div.setAttribute('role', 'status');
        div.innerHTML = `
            <div class="flex items-center gap-2">
                <div aria-hidden="true">
                    ${ type === 'error'
                        ? '<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>'
                        : '<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" /></svg>'
                    }
                </div>
                <div>${message}</div>
            </div>
            <div class="ml-auto">
                <button id="dismissCardBanner" class="text-xs underline">Dismiss</button>
            </div>
        `;
        cardBannerContainer.appendChild(div);

        document.getElementById('dismissCardBanner')?.addEventListener('click', hideCardBanner);

        if (!persist) {
            setTimeout(hideCardBanner, 5000);
        }

        // show global toast on small screens for visibility
        try {
            if (window.innerWidth < 768) {
                showGlobalBanner(message, type, persist);
            }
        } catch (e) {
            // ignore
        }
    }

    function hideCardBanner() {
        cardBannerContainer.classList.add('hidden');
        cardBannerContainer.innerHTML = '';
    }

    // Global floating banner (mobile toast)
    function showGlobalBanner(message, type = 'success', persist = false) {
        if (bannerTimeout) {
            clearTimeout(bannerTimeout);
            bannerTimeout = null;
        }

        globalBanner.setAttribute('aria-hidden', 'false');
        globalBannerInner.innerHTML = `
            <div class="flex items-center gap-3">
                <div class="flex items-center" aria-hidden="true">
                    ${ type === 'error'
                        ? '<svg class="h-5 w-5 text-rose-700" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>'
                        : '<svg class="h-5 w-5 text-emerald-700" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" /></svg>'
                    }
                </div>
                <div class="gb-message">${message}</div>
                <button id="closeGlobalBanner" class="gb-close underline text-sm">Dismiss</button>
            </div>
        `;

        if (type === 'error') {
            globalBannerInner.style.backgroundColor = '#fff1f2';
            globalBannerInner.style.border = '1px solid #fecaca';
            globalBannerInner.style.color = '#9f1239';
        } else {
            globalBannerInner.style.backgroundColor = '#ecfdf5';
            globalBannerInner.style.border = '1px solid #bbf7d0';
            globalBannerInner.style.color = '#065f46';
        }

        globalBanner.classList.add('show');

        if (!persist) {
            bannerTimeout = setTimeout(() => {
                hideGlobalBanner();
            }, 5000);
        }

        document.getElementById('closeGlobalBanner')?.addEventListener('click', hideGlobalBanner);

        // allow quick tap outside to dismiss on touch devices
        globalBanner.addEventListener('touchstart', _touchDismiss, { once: true, passive: true });
    }

    function _touchDismiss() {
        hideGlobalBanner();
    }

    function hideGlobalBanner() {
        globalBanner.classList.remove('show');
        globalBanner.setAttribute('aria-hidden', 'true');
        if (bannerTimeout) {
            clearTimeout(bannerTimeout);
            bannerTimeout = null;
        }
    }

    // create row logic
    function createRow() {
        rowCounter++;
        const node = tpl.cloneNode(true);
        node.querySelectorAll('[name]').forEach(el => {
            const name = el.getAttribute('name');
            if (!name) return;
            el.setAttribute('name', name.replace('__NAME__', `rows[${rowCounter}]`));
        });

        const tr = node.querySelector('tr');
        tr.setAttribute('data-row-id', 'row-' + rowCounter);

        // amount
        const amountInput = tr.querySelector('input[data-field="amount"]');
        amountInput?.addEventListener('input', recalcTotal);

        // attached button & file input
        const attachedBtn = tr.querySelector('.attached-btn');
        const fileInput = tr.querySelector('.file-input');
        const fileCount = tr.querySelector('.file-count');
        const fileSummary = tr.querySelector('.file-summary');

        attachedBtn.addEventListener('click', () => fileInput.click());

        fileInput.addEventListener('change', () => {
            const files = Array.from(fileInput.files || []);
            if (files.length === 0) {
                fileCount.textContent = '0';
                fileSummary.textContent = 'No files';
                return;
            }

            for (const f of files) {
                const ext = (f.name || '').split('.').pop()?.toLowerCase() || '';
                const mimeOk = ALLOWED.includes(f.type);
                const extOk = ['png','jpg','jpeg','pdf'].includes(ext);
                if ((!mimeOk && !extOk) || f.size > MAX_BYTES) {
                    showCardBanner('One or more files are invalid. Allowed: PNG, JPG, PDF. Max 5MB each.', 'error', true);
                    fileInput.value = '';
                    fileCount.textContent = '0';
                    fileSummary.textContent = 'No files';
                    return;
                }
            }

            fileCount.textContent = files.length;
            fileSummary.textContent = files.map(f => f.name).join(', ');
        });

        // remove row
        tr.querySelector('.remove-row-btn').addEventListener('click', () => {
            const rowId = tr.getAttribute('data-row-id');
            const returnRow = document.querySelector(`tr[data-return-row-for="${rowId}"]`);
            if (returnRow) returnRow.remove();

            tr.remove();
            recalcTotal();
        });

        rowsContainer.appendChild(node);
    }

    // Add initial row
    createRow();

    // Add row button
    document.getElementById('addRowBtn').addEventListener('click', () => {
        createRow();
        // scroll last row into view on small screens
        setTimeout(() => {
            const last = rowsContainer.lastElementChild;
            if (last) last.scrollIntoView({ behavior: 'smooth', block: 'end' });
        }, 80);
    });

    // Save Draft click -> set mode + submit
    saveDraftBtn.addEventListener('click', () => {
        saveModeInput.value = 'draft';
        form.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }));
    });

    // AJAX submit
    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        const currentMode = saveModeInput.value || 'final';

        submitBtn.disabled = true;
        saveDraftBtn.disabled = true;
        submitBtn.textContent = currentMode === 'final' ? 'Submitting...' : 'Submitting Draft...';

        // clear previous error highlights
        form.querySelectorAll('.border-red-400').forEach(el => el.classList.remove('border-red-400'));
        hideCardBanner();
        hideGlobalBanner();

        const formData = new FormData(form);

        try {
            const response = await fetch(form.action, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Accept': 'application/json'
                },
                body: formData
            });

            if (response.status === 422) {
                const data = await response.json();
                if (data.errors) {
                    // highlight inputs (best-effort)
                    Object.keys(data.errors).forEach(key => {
                        const el = form.querySelector(`[name="${key}"]`) || form.querySelector(`[name="${key.replace(/\./g, '][').replace('rows[','rows[')}]"]`);
                        if (el) el.classList.add('border-red-400');
                    });
                    showCardBanner('Please fix the highlighted fields.', 'error', true);
                } else {
                    showCardBanner('Validation error.', 'error', true);
                }
            } else if (!response.ok) {
                const data = await response.json().catch(() => ({}));
                showCardBanner(data.message || 'Something went wrong.', 'error', true);
            } else {
                const data = await response.json();
                showCardBanner(data.message || (currentMode === 'final' ? 'Expenses submitted.' : 'Draft saved.'), 'success', true);

                if (currentMode === 'final') {
                    rowsContainer.innerHTML = '';
                    rowCounter = 0;
                    recalcTotal();
                    createRow();
                }
            }
        } catch (err) {
            console.error(err);
            showCardBanner('Network error. Please try again.', 'error', true);
        } finally {
            saveModeInput.value = 'final';
            submitBtn.disabled = false;
            saveDraftBtn.disabled = false;
            submitBtn.textContent = 'Submit Expenses';
        }
    });

    // Expose recalcTotal for inline use (template uses oninput)
    window.recalcTotal = recalcTotal;
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.employee', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH E:\softwares\26dec25Backup\resources\views/employee/expenses/create.blade.php ENDPATH**/ ?>