@extends('layouts.employee')

@section('page-title', 'Edit Expense')
@section('page-subtitle', 'Edit expense — same sheet layout as Add')

@section('content')
@php
    // Normalize existing files into array of ['path'=>..., 'original_name'=>...]
    $existingFiles = [];
    if (isset($expense)) {
        if (!empty($expense->proof_paths) && is_array($expense->proof_paths)) {
            $existingFiles = $expense->proof_paths;
        } elseif (!empty($expense->proof_path)) {
            $existingFiles = [['path' => $expense->proof_path, 'original_name' => $expense->proof_original_name ?? basename($expense->proof_path)]];
        }
    }
@endphp

{{-- TOP SECTION --}}
<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">Edit Expense</h2>
        <p class="text-sm text-[color:var(--emp-muted)] mt-1">
            Edit your expense using the same sheet layout as Add Expenses.
        </p>
        <p class="text-xs text-[color:var(--emp-muted)] mt-1">
            Expense Date: <span class="font-semibold text-[color:var(--emp-text)]">{{ $expense->expense_date->format('d M Y') }}</span>
        </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">Notes</div>
        <ul class="space-y-1.5">
            <li>• Remove existing files to delete them on save.</li>
            <li>• Use <span class="font-semibold">Attached</span> to add bills (PNG / JPG / PDF). Max 5MB each.</li>
            <li>• Amount is in ₹ (rupees).</li>
        </ul>
    </div>
</div>

