@extends('layout.app')

@section('content')

<div class="container mt-4">

    <div class="d-flex justify-content-between align-items-center mb-3">
        <h3 class="fw-bold">Lines — Customers & Suppliers</h3>
        <a href="{{ route('user.dashboard') }}" class="btn btn-secondary">
            <i class="fa fa-arrow-left"></i> Back
        </a>
    </div>

    <div class="row">

        <!-- CUSTOMER COLUMN -->
        <div class="col-md-6 mb-4">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h5 class="fw-bold">Customer Line — Add</h5>

                   <form id="customerForm" method="POST" action="{{ route('user.lines.store') }}">
    @csrf
    <input type="hidden" name="type" value="Customer">

    <div class="mb-2">
        <label class="form-label">Line Name <span class="text-danger">*</span></label>

        <input autocomplete="off" 
               type="text" 
               name="line_name" 
               id="customerLineInput"
               class="form-control @error('line_name') is-invalid @enderror"
               placeholder="Enter customer line name"
               value="{{ old('line_name') }}"
               required>

        {{-- For normal (non-AJAX) Validation Errors --}}
        @error('line_name')
            <div class="invalid-feedback d-block">{{ $message }}</div>
        @enderror

        {{-- For AJAX errors --}}
        <div class="invalid-feedback" id="customerLineError"></div>
    </div>
</form>


                    <hr>

                    <h6 class="fw-semibold">Existing Customer Lines</h6>
                    <div class="table-responsive" style="max-height:320px; overflow:auto;">
                        <table class="table table-bordered table-sm" id="customerTable">
                            <thead class="table-dark">
                                <tr>
                                    <th>#</th>
                                    <th>Line Name</th>
                                    <th style="width:140px">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($customers as $i => $c)
                                <tr data-id="{{ $c->line_id }}">
                                    <td>{{ $i + 1 }}</td>
                                    <td class="line-name-cell">{{ $c->line_name }}</td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary btn-edit" data-type="Customer">Edit</button>
                                        <button class="btn btn-sm btn-outline-danger btn-delete" data-type="Customer">Delete</button>
                                    </td>
                                </tr>
                                @endforeach
                                @if($customers->isEmpty())
                                <tr><td colspan="3" class="text-center text-muted">No customer lines.</td></tr>
                                @endif
                            </tbody>
                        </table>
                    </div>

                    <hr>

                    <h6 class="fw-semibold text-muted">Deleted Customer Lines</h6>
                    <div class="table-responsive" style="max-height:150px; overflow:auto;">
                        <table class="table table-sm table-bordered" id="customerDeletedTable">
                            <thead>
                                <tr><th>#</th><th>Line Name</th><th>Restore</th></tr>
                            </thead>
                            <tbody>
                                @foreach($customersDeleted as $i => $d)
                                <tr data-id="{{ $d->line_id }}">
                                    <td>{{ $i + 1 }}</td>
                                    <td>{{ $d->line_name }}</td>
                                    <td><button class="btn btn-sm btn-success btn-restore" data-type="Customer">Restore</button></td>
                                </tr>
                                @endforeach
                                @if($customersDeleted->isEmpty())
                                <tr><td colspan="3" class="text-center text-muted">No deleted lines.</td></tr>
                                @endif
                            </tbody>
                        </table>
                    </div>

                </div>
            </div>
        </div>

        <!-- SUPPLIER COLUMN -->
        <div class="col-md-6 mb-4">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h5 class="fw-bold">Supplier Line — Add</h5>

                    <form id="supplierForm" method="POST" action="{{ route('user.lines.store') }}">
                        @csrf
                        <input type="hidden" name="type" value="Supplier">
                        <div class="mb-2">
                            <label class="form-label">Line Name <span class="text-danger">*</span></label>
                            <input autocomplete="off" type="text" name="line_name" id="supplierLineInput"
                                   class="form-control" placeholder="Enter supplier line name" required>
                            <div class="invalid-feedback" id="supplierLineError"></div>
                        </div>
                    </form>

                    <hr>

                    <h6 class="fw-semibold">Existing Supplier Lines</h6>
                    <div class="table-responsive" style="max-height:320px; overflow:auto;">
                        <table class="table table-bordered table-sm" id="supplierTable">
                            <thead class="table-dark">
                                <tr>
                                    <th>#</th>
                                    <th>Line Name</th>
                                    <th style="width:140px">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($suppliers as $i => $s)
                                <tr data-id="{{ $s->line_id }}">
                                    <td>{{ $i + 1 }}</td>
                                    <td class="line-name-cell">{{ $s->line_name }}</td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary btn-edit" data-type="Supplier">Edit</button>
                                        <button class="btn btn-sm btn-outline-danger btn-delete" data-type="Supplier">Delete</button>
                                    </td>
                                </tr>
                                @endforeach
                                @if($suppliers->isEmpty())
                                <tr><td colspan="3" class="text-center text-muted">No supplier lines.</td></tr>
                                @endif
                            </tbody>
                        </table>
                    </div>

                    <hr>

                    <h6 class="fw-semibold text-muted">Deleted Supplier Lines</h6>
                    <div class="table-responsive" style="max-height:150px; overflow:auto;">
                        <table class="table table-sm table-bordered" id="supplierDeletedTable">
                            <thead>
                                <tr><th>#</th><th>Line Name</th><th>Restore</th></tr>
                            </thead>
                            <tbody>
                                @foreach($suppliersDeleted as $i => $d)
                                <tr data-id="{{ $d->line_id }}">
                                    <td>{{ $i + 1 }}</td>
                                    <td>{{ $d->line_name }}</td>
                                    <td><button class="btn btn-sm btn-success btn-restore" data-type="Supplier">Restore</button></td>
                                </tr>
                                @endforeach
                                @if($suppliersDeleted->isEmpty())
                                <tr><td colspan="3" class="text-center text-muted">No deleted lines.</td></tr>
                                @endif
                            </tbody>
                        </table>
                    </div>

                </div>
            </div>
        </div>

    </div>
