@extends('layout.app')

@section('content')
<style>
/* layout tweaks */
.panel-card { height: calc(100vh - 140px); }
.card-body { padding: 12px; display:flex; flex-direction:column; gap:10px; min-height:0; }
.form-scroller { overflow:auto; flex:0 0 auto; }
.table-scroller { flex:1; min-height:0; overflow:hidden; display:flex; flex-direction:column; }
.table-fixed-body { overflow-y:auto; flex:1; }

/* toggle */
.type-toggle { display:flex; gap:8px; align-items:center; }
.toggle-btn { padding:6px 12px; border-radius:6px; border:1px solid #ddd; cursor:pointer; }
.toggle-btn.active { background:#0d6efd; color:#fff; border-color:#0d6efd; }

/* suggestion / small */
.text-danger.small { font-size:0.85rem; }

/* tables */
.table thead.table-dark th { position:sticky; top:0; z-index:2; }

/* inline edit styles */
.input-inline { width:100%; box-sizing:border-box; }
.action-btns .btn { margin-right:6px; }

/* deleted table styling smaller */
.deleted-table tbody td { font-size:0.95rem; color:#666; }
</style>

<div class="container mt-1">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h3 class="fw-bold">Add Member</h3>
        <a href="{{ route('user.dashboard') }}" class="btn btn-secondary">
            <i class="fa fa-arrow-left"></i> Back
        </a>
    </div>

    <div class="row">
        <!-- LEFT CARD (form + toggle) -->
        <div class="col-md-6">
            <div class="card shadow-sm panel-card">
                <div class="card-body">

                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div class="type-toggle" role="tablist" aria-label="Member type toggle">
                            <div class="toggle-btn active" data-type="Customer" id="toggleCustomer">Customer</div>
                            <div class="toggle-btn" data-type="Supplier" id="toggleSupplier">Supplier</div>
                        </div>

                        <div>
                            <small class="text-muted">Toggle to switch forms</small>
                        </div>
                    </div>

                    <!-- Customer form -->
                    <form id="formCustomer" class="member-form" data-type="Customer" autocomplete="off">
                        @csrf
                        <div class="form-scroller">
                            <div class="mb-2">
                                <label class="form-label">Name *</label>
                                <input type="text" name="name" class="form-control enter-next input-name" />
                                <div class="text-danger small error-name"></div>
                            </div>
                            <div class="mb-2">
                                <label class="form-label">Phone *</label>
                                <input type="text" name="phone" class="form-control enter-next input-phone" />
                                <div class="text-danger small error-phone"></div>
                            </div>
                            <div class="mb-2">
                                <label class="form-label">Address *</label>
                                <input type="text" name="address" class="form-control enter-next input-address" />
                                <div class="text-danger small error-address"></div>
                            </div>

                            <div class="mb-2">
                                <button type="button" class="btn btn-primary btn-save" data-type="Customer">Save Customer</button>
                                <button type="button" class="btn btn-outline-secondary btn-clear" data-type="Customer">Clear</button>
                            </div>
                            <small class="text-muted">Use Enter to move next. Enter on Address saves.</small>
                        </div>
                    </form>

                    <!-- Supplier form (hidden by toggle) -->
                    <form id="formSupplier" class="member-form d-none" data-type="Supplier" autocomplete="off">
                        @csrf
                        <div class="form-scroller">
                            <div class="mb-2">
                                <label class="form-label">Name *</label>
                                <input type="text" name="name" class="form-control enter-next input-name" />
                                <div class="text-danger small error-name"></div>
                            </div>
                            <div class="mb-2">
                                <label class="form-label">Phone *</label>
                                <input type="text" name="phone" class="form-control enter-next input-phone" />
                                <div class="text-danger small error-phone"></div>
                            </div>
                            <div class="mb-2">
                                <label class="form-label">Address *</label>
                                <input type="text" name="address" class="form-control enter-next input-address" />
                                <div class="text-danger small error-address"></div>
                            </div>

                            <div class="mb-2">
                                <button type="button" class="btn btn-primary btn-save" data-type="Supplier">Save Supplier</button>
                                <button type="button" class="btn btn-outline-secondary btn-clear" data-type="Supplier">Clear</button>
                            </div>
                            <small class="text-muted">Use Enter to move next. Enter on Address saves.</small>
                        </div>
                    </form>

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

        <!-- RIGHT: active + deleted tables per type (we show both but hide one based on toggle) -->
        <div class="col-md-6">
            <div class="card shadow-sm panel-card">
                <div class="card-body">
                    <div class="mb-2 d-flex gap-2">
                        <input id="tableSearch" class="form-control" placeholder="Search name or phone in active table">
                        <button class="btn btn-sm btn-outline-secondary" id="refreshTables">Refresh</button>
                    </div>

                    <div class="table-scroller">
                        <!-- ACTIVE table customer -->
                        <div id="activeCustomerWrap">
                            <h6>Existing Customer Members</h6>
                            <div class="table-fixed-body">
                                <table class="table table-bordered table-sm mb-0" id="customerActiveTable">
                                    <thead class="table-dark">
                                        <tr>
                                            <th style="width:40px">#</th>
                                            <th>Name</th>
                                            <th>Phone</th>
                                            <th>Address</th>
                                            <th style="width:150px">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody id="customerActiveTbody">
                                        @php $i=1; @endphp
                                        @foreach($customers as $c)
                                        <tr data-id="{{ $c->id ?? $c->member_id ?? $c->id ?? '' }}">
                                            <td>{{ $i++ }}</td>
                                            <td class="m-name">{{ $c->name }}</td>
                                            <td class="m-phone">{{ $c->phone }}</td>
                                            <td class="m-address">{{ $c->address }}</td>
                                            <td class="action-btns">
                                                <button class="btn btn-sm btn-outline-primary btn-edit">Edit</button>
                                                <button class="btn btn-sm btn-outline-danger btn-delete">Delete</button>
                                            </td>
                                        </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>

                            <hr class="my-2">

                            <h6>Deleted Customer Members</h6>
                            <div class="table-fixed-body" style="max-height:140px;">
                                <table class="table table-sm deleted-table" id="customerDeletedTable">
                                    <thead>
                                        <tr><th style="width:40px">#</th><th>Name</th><th>Restore</th></tr>
                                    </thead>
                                    <tbody>
                                        @php $i = 1; @endphp
                                        @foreach($customersDeleted as $d)
                                        
                                        <tr data-id="{{ $d->id ?? $d->member_id ?? $d->id ?? '' }}">
                                            <td>{{ $i++ }}</td>
                                            <td>{{ $d->name }}</td>
                                            <td><button class="btn btn-sm btn-success btn-restore">Restore</button></td>
                                        </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- ACTIVE table supplier -->
                        <div id="activeSupplierWrap" class="d-none">
                            <h6>Existing Supplier Members</h6>
                            <div class="table-fixed-body">
                                <table class="table table-bordered table-sm mb-0" id="supplierActiveTable">
                                    <thead class="table-dark">
                                        <tr>
                                            <th style="width:40px">#</th>
                                            <th>Name</th>
                                            <th>Phone</th>
                                            <th>Address</th>
                                            <th style="width:150px">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody id="supplierActiveTbody">
                                        @php $i=1; @endphp
                                        @foreach($suppliers as $s)
                                        <tr data-id="{{ $s->id ?? $s->member_id ?? $s->id ?? '' }}">
                                            <td>{{ $i++ }}</td>
                                            <td class="m-name">{{ $s->name }}</td>
                                            <td class="m-phone">{{ $s->phone }}</td>
                                            <td class="m-address">{{ $s->address }}</td>
                                            <td class="action-btns">
                                                <button class="btn btn-sm btn-outline-primary btn-edit">Edit</button>
                                                <button class="btn btn-sm btn-outline-danger btn-delete">Delete</button>
                                            </td>
                                        </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>

                            <hr class="my-2">

                            <h6>Deleted Supplier Members</h6>
                            <div class="table-fixed-body" style="max-height:140px;">
                                <table class="table table-sm deleted-table" id="supplierDeletedTable">
                                    <thead>
                                        <tr><th style="width:40px">#</th><th>Name</th><th>Restore</th></tr>
                                    </thead>
                                    <tbody>
                                        @php $i = 1; @endphp
                                        @foreach($suppliersDeleted as $d)
                                        <tr data-id="{{ $d->id ?? $d->member_id ?? $d->id ?? '' }}">
                                            <td>{{ $i++ }}</td>
                                            <td>{{ $d->name }}</td>
                                            <td><button class="btn btn-sm btn-success btn-restore">Restore</button></td>
                                        </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        </div>

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

    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {

    // CSRF token helper
    const meta = document.querySelector('meta[name="csrf-token"]');
    const token = meta ? meta.getAttribute('content') : (document.querySelector('input[name="_token"]')?.value || '');

    // Elements
    const toggleCustomer = document.getElementById('toggleCustomer');
    const toggleSupplier = document.getElementById('toggleSupplier');

    const formCustomer = document.getElementById('formCustomer');
    const formSupplier = document.getElementById('formSupplier');

    const activeCustomerWrap = document.getElementById('activeCustomerWrap');
    const activeSupplierWrap = document.getElementById('activeSupplierWrap');

    const tableSearch = document.getElementById('tableSearch');
    const refreshBtn = document.getElementById('refreshTables');

    // helpers to find inputs inside a form
    function getInputs(form) {
        return {
            name: form.querySelector('.input-name'),
            phone: form.querySelector('.input-phone'),
            address: form.querySelector('.input-address'),
            errorName: form.querySelector('.error-name'),
            errorPhone: form.querySelector('.error-phone'),
            errorAddress: form.querySelector('.error-address'),
        };
    }

    // Toggle handlers
    function activateType(type) {
        if (type === 'Customer') {
            toggleCustomer.classList.add('active');
            toggleSupplier.classList.remove('active');
            formCustomer.classList.remove('d-none');
            formSupplier.classList.add('d-none');
            activeCustomerWrap.classList.remove('d-none');
            activeSupplierWrap.classList.add('d-none');
        } else {
            toggleSupplier.classList.add('active');
            toggleCustomer.classList.remove('active');
            formSupplier.classList.remove('d-none');
            formCustomer.classList.add('d-none');
            activeSupplierWrap.classList.remove('d-none');
            activeCustomerWrap.classList.add('d-none');
        }
    }

    toggleCustomer.addEventListener('click', () => activateType('Customer'));
    toggleSupplier.addEventListener('click', () => activateType('Supplier'));

    // Enter navigation for both forms
    document.querySelectorAll('.member-form').forEach(form => {
        const inputs = form.querySelectorAll('.enter-next');
        inputs.forEach((inp, idx) => {
            inp.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    // if last field -> submit
                    if (idx === inputs.length - 1) {
                        form.querySelector('.btn-save').click();
                    } else {
                        inputs[idx + 1].focus();
                    }
                }
            });
        });
    });

    // Clear button
    document.querySelectorAll('.btn-clear').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const type = btn.dataset.type;
            const form = type === 'Customer' ? formCustomer : formSupplier;
            const fb = getInputs(form);
            fb.name.value = ''; fb.phone.value=''; fb.address.value='';
            fb.errorName.innerText=''; fb.errorPhone.innerText=''; fb.errorAddress.innerText='';
            fb.name.focus();
        });
    });

    // Save handlers
    document.querySelectorAll('.btn-save').forEach(btn => {
        btn.addEventListener('click', () => {
            const type = btn.dataset.type;
            const form = type === 'Customer' ? formCustomer : formSupplier;
            submitForm(form, type);
        });
    });

    // Submit form (AJAX)
    async function submitForm(form, type) {
        const fb = getInputs(form);
        // clear errors
        fb.errorName.innerText=''; fb.errorPhone.innerText=''; fb.errorAddress.innerText='';

        const payload = {
            _token: document.querySelector('input[name="_token"]').value,
            name: fb.name.value.trim(),
            phone: fb.phone.value.trim(),
            address: fb.address.value.trim(),
            type: type
        };

        // client-side simple validation
        if (!payload.name) { fb.errorName.innerText = 'Name is required'; fb.name.focus(); return; }
        if (!payload.phone) { fb.errorPhone.innerText = 'Phone is required'; fb.phone.focus(); return; }

        // DUPLICATE PREVENTION: check active rows in table for same name+phone
        const tbody = (type === 'Customer') ? document.getElementById('customerActiveTbody') : document.getElementById('supplierActiveTbody');
        const exists = [...tbody.querySelectorAll('tr')].some(tr => {
            const n = tr.querySelector('.m-name')?.innerText.trim() || '';
            const p = tr.querySelector('.m-phone')?.innerText.trim() || '';
            return n.toLowerCase() === payload.name.toLowerCase() && p === payload.phone;
        });
        if (exists) {
            fb.errorName.innerText = 'This member already exists';
            return;
        }

        // send
        try {
            const res = await fetch("{{ route('user.members.store') }}", {
                method: 'POST',
                headers: {
                    'Content-Type':'application/json',
                    'Accept':'application/json',
                    'X-CSRF-TOKEN': token,
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify(payload)
            });

            const data = await res.json().catch(()=> ({}));

            if (res.status === 422) {
                // show validation errors
                fb.errorName.innerText = data.errors?.name?.[0] ?? '';
                fb.errorPhone.innerText = data.errors?.phone?.[0] ?? '';
                fb.errorAddress.innerText = data.errors?.address?.[0] ?? '';
                return;
            }

            if (res.status >= 400) {
                alert(data.message || 'Server error');
                return;
            }

            // success: server should return created member object as "member"
            const member = data.member ?? payload;

            addRowToTable(type, member);
            // clear form
            fb.name.value=''; fb.phone.value=''; fb.address.value='';
            fb.name.focus();
        } catch (err) {
            console.error(err);
            alert('Request failed');
        }
    }

    // add row to the top of the appropriate active table
    function addRowToTable(type, member) {
        const tbody = (type === 'Customer') ? document.getElementById('customerActiveTbody') : document.getElementById('supplierActiveTbody');
        const tr = document.createElement('tr');
        tr.setAttribute('data-id', member.id ?? member.member_id ?? member.id ?? '');
        tr.innerHTML = `
            <td></td>
            <td class="m-name">${escapeHtml(member.name)}</td>
            <td class="m-phone">${escapeHtml(member.phone)}</td>
            <td class="m-address">${escapeHtml(member.address)}</td>
            
            <td class="action-btns">
                <button class="btn btn-sm btn-outline-primary btn-edit">Edit</button>
                <button class="btn btn-sm btn-outline-danger btn-delete">Delete</button>
            </td>
        `;
        tbody.prepend(tr);
        renumberTbody(tbody);
    }

    function renumberTbody(tbody) {
        [...tbody.querySelectorAll('tr')].forEach((tr, i) => {
            tr.querySelector('td').innerText = i + 1;
        });
    }

    // Delegated click handlers for edit/delete/restore
    document.addEventListener('click', function (e) {
        const el = e.target;

        // EDIT
        if (el.matches('.btn-edit')) {
            const tr = el.closest('tr');
            enterInlineEdit(tr);
            return;
        }

        // DELETE (soft)
        if (el.matches('.btn-delete')) {
            if (!confirm('Delete this member? (soft delete)')) return;
            const tr = el.closest('tr');
            const id = tr.getAttribute('data-id');
            deleteMember(tr, id);
            return;
        }

        // RESTORE
        if (el.matches('.btn-restore')) {
            const tr = el.closest('tr');
            const id = tr.getAttribute('data-id');
            restoreMember(tr, id, (el.closest('table')?.id ?? '').includes('customer') ? 'Customer' : 'Supplier');
            return;
        }
    });

    // inline edit implementation
   function enterInlineEdit(tr) {

    const id = tr.getAttribute('data-id');

    // SAFETY CHECK → prevents "No query results for model Member create"
    if (!id || id === "create") {
        alert("Invalid ID. Row missing data-id attribute.");
        return;
    }

    const nameCell = tr.querySelector('.m-name');
    const phoneCell = tr.querySelector('.m-phone');
    const addrCell = tr.querySelector('.m-address');
    const actions = tr.querySelector('.action-btns');

    const curName = nameCell.innerText.trim();
    const curPhone = phoneCell.innerText.trim();
    const curAddr = addrCell.innerText.trim();

    nameCell.innerHTML = `
        <input class="form-control form-control-sm edit-name input-inline"
               value="${escapeHtml(curName)}">
    `;
    phoneCell.innerHTML = `
        <input class="form-control form-control-sm edit-phone input-inline"
               value="${escapeHtml(curPhone)}">
    `;
    addrCell.innerHTML = `
        <input class="form-control form-control-sm edit-addr input-inline"
               value="${escapeHtml(curAddr)}">
    `;

    actions.innerHTML = `
        <button class="btn btn-sm btn-success btn-save-inline">Save</button>
        <button class="btn btn-sm btn-secondary btn-cancel-inline">Cancel</button>
    `;

    const saveBtn = actions.querySelector('.btn-save-inline');
    const cancelBtn = actions.querySelector('.btn-cancel-inline');

    // -------------------------------------------
    // SAVE BUTTON
    // -------------------------------------------
    saveBtn.addEventListener('click', async () => {

        const newName = tr.querySelector('.edit-name').value.trim();
        const newPhone = tr.querySelector('.edit-phone').value.trim();
        const newAddr = tr.querySelector('.edit-addr').value.trim();

        if (!newName) { alert("Name required"); return; }
        if (!newPhone) { alert("Phone required"); return; }

        // Duplicate check
        const tbody = tr.closest('tbody');
        const duplicate = [...tbody.querySelectorAll('tr')].some(r => {
            if (r === tr) return false;
            const rn = r.querySelector('.m-name')?.innerText.trim() || '';
            const rp = r.querySelector('.m-phone')?.innerText.trim() || '';
            return rn.toLowerCase() === newName.toLowerCase() && rp === newPhone;
        });

        if (duplicate) {
            alert("Another member with same Name + Phone exists");
            return;
        }

        try {
           const res = await fetch(`/user/members/${id}`, {
    method: "PUT",
    headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "X-CSRF-TOKEN": token,
        "X-Requested-With": "XMLHttpRequest"
    },
    body: JSON.stringify({
        name: newName,
        phone: newPhone,
        address: newAddr
    })
});

            const data = await res.json().catch(() => ({}));

            if (res.status === 422) {
                alert(Object.values(data.errors).flat()[0]);
                return;
            }

            if (!res.ok) {
                alert(data.message || "Update failed");
                return;
            }

            // SUCCESS → update table view
            nameCell.innerText = data.member?.name ?? newName;
            phoneCell.innerText = data.member?.phone ?? newPhone;
            addrCell.innerText = data.member?.address ?? newAddr;

            // restore action buttons WITH data-id
            actions.innerHTML = `
                <button class="btn btn-sm btn-outline-primary btn-edit"
                        data-id="${id}">
                    Edit
                </button>
                <button class="btn btn-sm btn-outline-danger btn-delete"
                        data-id="${id}">
                    Delete
                </button>
            `;

        } catch (err) {
            console.error(err);
            alert("Update failed");
        }
    });

    // -------------------------------------------
    // CANCEL BUTTON
    // -------------------------------------------
    cancelBtn.addEventListener('click', () => {

        nameCell.innerText = curName;
        phoneCell.innerText = curPhone;
        addrCell.innerText = curAddr;

        actions.innerHTML = `
            <button class="btn btn-sm btn-outline-primary btn-edit"
                    data-id="${id}">
                Edit
            </button>
            <button class="btn btn-sm btn-outline-danger btn-delete"
                    data-id="${id}">
                Delete
            </button>
        `;
    });
}


    // delete (soft)
   async function deleteMember(tr, id) {
    try {
const res = await fetch("{{ url('user/members') }}/" + id, {

            method: 'DELETE',
            headers: {
                'Accept': 'application/json',
                'X-CSRF-TOKEN': token,
                'X-Requested-With': 'XMLHttpRequest'
            }
        });

        const data = await res.json().catch(() => ({}));

        if (!res.ok) {
            alert(data.message || 'Delete failed');
            return;
        }

        // Determine customer/supplier table
        const isCustomerVisible = !activeCustomerWrap.classList.contains('d-none');
        const deletedTbody = isCustomerVisible
            ? document.querySelector('#customerDeletedTable tbody')
            : document.querySelector('#supplierDeletedTable tbody');

        // Create deleted record row
        const deletedRow = document.createElement('tr');
        deletedRow.setAttribute('data-id', id);
        deletedRow.innerHTML = `
            <td></td>
            <td>${escapeHtml(tr.querySelector('.m-name').innerText)}</td>
            <td>
                <button class="btn btn-sm btn-success btn-restore">Restore</button>
            </td>
        `;

        // Add to deleted table
        deletedTbody.prepend(deletedRow);

        // Remove from active
        tr.remove();

        // renumber tables
        renumberTbody(
            document.getElementById(
                isCustomerVisible ? 'customerActiveTbody' : 'supplierActiveTbody'
            )
        );
        renumberTbody(deletedTbody);

    } catch (err) {
        console.error(err);
        alert('Delete failed');
    }
}

    // restore
    async function restoreMember(tr, id, type) {
        try {
            const res = await fetch("{{ url('user/members') }}/" + id + "/restore", {
                method: 'POST',
                headers: {
                    'Accept':'application/json',
                    'X-CSRF-TOKEN': token,
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });
            const data = await res.json().catch(()=>({}));
            if (res.status >= 400) {
                alert(data.message || 'Restore failed');
                return;
            }

            const member = data.member ?? { id, name: tr.querySelector('td:nth-child(2)').innerText, phone: '', address: '' };
            addRowToTable(type, member);

            // remove deleted row
            tr.remove();
            const deletedTable = (type === 'Customer') ? document.querySelector('#customerDeletedTable tbody') : document.querySelector('#supplierDeletedTable tbody');
            renumberTbody(deletedTable);

        } catch (err) {
            console.error(err);
            alert('Restore failed');
        }
    }

    // refresh: simple page reload (or you can implement Ajax fetch to re-populate tables)
    refreshBtn.addEventListener('click', () => location.reload());

    // simple client-side table search for visible active table
    tableSearch.addEventListener('input', () => {
        const q = tableSearch.value.trim().toLowerCase();
        const activeTbody = !activeCustomerWrap.classList.contains('d-none') ? document.getElementById('customerActiveTbody') : document.getElementById('supplierActiveTbody');
        [...activeTbody.querySelectorAll('tr')].forEach(tr => {
            const name = tr.querySelector('.m-name')?.innerText.trim().toLowerCase() || '';
            const phone = tr.querySelector('.m-phone')?.innerText.trim().toLowerCase() || '';
            tr.style.display = (name.includes(q) || phone.includes(q)) ? '' : 'none';
        });
    });

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

    // initial focus
    formCustomer.querySelector('.input-name').focus();
});
</script>

@endsection