{{-- CARD --}}
<div class="rounded-3xl bg-[color:var(--emp-surface)] border border-[color:var(--emp-border)] shadow-sm p-5 mb-6">
    {{-- header --}}
    <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 Entry</h3>
            <p class="text-xs md:text-sm text-[color:var(--emp-muted)] mt-1">Update the row below and save.</p>
        </div>

        <div class="flex gap-2">
            <a href="{{ route('employee.expenses.index') }}" class="inline-flex items-center gap-2 px-3 py-2 rounded-xl border bg-[color:var(--emp-bg-soft)] text-xs font-semibold hover:bg-slate-100">← Back</a>
        </div>
    </div>

    {{-- in-card banner --}}
    <div id="cardBannerContainer" class="mb-4 hidden"></div>

    {{-- FORM --}}
    <form id="expenseEditForm" method="POST" action="{{ route('employee.expenses.update', $expense->id) }}" enctype="multipart/form-data" novalidate>
        @csrf
        @method('PUT')
        <input type="hidden" name="financial_session_id" value="{{ $expense->financial_session_id }}">
        {{-- remove_files[] inputs appended here by JS --}}
        <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)]">
                        {{-- single prefilled row (mirrors create row structure) --}}
                        <tr data-row-id="edit-row-1" data-row-type="main">
                            {{-- DATE --}}
                            <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="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)]"
                                           value="{{ old('expense_date', $expense->expense_date->format('Y-m-d')) }}">
                                </div>
                            </td>

                            {{-- GROUP --}}
                            <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="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>
                                        @foreach($expenseGroups ?? [] as $g)
                                            <option value="{{ $g->id }}" @selected(old('expense_group_id', $expense->expense_group_id) == $g->id)>{{ $g->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </td>

                            {{-- PARTY NAME --}}
                            <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="party_name" placeholder="Vendor / Party"
                                           class="w-full border border-[color:var(--emp-border)] rounded-xl px-2.5 py-1.5 text-[13px]"
                                           value="{{ old('party_name', $expense->party_name) }}">
                                </div>
                            </td>

                            {{-- PURPOSE --}}
                            <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="purpose" placeholder="Purpose of expense"
                                           class="w-full border border-[color:var(--emp-border)] rounded-xl px-2.5 py-1.5 text-[13px]"
                                           value="{{ old('purpose', $expense->purpose) }}">
                                </div>
                            </td>

                            {{-- AMOUNT --}}
                            <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="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]"
                                           value="{{ old('amount', number_format($expense->amount, 2, '.', '')) }}" oninput="recalcTotal()">
                                </div>
                            </td>

                            {{-- ATTACHED (existing + add new) --}}
                            <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" id="attachedBtn" class="attached-btn px-3 py-1.5 rounded-xl bg-white border text-sm">
                                            Attached (<span id="attached-count">{{ count($existingFiles) }}</span>)
                                        </button>
                                        <div id="attached-summary" class="text-xs text-[color:var(--emp-muted)] file-summary truncate">
                                            @if(count($existingFiles))
                                                {{ collect($existingFiles)->pluck('original_name')->join(', ') }}
                                            @else
                                                No files
                                            @endif
                                        </div>
                                    </div>

                                    {{-- hidden new file input (for adding more) --}}
                                    <input type="file" name="add_files[]" id="addFilesInput" accept=".png,.jpg,.jpeg,.pdf" multiple class="hidden file-input">
                                </div>

                                {{-- existing files are also shown below the input on small screens --}}
                                <div id="existing-files-mobile" class="mt-2 space-y-2 md:hidden">
                                    @foreach($existingFiles as $f)
                                        <div class="existing-file flex items-center justify-between gap-3 p-2 rounded-xl border bg-[color:var(--emp-bg-soft)]">
                                            <div class="truncate text-sm">{{ $f['original_name'] ?? basename($f['path']) }}</div>
                                            <div class="flex items-center gap-2">
                                                <a href="{{ route('employee.expenses.download', $expense->id) }}?file={{ urlencode($f['path']) }}" class="text-xs px-2 py-1 rounded-xl border bg-white hover:bg-slate-50">Download</a>
                                                <button type="button" class="text-xs text-rose-600 hover:underline remove-existing-file" data-path="{{ $f['path'] }}">Remove</button>
                                            </div>
                                        </div>
                                    @endforeach
                                </div>
                            </td>

                            {{-- ACTIONS --}}
                            <td data-label="Actions" class="p-2 md:p-3 text-center align-top">
                                <div class="md:hidden mobile-label">Actions</div>
                                <div class="field-wrap">
                                    <a href="{{ route('employee.expenses.index') }}" class="text-[11px] px-2 py-1 rounded-lg bg-[color:var(--emp-bg-soft)] border border-[color:var(--emp-border)] hover:bg-slate-100 font-semibold">Back</a>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>

                {{-- Desktop existing files list (shown under table on md+) --}}
                <div class="p-4 border-t border-[color:var(--emp-border)] bg-white hidden md:block">
                    <label class="text-xs font-medium mb-2 block">Existing Attachments</label>
                    <div id="existing-files" class="space-y-2">
                        @forelse($existingFiles as $f)
                            <div class="existing-file flex items-center justify-between gap-3 p-3 rounded-xl border bg-[color:var(--emp-bg-soft)]">
                                <div class="truncate text-sm text-[color:var(--emp-text)]">{{ $f['original_name'] ?? basename($f['path']) }}</div>
                                <div class="flex items-center gap-2">
                                    <a href="{{ route('employee.expenses.download', $expense->id) }}?file={{ urlencode($f['path']) }}" class="text-xs px-3 py-1 rounded-xl border bg-white hover:bg-slate-50">Download</a>
                                    <button type="button" class="text-xs text-rose-600 hover:underline remove-existing-file" data-path="{{ $f['path'] }}">Remove</button>
                                </div>
                            </div>
                        @empty
                            <div class="text-xs text-[color:var(--emp-muted)]">No attachments</div>
                        @endforelse
                    </div>
                </div>
            </div>

            {{-- TOTAL BAR & ACTIONS --}}
            <div class="border-t border-[color:var(--emp-border)] bg-slate-50 p-3 flex items-center justify-between gap-3">
                <div class="text-[color:var(--emp-muted)] text-[11px]">
                    Current amount:
                </div>

                <div class="flex items-center gap-2">
                    <div id="totalAmountCell" class="font-extrabold text-[color:var(--emp-brand)] text-base">₹ {{ number_format((float)old('amount', $expense->amount), 2) }}</div>

                    <div class="flex gap-2">
                        <a href="{{ route('employee.expenses.index') }}" 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">Cancel</a>

                        <button type="submit" id="submitBtn" 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">
                            Save Changes
                        </button>
                    </div>
                </div>
            </div>
        </div>

        {{-- container for remove_files[] hidden inputs (added by JS when user removes existing files) --}}
        <div id="removeFilesContainer"></div>
    </form>
</div>

{{-- Styles for responsive table and equal heights (matches Create) --}}
<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; }
    .responsive-table input[type="checkbox"] { height: auto; width: auto; }

    @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-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%; }
    }

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