</div>

{{-- SCRIPT: placed directly so it always runs --}}
<script>
document.addEventListener('DOMContentLoaded', function () {

    // CSRF token (meta tag recommended in layout: <meta name="csrf-token" content="{{ csrf_token() }}">)
    const meta = document.querySelector('meta[name="csrf-token"]');
    const token = meta ? meta.getAttribute('content') : (document.querySelector('input[name="_token"]')?.value || '');

    // quick helpers
    function showFieldError(type, message) {
        const errId = (type === 'Customer') ? 'customerLineError' : 'supplierLineError';
        const input = (type === 'Customer') ? document.getElementById('customerLineInput') : document.getElementById('supplierLineInput');

        input.classList.add('is-invalid');
        document.getElementById(errId).innerText = message;
    }
    function clearFieldError(type) {
        const errId = (type === 'Customer') ? 'customerLineError' : 'supplierLineError';
        const input = (type === 'Customer') ? document.getElementById('customerLineInput') : document.getElementById('supplierLineInput');

        input.classList.remove('is-invalid');
        document.getElementById(errId).innerText = '';
    }

    // submit on Enter
    ['customerLineInput','supplierLineInput'].forEach(id => {
        const el = document.getElementById(id);
        if (!el) return;
        el.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                const type = id === 'customerLineInput' ? 'Customer' : 'Supplier';
                submitLineForm(type);
            }
        });
    });

    // Submit function
    // function submitLineForm(type) {
    //     clearFieldError(type);
    //     const url = "{{ route('user.lines.store') }}";
    //     const input = (type === 'Customer') ? document.getElementById('customerLineInput') : document.getElementById('supplierLineInput');
    //     const name = input.value.trim();
    //     if (!name) {
    //         showFieldError(type, 'Line name is required');
    //         return;
    //     }

    //     fetch(url, {
    //         method: 'POST',
    //         headers: {
    //             'X-CSRF-TOKEN': token,
    //             'Accept': 'application/json',
    //             'Content-Type': 'application/json'
    //         },
    //         body: JSON.stringify({ line_name: name, type: type })
    //     })
    //     .then(r => r.json().then(j => ({ status: r.status, body: j })).catch(()=>({ status: r.status, body: {} })))
    //     .then(resp => {
    //         if (resp.status >= 400 || resp.body.status === 'error') {
    //             const msg = resp.body.message || 'Server validation failed';
    //             showFieldError(type, msg);
    //             return;
    //         }
    //         const line = resp.body.line;
    //         if (line) addLineRow(type, line);
    //         input.value = '';
    //         clearFieldError(type);
    //     })
    //     .catch(err => {
    //         showFieldError(type, 'Request failed');
    //         console.error(err);
    //     });
    // }
