

<?php $__env->startSection('page-title', 'Add Conveyance'); ?>
<?php $__env->startSection('page-subtitle', 'Log your daily travel 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 Conveyance</h2>
            <p class="text-sm text-[color:var(--emp-muted)] mt-1">
                Use this sheet to enter your daily conveyance trips.
            </p>
            <p class="text-xs text-[color:var(--emp-muted)] mt-1">
                You are entering conveyance for
                <span class="font-semibold text-[color:var(--emp-text)]"><?php echo e($targetMonthLabel); ?></span>
                (<?php echo e($monthStart->format('d M Y')); ?> – <?php echo e($monthEnd->format('d M Y')); ?>).
                Submission allowed till <?php echo e($cutoffDate->format('d M Y')); ?>.
            </p>
        </div>

        <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 trip in <?php echo e($targetMonthLabel); ?>.</li>
                <li>• Use <span class="font-semibold">Return</span> when you travel back to same location.</li>
                <li>• Amount is in ₹ (rupees).</li>
            </ul>
        </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">Daily Conveyance 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">
            <!-- Filled by JS (showCardBanner) -->
        </div>

        
        <form id="conveyanceForm" method="POST" action="<?php echo e(route('employee.conveyance.store')); ?>">
            <?php echo csrf_field(); ?>
            
            <input type="hidden" name="save_mode" id="saveModeInput" value="final">

            
            <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]">From</th>
                                <th class="p-2 md:p-3 text-left font-semibold w-[8rem]">To</th>
                                <th class="p-2 md:p-3 text-left font-semibold w-[10rem]">Client</th>
                                <th class="p-2 md:p-3 text-left font-semibold w-[8rem]">Mode</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">Remarks</th>
                                <th class="p-2 md:p-3 text-center font-semibold w-[4rem]">Return</th>
                                <th class="p-2 md:p-3 text-center font-semibold w-[3rem]"></th>
                            </tr>
                        </thead>
                        <tbody id="conv-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 (including return trips):
                        </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> will save as draft (not final).
                    • <span class="font-semibold">Submit Conveyance</span> will submit final entries.
                </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 Conveyance
                    </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">Clients & Rules</h4>
        <ul class="text-xs text-[color:var(--emp-muted)] space-y-1.5">
            <li>• Client list below is coming from Admin (live data).</li>
            <li>• “Request new client” just shows a message for now – workflow later.</li>
        </ul>

        <div id="clientRequestBox"
            class="mt-4 p-3 rounded-2xl bg-[color:var(--emp-bg-soft)] border border-[color:var(--emp-border)] hidden">
            <div class="flex items-center justify-between mb-2">
                <div class="text-xs font-semibold text-[color:var(--emp-text)]">Request new client</div>
                <button type="button" id="closeClientRequest"
                    class="text-[11px] text-[color:var(--emp-muted)] hover:text-[color:var(--emp-text)]">
                    ✕
                </button>
            </div>
            <div class="space-y-2">
                <div>
                    <label class="text-[11px] font-medium block mb-1">Client Name</label>
                    <input id="reqClientName"
                        class="w-full border border-[color:var(--emp-border)] rounded-xl px-3 py-2 text-xs focus:outline-none focus:ring-1 focus:ring-[color:var(--emp-brand)]"
                        placeholder="Proposed client name">
                </div>
                <div>
                    <label class="text-[11px] font-medium block mb-1">Details / Reason</label>
                    <textarea id="reqClientNotes" rows="2"
                        class="w-full border border-[color:var(--emp-border)] rounded-xl px-3 py-2 text-xs focus:outline-none focus:ring-1 focus:ring-[color:var(--emp-brand)]"
                        placeholder="Why do you need this client added?"></textarea>
                </div>
                <button type="button" id="fakeClientRequestBtn"
                    class="w-full inline-flex items-center justify-center gap-1 px-3 py-2 rounded-xl bg-[color:var(--emp-brand)] text-white text-xs font-semibold hover:bg-blue-700 transition">
                    Submit Request (UI only)
                </button>
                <div id="clientRequestMsg" class="text-[11px] text-emerald-600 mt-1 hidden">
                    Request captured (demo only). Backend workflow will be added later.
                </div>
            </div>
        </div>
    </div>

    
    <div id="returnModal" class="fixed inset-0 bg-black/40 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-2xl shadow-xl w-full max-w-sm mx-4">
            <div class="px-4 py-3 border-b border-slate-200 flex items-center justify-between">
                <h3 class="text-sm font-semibold text-slate-800">Return Trip Details</h3>
                <button type="button" id="returnModalClose"
                    class="text-xs text-slate-500 hover:text-slate-700">&times;</button>
            </div>

            <div class="p-4 space-y-4">
                
                <div id="returnStepQuestion">
                    <p class="text-xs text-slate-600 mb-3">
                        Is the fare for the return journey the same as the onward fare?
                    </p>
                    <div class="flex flex-col gap-2">
                        <button type="button" id="btnReturnSame"
                            class="w-full px-3 py-2 rounded-xl bg-[color:var(--emp-brand)] text-white text-xs font-semibold hover:bg-blue-700">
                            Yes, same fare (use ×2)
                        </button>
                        <button type="button" id="btnReturnDifferent"
                            class="w-full px-3 py-2 rounded-xl border border-[color:var(--emp-border)] text-xs font-semibold text-[color:var(--emp-text)] hover:bg-slate-50">
                            No, different fare
                        </button>
                    </div>
                </div>

                
                <div id="returnStepDifferent" class="hidden space-y-3">
                    <div>
                        <label class="block text-[11px] font-medium mb-1">Return Amount (₹)</label>
                        <input type="number" step="0.01" min="0" id="returnDifferentAmount"
                            class="w-full border border-[color:var(--emp-border)] rounded-xl px-3 py-2 text-xs focus:outline-none focus:ring-1 focus:ring-[color:var(--emp-brand)]"
                            placeholder="Enter return fare">
                    </div>
                    <div>
                        <label class="block text-[11px] font-medium mb-1">Return Remark (optional)</label>
                        <input type="text" id="returnDifferentRemark"
                            class="w-full border border-[color:var(--emp-border)] rounded-xl px-3 py-2 text-xs focus:outline-none focus:ring-1 focus:ring-[color:var(--emp-brand)]"
                            placeholder="e.g. different route, surge pricing">
                    </div>
                    <div class="flex justify-end gap-2 pt-1">
                        <button type="button" id="btnReturnDifferentBack"
                            class="px-3 py-1.5 rounded-xl text-[11px] border border-[color:var(--emp-border)] text-[color:var(--emp-muted)] hover:bg-slate-50">
                            Back
                        </button>
                        <button type="button" id="btnReturnDifferentSave"
                            class="px-3 py-1.5 rounded-xl bg-[color:var(--emp-brand)] text-white text-[11px] font-semibold hover:bg-blue-700">
                            Save return fare
                        </button>
                    </div>
                </div>
            </div>

            <div class="px-4 py-3 border-t border-slate-200 flex justify-end">
                <button type="button" id="returnModalCancel"
                    class="px-3 py-1.5 rounded-xl text-[11px] text-[color:var(--emp-muted)] hover:bg-slate-50">
                    Cancel return
                </button>
            </div>
        </div>
    </div>

    <?php
        $clientOptionsHtml = '<option value=\"\">Select client</option>';
        foreach ($clients as $c) {
            $clientOptionsHtml .= '<option value=\"' . $c->id . '\">' . e($c->name) . '</option>';
        }
        $clientOptionsHtml .= '<option value=\"__request_new__\">+ Request new client…</option>';
    ?>

    
    <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.45rem;
            /* visually center text */
            padding-bottom: 0.45rem;
            padding-left: 0.625rem;
            padding-right: 0.625rem;
            line-height: 1.2;
        }

        .responsive-table textarea {
            height: 44px;
            min-height: 44px;
            padding-top: 0.45rem;
            padding-bottom: 0.45rem;
        }

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

        /* Date picker indicator visual consistency */
        .responsive-table input[type="date"]::-webkit-calendar-picker-indicator {
            opacity: 0.9;
        }

        /* 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;
            }

            /* Hide pseudo label (we're using explicit label elements for better control) */
            .responsive-table td::before {
                display: none !important;
            }

            /* 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;
            /* emerald-50 */
            border: 1px solid #bbf7d0;
            /* emerald-200 */
            color: #065f46;
            /* emerald-800 */
            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;
            /* rose-50 */
            border: 1px solid #fecaca;
            /* rose-200 */
            color: #9f1239;
            /* rose-800 */
            padding: 0.6rem 0.9rem;
            border-radius: 0.75rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            font-weight: 600;
        }

        /* Keep existing desktop data-label styling for accessibility but it's not used on mobile now */
        .responsive-table td[data-label] {
            position: relative;
        }

        /* GLOBAL FLOATING BANNER (mobile-friendly) */
        #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;
            /* outer wrapper non-interactive; inner content will be interactive */
            transition: transform .22s ease, opacity .22s ease;
            opacity: 0;
        }

        #globalBanner.show {
            transform: translateX(-50%) translateY(0);
            opacity: 1;
        }

        #globalBannerInner {
            pointer-events: auto;
            /* allow taps/clicks inside */
            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);
        }

        /* compact styling for mobile text and buttons */
        #globalBannerInner .gb-message {
            flex: 1;
            font-weight: 600;
            font-size: 14px;
        }

        #globalBannerInner .gb-close {
            font-size: 13px;
            margin-left: 8px;
        }

        @media (min-width: 768px) {

            /* On desktop keep the floating banner subtle (but still available) */
            #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>
        const clientOptionsHtml = "<?php echo $clientOptionsHtml; ?>";
        const minDate = "<?php echo e($monthStart->format('Y-m-d')); ?>";
        const maxDate = "<?php echo e($monthEnd->format('Y-m-d')); ?>";
        const clientRequestUrl = "<?php echo e(route('employee.client-requests.store')); ?>";

        let rowCounter = 0;
        const rowsContainer = document.getElementById('conv-rows');
        const totalAmountCell = document.getElementById('totalAmountCell');

        // Card banner
        const cardBannerContainer = document.getElementById('cardBannerContainer');
        let cardBannerTimeout = null;

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

        // Modal-related variables
        let returnModal,
            returnStepQuestion,
            returnStepDifferent,
            btnReturnSame,
            btnReturnDifferent,
            btnReturnDifferentBack,
            btnReturnDifferentSave,
            btnReturnModalClose,
            btnReturnModalCancel,
            inputReturnDifferentAmount,
            inputReturnDifferentRemark,
            currentReturnCheckbox = null;

        function formatCurrency(value) {
            const num = isNaN(value) ? 0 : Number(value);
            return '₹ ' + num.toFixed(2);
        }

        // --- CARD BANNER (visible inside the card) ---
        // type: 'success' | 'error' | 'info'
        function showCardBanner(message, type = 'success', persist = false) {
            // clear existing
            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);

            // Dismiss action
            document.getElementById('dismissCardBanner')?.addEventListener('click', () => {
                hideCardBanner();
            });

            // auto-hide if not persistent
            if (!persist) {
                if (cardBannerTimeout) clearTimeout(cardBannerTimeout);
                cardBannerTimeout = setTimeout(() => {
                    hideCardBanner();
                }, 5000);
            }

            // ALSO show the floating banner on small screens for better visibility
            try {
                if (window.innerWidth < 768) {
                    showGlobalBanner(message, type, persist);
                }
            } catch (e) {
                // ignore if window not available
            }
        }

        function hideCardBanner() {
            cardBannerContainer.classList.add('hidden');
            cardBannerContainer.innerHTML = '';
            if (cardBannerTimeout) {
                clearTimeout(cardBannerTimeout);
                cardBannerTimeout = null;
            }
        }

        // GLOBAL floating banner (toast) helper
        function showGlobalBanner(message, type = 'success', persist = false) {
            // Avoid duplicating the same message — clear previous
            if (bannerTimeout) {
                clearTimeout(bannerTimeout);
                bannerTimeout = null;
            }

            // Accessibility attributes
            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>
                    `;

            // Apply background classes based on type
            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';
            }

            // Show banner
            globalBanner.classList.add('show');

            // Auto-hide if not persistent
            if (!persist) {
                bannerTimeout = setTimeout(() => {
                    hideGlobalBanner();
                }, 5000);
            }

            // Close button
            document.getElementById('closeGlobalBanner')?.addEventListener('click', () => {
                hideGlobalBanner();
            });

            // Allow tapping outside to dismiss on small screens
            // (we won't attach a global handler; instead a short touchstart near the banner hides it)
            globalBanner.addEventListener('touchstart', _touchDismiss, { once: true, passive: true });
        }

        function _touchDismiss(e) {
            // If user taps the banner itself, don't hide (they may intend to press Dismiss). If they tap anywhere near, hide.
            hideGlobalBanner();
        }

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

        // TOTAL calculation: respects custom return_amount if present
        function recalcTotal() {
            let total = 0;
            const mainRows = rowsContainer.querySelectorAll('tr[data-row-type="main"]');

            mainRows.forEach(row => {
                const amountInput = row.querySelector('input[data-field="amount"]');
                const returnCheckbox = row.querySelector('input[data-field="return"]');
                const returnAmountInput = row.querySelector('input[data-field="return_amount"]');

                const amt = parseFloat(amountInput?.value || '0');
                if (isNaN(amt) || amt <= 0) return;

                if (returnCheckbox && returnCheckbox.checked) {
                    const retAmt = parseFloat(returnAmountInput?.value || '0');

                    // If custom return amount given → onward + return
                    if (!isNaN(retAmt) && retAmt > 0) {
                        total += amt + retAmt;
                    } else {
                        // Same fare → double
                        total += amt * 2;
                    }
                } else {
                    total += amt;
                }
            });

            totalAmountCell.textContent = formatCurrency(total);
        }

        // Update/create the grey "Return leg" display row
        function updateReturnDisplayRow(rowId) {
            const mainRow = document.querySelector(`tr[data-row-id="${rowId}"]`);
            if (!mainRow) return;

            const dateInput = mainRow.querySelector('input[type="date"]');
            const fromInput = mainRow.querySelector('input[data-field="from"]');
            const toInput = mainRow.querySelector('input[data-field="to"]');
            const clientSelect = mainRow.querySelector('select[data-field="client"]');
            const modeInput = mainRow.querySelector('input[data-field="mode"]');
            const amountInput = mainRow.querySelector('input[data-field="amount"]');
            const returnAmountInput = mainRow.querySelector('input[data-field="return_amount"]');
            const returnRemarkInput = mainRow.querySelector('input[data-field="return_remarks"]');

            const dateVal = dateInput?.value || '-';
            const fromVal = fromInput?.value || '-';
            const toVal = toInput?.value || '-';
            const clientText = clientSelect?.selectedOptions[0]?.text || '-';
            const modeText = modeInput?.value || '-';
            const onwardAmt = parseFloat(amountInput?.value || '0');
            const retAmt = parseFloat(returnAmountInput?.value || '0');
            const useSameFare = isNaN(retAmt) || retAmt <= 0;
            const displayAmt = useSameFare ? onwardAmt : retAmt;

            const remarksText = useSameFare
                ? 'Return leg (auto – same fare)'
                : (returnRemarkInput?.value || 'Return leg (custom fare)');

            let existingReturnRow = document.querySelector(`tr[data-return-row-for="${rowId}"]`);
            if (!existingReturnRow) {
                existingReturnRow = document.createElement('tr');
                existingReturnRow.setAttribute('data-row-type', 'return');
                existingReturnRow.setAttribute('data-return-row-for', rowId);
                existingReturnRow.className = 'bg-[color:var(--emp-bg-soft)] text-[11px]';
                mainRow.insertAdjacentElement('afterend', existingReturnRow);
            }

            existingReturnRow.innerHTML = `
                        <td data-label="Date" class="p-2 md:p-3 text-[color:var(--emp-muted)]">
                            <div class="md:hidden mobile-label">Date</div>
                            <div class="field-wrap">${dateVal}</div>
                        </td>
                        <td data-label="From" class="p-2 md:p-3 text-[color:var(--emp-muted)]">
                            <div class="md:hidden mobile-label">From</div>
                            <div class="field-wrap">${toVal}</div>
                        </td>
                        <td data-label="To" class="p-2 md:p-3 text-[color:var(--emp-muted)]">
                            <div class="md:hidden mobile-label">To</div>
                            <div class="field-wrap">${fromVal}</div>
                        </td>
                        <td data-label="Client" class="p-2 md:p-3 text-[color:var(--emp-muted)]">
                            <div class="md:hidden mobile-label">Client</div>
                            <div class="field-wrap">${clientText}</div>
                        </td>
                        <td data-label="Mode" class="p-2 md:p-3 text-[color:var(--emp-muted)]">
                            <div class="md:hidden mobile-label">Mode</div>
                            <div class="field-wrap">${modeText}</div>
                        </td>
                        <td data-label="Amount" class="p-2 md:p-3 text-right text-[color:var(--emp-muted)]">
                            <div class="md:hidden mobile-label">Amount</div>
                            <div class="field-wrap">${isNaN(displayAmt) ? '₹ 0.00' : formatCurrency(displayAmt)}</div>
                        </td>
                        <td data-label="Remarks" class="p-2 md:p-3 text-[color:var(--emp-muted)] italic">
                            <div class="md:hidden mobile-label">Remarks</div>
                            <div class="field-wrap">${remarksText}</div>
                        </td>
                        <td data-label="" class="p-2 md:p-3 text-center"></td>
                        <td data-label="" class="p-2 md:p-3"></td>
                    `;
        }

        function handleReturnToggle(checkbox) {
            const rowId = checkbox.dataset.rowId;
            const mainRow = document.querySelector(`tr[data-row-id="${rowId}"]`);
            if (!mainRow) return;

            const returnAmountInput = mainRow.querySelector('input[data-field="return_amount"]');
            const returnRemarkInput = mainRow.querySelector('input[data-field="return_remarks"]');
            const clientSelect = mainRow.querySelector('select[data-field="client"]');

            if (checkbox.checked) {
                if (!clientSelect.value) {
                    showCardBanner('Please select a client before adding a return trip.', 'error');
                    checkbox.checked = false;
                    clientSelect.focus();
                    return;
                }

                // Open modal to decide same vs different
                currentReturnCheckbox = checkbox;
                openReturnModal();
            } else {
                // Clear any custom return data and display row
                if (returnAmountInput) returnAmountInput.value = '';
                if (returnRemarkInput) returnRemarkInput.value = '';
                const existingReturnRow = document.querySelector(`tr[data-return-row-for="${rowId}"]`);
                if (existingReturnRow) existingReturnRow.remove();
                recalcTotal();
            }
        }

        function handleClientChange(selectEl) {
            if (selectEl.value === '__request_new__') {
                selectEl.value = '';
                document.getElementById('clientRequestBox').classList.remove('hidden');
            }
        }

        function createRow() {
            rowCounter++;
            const rowId = 'row-' + rowCounter;

            const tr = document.createElement('tr');
            tr.setAttribute('data-row-type', 'main');
            tr.setAttribute('data-row-id', rowId);
            tr.className = 'hover:bg-slate-50 transition';

            // Each td includes a mobile-only label above the input for consistent sizing on phones
            tr.innerHTML = `
                        <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="rows[${rowCounter}][date]"
                                       min="${minDate}"
                                       max="${maxDate}"
                                       class="w-full border border-[color:var(--emp-border)] rounded-xl text-[13px] focus:outline-none focus:ring-2 focus:ring-[color:var(--emp-brand)]">
                            </div>
                        </td>
                        <td data-label="From" class="p-2 md:p-3 align-top">
                            <div class="md:hidden mobile-label">From</div>
                            <div class="field-wrap">
                                <input type="text"
                                       name="rows[${rowCounter}][from]"
                                       data-field="from"
                                       class="w-full border border-[color:var(--emp-border)] rounded-xl text-[13px] focus:outline-none focus:ring-2 focus:ring-[color:var(--emp-brand)]"
                                       placeholder="From">
                            </div>
                        </td>
                        <td data-label="To" class="p-2 md:p-3 align-top">
                            <div class="md:hidden mobile-label">To</div>
                            <div class="field-wrap">
                                <input type="text"
                                       name="rows[${rowCounter}][to]"
                                       data-field="to"
                                       class="w-full border border-[color:var(--emp-border)] rounded-xl text-[13px] focus:outline-none focus:ring-2 focus:ring-[color:var(--emp-brand)]"
                                       placeholder="To">
                            </div>
                        </td>
                        <td data-label="Client" class="p-2 md:p-3 align-top">
                            <div class="md:hidden mobile-label">Client</div>
                            <div class="field-wrap">
                                <select name="rows[${rowCounter}][client_id]"
                                        data-field="client"
                                        required
                                        class="w-full border border-[color:var(--emp-border)] rounded-xl text-[13px] bg-white focus:outline-none focus:ring-2 focus:ring-[color:var(--emp-brand)]"
                                        onchange="handleClientChange(this)">
                                    ${clientOptionsHtml}
                                </select>
                            </div>
                        </td>
                        <td data-label="Mode" class="p-2 md:p-3 align-top">
                            <div class="md:hidden mobile-label">Mode</div>
                            <div class="field-wrap">
                                <input type="text"
                                       name="rows[${rowCounter}][mode]"
                                       data-field="mode"
                                       class="w-full border border-[color:var(--emp-border)] rounded-xl text-[13px] focus:outline-none focus:ring-2 focus:ring-[color:var(--emp-brand)]"
                                       placeholder="e.g. Cab, Auto, Bus">
                            </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="rows[${rowCounter}][amount]"
                                       data-field="amount"
                                       class="w-full border border-[color:var(--emp-border)] rounded-xl text-[13px] text-right focus:outline-none focus:ring-2 focus:ring-[color:var(--emp-brand)]"
                                       placeholder="0.00"
                                       oninput="recalcTotal()">
                            </div>
                        </td>
                        <td data-label="Remarks" class="p-2 md:p-3 align-top">
                            <div class="md:hidden mobile-label">Remarks</div>
                            <div class="field-wrap">
                                <input type="text"
                                       name="rows[${rowCounter}][remarks]"
                                       class="w-full border border-[color:var(--emp-border)] rounded-xl text-[13px] focus:outline-none focus:ring-2 focus:ring-[color:var(--emp-brand)]"
                                       placeholder="Optional remarks">
                            </div>
                        </td>
                        <td data-label="Return" class="p-2 md:p-3 text-center align-top">
                            <div class="md:hidden mobile-label">Return</div>
                            <div class="field-wrap">
                                <input type="checkbox"
                                       name="rows[${rowCounter}][return]"
                                       value="1"
                                       data-field="return"
                                       data-row-id="${rowId}"
                                       class="h-4 w-4 rounded border-[color:var(--emp-border)] text-[color:var(--emp-brand)] focus:ring-[color:var(--emp-brand)]"
                                       onchange="handleReturnToggle(this)">
                            </div>
                        </td>
                        <td data-label="Actions" class="p-2 md:p-3 text-center align-top actions">
                            <div class="md:hidden mobile-label">Actions</div>
                            <div class="field-wrap">
                                <button type="button"
                                        class="text-[11px] text-rose-500 hover:text-rose-700"
                                        onclick="removeRow('${rowId}')">
                                    ✕
                                </button>
                            </div>

                            <!-- Hidden fields for custom return (moved inside TD) -->
                            <input type="hidden"
                                   name="rows[${rowCounter}][return_amount]"
                                   data-field="return_amount">
                            <input type="hidden"
                                   name="rows[${rowCounter}][return_remarks]"
                                   data-field="return_remarks">
                        </td>
                    `;
            rowsContainer.appendChild(tr);
        }

        function removeRow(rowId) {
            const mainRow = document.querySelector(`tr[data-row-id="${rowId}"]`);
            const returnRow = document.querySelector(`tr[data-return-row-for="${rowId}"]`);
            if (returnRow) returnRow.remove();
            if (mainRow) mainRow.remove();
            recalcTotal();
        }

        function openReturnModal() {
            if (!returnModal) return;
            // Reset modal to first step
            returnStepQuestion.classList.remove('hidden');
            returnStepDifferent.classList.add('hidden');
            inputReturnDifferentAmount.value = '';
            inputReturnDifferentRemark.value = '';
            returnModal.classList.remove('hidden');
        }

        function closeReturnModal() {
            if (!returnModal) return;
            returnModal.classList.add('hidden');
            currentReturnCheckbox = null;
        }

        document.addEventListener('DOMContentLoaded', () => {
            // Init modal DOM refs
            returnModal = document.getElementById('returnModal');
            returnStepQuestion = document.getElementById('returnStepQuestion');
            returnStepDifferent = document.getElementById('returnStepDifferent');
            btnReturnSame = document.getElementById('btnReturnSame');
            btnReturnDifferent = document.getElementById('btnReturnDifferent');
            btnReturnDifferentBack = document.getElementById('btnReturnDifferentBack');
            btnReturnDifferentSave = document.getElementById('btnReturnDifferentSave');
            btnReturnModalClose = document.getElementById('returnModalClose');
            btnReturnModalCancel = document.getElementById('returnModalCancel');
            inputReturnDifferentAmount = document.getElementById('returnDifferentAmount');
            inputReturnDifferentRemark = document.getElementById('returnDifferentRemark');

            // Modal buttons
            if (btnReturnSame) {
                btnReturnSame.addEventListener('click', () => {
                    if (!currentReturnCheckbox) return;
                    const rowId = currentReturnCheckbox.dataset.rowId;
                    const mainRow = document.querySelector(`tr[data-row-id="${rowId}"]`);
                    if (!mainRow) return;

                    // Clear custom return amount for "same fare"
                    const retAmtInput = mainRow.querySelector('input[data-field="return_amount"]');
                    const retRemInput = mainRow.querySelector('input[data-field="return_remarks"]');
                    if (retAmtInput) retAmtInput.value = '';
                    if (retRemInput) retRemInput.value = '';

                    updateReturnDisplayRow(rowId);
                    recalcTotal();
                    closeReturnModal();
                });
            }

            if (btnReturnDifferent) {
                btnReturnDifferent.addEventListener('click', () => {
                    returnStepQuestion.classList.add('hidden');
                    returnStepDifferent.classList.remove('hidden');
                    inputReturnDifferentAmount.focus();
                });
            }

            if (btnReturnDifferentBack) {
                btnReturnDifferentBack.addEventListener('click', () => {
                    returnStepDifferent.classList.add('hidden');
                    returnStepQuestion.classList.remove('hidden');
                });
            }

            if (btnReturnDifferentSave) {
                btnReturnDifferentSave.addEventListener('click', () => {
                    if (!currentReturnCheckbox) return;
                    const rowId = currentReturnCheckbox.dataset.rowId;
                    const mainRow = document.querySelector(`tr[data-row-id="${rowId}"]`);
                    if (!mainRow) return;

                    const val = parseFloat(inputReturnDifferentAmount.value || '0');
                    const remark = inputReturnDifferentRemark.value.trim();

                    if (isNaN(val) || val <= 0) {
                        alert('Please enter a valid return amount greater than 0.');
                        inputReturnDifferentAmount.focus();
                        return;
                    }

                    const retAmtInput = mainRow.querySelector('input[data-field="return_amount"]');
                    const retRemInput = mainRow.querySelector('input[data-field="return_remarks"]');

                    if (retAmtInput) retAmtInput.value = val.toFixed(2);
                    if (retRemInput) retRemInput.value = remark;

                    updateReturnDisplayRow(rowId);
                    recalcTotal();
                    closeReturnModal();
                });
            }

            // Close/cancel actions
            if (btnReturnModalClose) {
                btnReturnModalClose.addEventListener('click', () => {
                    if (currentReturnCheckbox) {
                        currentReturnCheckbox.checked = false;
                    }
                    closeReturnModal();
                    recalcTotal();
                });
            }

            if (btnReturnModalCancel) {
                btnReturnModalCancel.addEventListener('click', () => {
                    if (currentReturnCheckbox) {
                        const rowId = currentReturnCheckbox.dataset.rowId;
                        const mainRow = document.querySelector(`tr[data-row-id="${rowId}"]`);
                        if (mainRow) {
                            const retAmtInput = mainRow.querySelector('input[data-field="return_amount"]');
                            const retRemInput = mainRow.querySelector('input[data-field="return_remarks"]');
                            if (retAmtInput) retAmtInput.value = '';
                            if (retRemInput) retRemInput.value = '';
                            const existingReturnRow = document.querySelector(`tr[data-return-row-for="${rowId}"]`);
                            if (existingReturnRow) existingReturnRow.remove();
                        }
                        currentReturnCheckbox.checked = false;
                    }
                    closeReturnModal();
                    recalcTotal();
                });
            }

            // Also close if clicking outside the dialog (on the backdrop)
            if (returnModal) {
                returnModal.addEventListener('click', (e) => {
                    if (e.target === returnModal) {
                        if (currentReturnCheckbox) {
                            currentReturnCheckbox.checked = false;
                        }
                        closeReturnModal();
                        recalcTotal();
                    }
                });
            }

            // Start with one row
            createRow();

            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);
            });

            document.getElementById('closeClientRequest')?.addEventListener('click', () => {
                document.getElementById('clientRequestBox').classList.add('hidden');
            });

            // REAL client request submit with loader (shows in-card banner)
            document.getElementById('fakeClientRequestBtn')?.addEventListener('click', async (e) => {
                const btn = e.currentTarget;
                const nameInput = document.getElementById('reqClientName');
                const notesInput = document.getElementById('reqClientNotes');

                const name = nameInput.value.trim();
                const notes = notesInput.value.trim();

                if (!name) {
                    showCardBanner('Please enter client name for request.', 'error');
                    nameInput.focus();
                    return;
                }

                const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

                // Start loading state
                btn.disabled = true;
                const originalHtml = btn.innerHTML;
                btn.innerHTML = `
                            <svg class="animate-spin h-4 w-4 mr-2 inline-block" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
                            </svg>
                            Sending...
                        `;

                try {
                    const res = await fetch(clientRequestUrl, {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': token,
                            'Accept': 'application/json',
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            client_name: name,
                            notes: notes,
                        }),
                    });

                    if (!res.ok) {
                        const data = await res.json().catch(() => ({}));
                        showCardBanner(data.message || 'Failed to submit client request.', 'error', true);
                        return;
                    }

                    const data = await res.json();
                    showCardBanner(
                        data.message ||
                        'Client request submitted. Once Admin approves & creates it, the client will appear in your dropdown automatically.',
                        'success', true
                    );

                    // Reset + hide box
                    nameInput.value = '';
                    notesInput.value = '';
                    document.getElementById('clientRequestBox').classList.add('hidden');
                } catch (err) {
                    console.error(err);
                    showCardBanner('Network error while submitting client request.', 'error', true);
                } finally {
                    // Restore button
                    btn.disabled = false;
                    btn.innerHTML = originalHtml;
                }
            });

            const form = document.getElementById('conveyanceForm');
            const submitBtn = document.getElementById('submitBtn');
            const saveDraftBtn = document.getElementById('saveDraftBtn');
            const saveModeInput = document.getElementById('saveModeInput');

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

            // AJAX submit for conveyance rows
            form.addEventListener('submit', async (e) => {
                e.preventDefault();

                const currentMode = saveModeInput.value || 'final'; // draft/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(); // hide previous message
                hideGlobalBanner();

                const formData = new FormData(form);
                const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

                try {
                    const response = await fetch(form.action, {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': token,
                            'Accept': 'application/json',
                        },
                        body: formData,
                    });

                    if (response.status === 422) {
                        const data = await response.json();
                        if (data.errors) {
                            Object.keys(data.errors).forEach(key => {
                                // Match fields like rows.0.date → convert to form input name format
                                const nameCandidates = [
                                    key,
                                    key.replace(/\./g, '\\.'),
                                    key.replace(/\./g, '[').replace(/(\d+)\]/g, '$1]').replace(/rows\./, 'rows[')
                                ];
                                // Try to find an input
                                let field = null;
                                for (const candidate of nameCandidates) {
                                    field = form.querySelector(`[name="${candidate}"]`);
                                    if (field) break;
                                }
                                // Fallback: attempt to find first input matching rows[*][fieldname]
                                if (!field) {
                                    const m = key.match(/rows\.(\d+)\.(\w+)/);
                                    if (m) {
                                        const probe = form.querySelector(`[name="rows[${m[1]}][${m[2]}]"]`);
                                        if (probe) field = probe;
                                    }
                                }

                                if (field) {
                                    field.classList.add('border-red-400');
                                    field.scrollIntoView({ behavior: 'smooth', block: 'center' });
                                }
                            });
                            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' ? 'Conveyance submitted.' : 'Draft saved.'), 'success', true);

                        // FINAL: reset sheet
                        if (currentMode === 'final') {
                            rowsContainer.innerHTML = '';
                            rowCounter = 0;
                            recalcTotal();
                            createRow();
                        }
                        // DRAFT: keep rows as-is
                    }
                } catch (err) {
                    console.error(err);
                    showCardBanner('Network error. Please try again.', 'error', true);
                } finally {
                    // reset to default final for next submit
                    saveModeInput.value = 'final';
                    submitBtn.disabled = false;
                    saveDraftBtn.disabled = false;
                    submitBtn.textContent = 'Submit Conveyance';
                }
            });
        });
    </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/conveyance/create.blade.php ENDPATH**/ ?>