<script>
    // Config (same as create)
    const ALLOWED = ['image/png','image/jpeg','application/pdf'];
    const MAX_BYTES = 5 * 1024 * 1024; // 5MB

    // DOM refs
    const amountInput = document.querySelector('input[name="amount"]');
    const totalAmountCell = document.getElementById('totalAmountCell');
    const addFilesInput = document.getElementById('addFilesInput');
    const attachedBtn = document.getElementById('attachedBtn');
    const attachedCount = document.getElementById('attached-count');
    const attachedSummary = document.getElementById('attached-summary');
    const existingFilesDesktop = document.getElementById('existing-files');
    const removeFilesContainer = document.getElementById('removeFilesContainer');
    const cardBannerContainer = document.getElementById('cardBannerContainer');

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

    function recalcTotal() {
        const a = parseFloat(amountInput?.value || '0') || 0;
        totalAmountCell.textContent = formatCurrency(a);
    }

    // card banner helper
    let cardBannerTimeout = null;
    function showCardBanner(message, type = 'success', persist = false) {
        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) {
            if (cardBannerTimeout) clearTimeout(cardBannerTimeout);
            cardBannerTimeout = setTimeout(hideCardBanner, 5000);
        }
    }
    function hideCardBanner() {
        cardBannerContainer.classList.add('hidden');
        cardBannerContainer.innerHTML = '';
        if (cardBannerTimeout) { clearTimeout(cardBannerTimeout); cardBannerTimeout = null; }
    }

    // Existing file removal (delegated)
    document.addEventListener('click', function(e) {
        const btn = e.target.closest('.remove-existing-file');
        if (!btn) return;
        const path = btn.dataset.path;
        // remove visual row(s)
        const row = btn.closest('.existing-file');
        if (row) row.remove();

        // add hidden input to signal removal to controller
        const inp = document.createElement('input');
        inp.type = 'hidden';
        inp.name = 'remove_files[]';
        inp.value = path;
        removeFilesContainer.appendChild(inp);

        // update attached count & summary
        const currentCount = Number(attachedCount.textContent || '0') - 1;
        attachedCount.textContent = Math.max(0, currentCount);
        attachedSummary.textContent = attachedSummary.textContent.split(',').filter(Boolean).filter(n => !n.includes(path)).join(', ') || 'No files';

        showCardBanner('File marked for deletion. It will be removed when you save.', 'success', true);
    });

    // Attach more files (new uploads)
    attachedBtn?.addEventListener('click', () => addFilesInput.click());

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

        for (const f of files) {
            // fallback check by extension when type missing
            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('Invalid file selected. Allowed: PNG, JPG, PDF. Max 5MB each.', 'error', true);
                addFilesInput.value = '';
                attachedSummary.textContent = 'No files';
                return;
            }
        }

        // show filenames and update attached count (existing + new)
        const existing = Number(attachedCount.textContent || '0');
        attachedCount.textContent = existing + files.length;
        attachedSummary.textContent = files.map(f => f.name).join(', ');
        showCardBanner(files.length + ' file(s) selected.', 'success');
    });

    // init
    document.addEventListener('DOMContentLoaded', () => {
        recalcTotal();

        amountInput?.addEventListener('input', recalcTotal);

        // show server messages if present
        @if(session('success'))
            showCardBanner(@json(session('success')), 'success', true);
        @endif
        @if(session('error'))
            showCardBanner(@json(session('error')), 'error', true);
        @endif
        @if($errors->any())
            showCardBanner(@json($errors->first()), 'error', true);
        @endif
    });
</script>
@endsection