function submitLineForm(type) {
    clearFieldError(type);

    const url = "{{ route('user.lines.store') }}";
    const input = (type === 'Customer')
        ? document.getElementById('customerLineInput')
        : document.getElementById('supplierLineInput');

    const name = input.value.trim();
    if (!name) return showFieldError(type, 'Line name is required');

    fetch(url, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': token,
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({ line_name: name, type: type })
    })
    .then(async r => {
        const body = await r.json().catch(() => ({}));
        return { status: r.status, body };
    })
    .then(resp => {
        if (resp.status !== 200 || resp.body.status === 'error') {
            showFieldError(type, resp.body.message);
            return;
        }

        addLineRow(type, resp.body.line);
        input.value = '';
    })
    .catch(() => {
        showFieldError(type, 'Request failed');
    });
}

    // Create new row at top
    function addLineRow(type, line) {
        const tableId = (type === 'Customer') ? 'customerTable' : 'supplierTable';
        const tbody = document.querySelector(`#${tableId} tbody`);
        if (!tbody) return;
        const noRows = tbody.querySelector('tr td.text-center.text-muted');
        if (noRows) noRows.closest('tr').remove();

        const row = document.createElement('tr');
        row.setAttribute('data-id', line.line_id);

        const indexCell = document.createElement('td');
        indexCell.innerText = (tbody.querySelectorAll('tr').length + 1);

        const nameCell = document.createElement('td');
        nameCell.classList.add('line-name-cell');
        nameCell.innerText = line.line_name;

        const actionsCell = document.createElement('td');
        actionsCell.innerHTML = `
            <button class="btn btn-sm btn-outline-primary btn-edit" data-type="${type}">Edit</button>
            <button class="btn btn-sm btn-outline-danger btn-delete" data-type="${type}">Delete</button>
        `;

        row.appendChild(indexCell);
        row.appendChild(nameCell);
        row.appendChild(actionsCell);

        tbody.prepend(row);
    }

    // Event delegation for edit/delete/restore clicks
    document.addEventListener('click', function (e) {
        const target = e.target;

        // EDIT
        if (target.matches('.btn-edit')) {
            e.preventDefault();
            const btn = target;
            const tr = btn.closest('tr');
            const id = tr?.getAttribute('data-id');
            const type = btn.getAttribute('data-type');
            const cell = tr.querySelector('.line-name-cell');
            const current = cell.innerText;

            cell.innerHTML = `
                <div class="input-group input-group-sm">
                    <input class="form-control edit-input" value="${escapeHtml(current)}" />
                    <button class="btn btn-success btn-save">Save</button>
                    <button class="btn btn-secondary btn-cancel">Cancel</button>
                </div>
            `;

            const input = cell.querySelector('.edit-input');
            const saveBtn = cell.querySelector('.btn-save');
            const cancelBtn = cell.querySelector('.btn-cancel');

            saveBtn.addEventListener('click', function () {
                const newName = input.value.trim();
                if (!newName) return alert('Line name required');
                updateLine(id, newName, tr, type);
            });

            cancelBtn.addEventListener('click', function () {
                cell.innerText = current;
            });

            input.addEventListener('keydown', function (ev) {
                if (ev.key === 'Enter') {
                    ev.preventDefault();
                    saveBtn.click();
                }
                if (ev.key === 'Escape') {
                    cell.innerText = current;
                }
            });

            input.focus();
            input.select();
            return;
        }

        // DELETE (soft)
        if (target.matches('.btn-delete')) {
            e.preventDefault();
            if (!confirm('Delete this line? (soft delete)')) return;

            const btn = target;
            const tr = btn.closest('tr');
            const id = tr?.getAttribute('data-id');
            const url = "{{ url('user/lines') }}/" + id;

            fetch(url, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': token,
                    'Accept': 'application/json'
                }
            })
            .then(r => r.json().then(j => ({ status: r.status, body: j })).catch(()=>({ status: r.status, body: {} })))
            .then(resp => {
                if (resp.status >= 400 || resp.body.status === 'error') {
                    alert(resp.body.message || 'Delete failed');
                    return;
                }
                tr.remove();
                // reload to sync deleted lists and indexes (simple approach)
                location.reload();
            })
            .catch(err => {
                console.error(err);
                alert('Delete request failed');
            });

            return;
        }

        // RESTORE
        if (target.matches('.btn-restore')) {
            e.preventDefault();
            const btn = target;
            const tr = btn.closest('tr');
            const id = tr?.getAttribute('data-id');
            const url = "{{ url('user/lines') }}/" + id + "/restore";

            fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': token,
                    'Accept': 'application/json'
                }
            })
            .then(r => r.json().then(j => ({ status: r.status, body: j })).catch(()=>({ status: r.status, body: {} })))
            .then(resp => {
                if (resp.status >= 400 || resp.body.status === 'error') {
                    alert(resp.body.message || 'Restore failed');
                    return;
                }
                location.reload();
            })
            .catch(err => {
                console.error(err);
                alert('Restore request failed');
            });

            return;
        }

        // SAVE button inside edit box (delegated)
        if (target.matches('.btn-save')) {
            // Handled by saveBtn.addEventListener created when entering edit mode,
            // but kept here if you prefer delegation — current implementation uses local listener.
            return;
        }

    });

    // Update (PATCH) function
    function updateLine(id, newName, tr, type) {
        const url = "{{ url('user/lines') }}/" + id;
        fetch(url, {
            method: 'PATCH',
            headers: {
                'X-CSRF-TOKEN': token,
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ line_name: newName })
        })
        .then(r => r.json().then(j => ({ status: r.status, body: j })).catch(()=>({ status: r.status, body: {} })))
        .then(resp => {
            if (resp.status >= 400 || resp.body.status === 'error') {
                const message = resp.body.message || 'Update failed';
                alert(message);
                return;
            }
            tr.querySelector('.line-name-cell').innerText = resp.body.line.line_name;
        })
        .catch(err => {
            console.error(err);
            alert('Update request failed');
        });
    }

    // escape html
    function escapeHtml(text) {
        return (text + '').replace(/[&<>"'`=\/]/g, function (s) {
            return {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#39;',
                '/': '&#x2F;',
                '=': '&#x3D;',
                '`': '&#x60;'
            }[s];
        });
    }

});
</script>

@endsection
