<?php $__env->startSection('title', 'CEYLON THARU TRAVELS | SUB ITINERARIES'); ?>

<?php $__env->startSection('content_admin'); ?>
    <div class="content-wrapper">
        <section class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1>Itineraries for <?php echo e($package->title); ?></h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="<?php echo e(route('packages.index')); ?>">Packages</a></li>
                            <li class="breadcrumb-item active">Itineraries</li>
                        </ol>
                    </div>
                </div>
            </div>
        </section>

        <div class="container-fluid">
            <div class="row mb-3">
                <div class="col-12 d-flex justify-content-between align-items-center">
                    <h3>Sub-Itineraries for: <?php echo e($package->title); ?> — Day <?php echo e($itinerary->day_number); ?>

                        (<?php echo e($itinerary->title); ?>)</h3>
                    <a href="<?php echo e(route('packages.itineraries', $package->id)); ?>" class="btn btn-secondary">Back to
                        Itineraries</a>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <strong>Add new list item</strong>
                        </div>
                        <div class="card-body">
                            <form id="add-sub-form">
                                <?php echo csrf_field(); ?>
                                <div class="mb-3">
                                    <label for="detail">Detail (e.g. "Day 1: ...")</label>
                                    <textarea name="detail" id="detail" class="form-control" rows="3" required></textarea>
                                </div>
                                <button class="btn btn-primary" type="submit">Add Item</button>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <strong>Existing list items</strong>
                        </div>
                        <div class="card-body">
                            <ul class="list-group" id="sub-list">
                                <?php $__empty_1 = true; $__currentLoopData = $subItineraries; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $sub): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                    <li class="list-group-item d-flex justify-content-between align-items-start"
                                        data-id="<?php echo e($sub->id); ?>">
                                        <div class="ms-2 me-auto">
                                            <div class="fw-bold"><?php echo e($sub->order); ?>.</div>
                                            <div class="sub-detail"><?php echo e($sub->detail); ?></div>
                                        </div>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <button class="btn btn-outline-secondary move-up" title="Move up">↑</button>
                                            <button class="btn btn-outline-secondary move-down" title="Move down">↓</button>
                                            
                                            <button class="btn btn-danger delete-sub" title="Delete">Delete</button>
                                        </div>
                                    </li>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                    <li class="list-group-item">No list items yet.</li>
                                <?php endif; ?>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            (function() {
                const packageId = <?php echo e($package->id); ?>;
                const itineraryId = <?php echo e($itinerary->id); ?>;

                // Helper to build route URLs
                function route(name, params = {}) {
                    // Minimal helper: replace tokens. Note routes are registered under the '/admin' prefix.
                    let urlTemplates = {
                        store: '/admin/packages/{package}/itineraries/{itinerary}/sub-itineraries',
                        update: '/admin/packages/{package}/itineraries/{itinerary}/sub-itineraries/{subItinerary}',
                        destroy: '/admin/packages/{package}/itineraries/{itinerary}/sub-itineraries/{subItinerary}',
                        reorder: '/admin/packages/{package}/itineraries/{itinerary}/sub-itineraries/reorder'
                    };
                    let url = urlTemplates[name];
                    Object.keys(params).forEach(k => {
                        url = url.replace('{' + k + '}', params[k]);
                    });
                    return url;
                }

                function csrfToken() {
                    return document.querySelector('meta[name="csrf-token"]').getAttribute('content');
                }

                // Helper to parse responses robustly (handles JSON or HTML/error text)
                function parseResponse(response) {
                    return response.text().then(text => {
                        // Try to parse JSON if possible
                        try {
                            const json = text ? JSON.parse(text) : {};
                            if (!response.ok) throw json;
                            return json;
                        } catch (e) {
                            // If response.ok but not JSON, return empty object
                            if (response.ok) {
                                return {};
                            }
                            // Non-ok and not JSON -> return text as an error
                            throw { message: text || 'Request failed' };
                        }
                    });
                }

                // Add
                document.getElementById('add-sub-form').addEventListener('submit', function(e) {
                    e.preventDefault();
                    const detail = document.getElementById('detail').value.trim();
                    if (!detail) return alert('Detail required');

                    fetch(route('store', {
                        package: packageId,
                        itinerary: itineraryId
                    }), {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': csrfToken(),
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({
                            detail
                        })
                    }).then(parseResponse).then(json => {
                        if (json.success) {
                            addListItemToDom(json.subItinerary);
                            document.getElementById('detail').value = '';
                        } else {
                            // Show validation messages if present
                            if (json.errors) {
                                const msg = Object.values(json.errors).flat().join('\n');
                                alert(msg);
                            } else {
                                alert('Error adding item');
                            }
                        }
                    }).catch(err => {
                        console.error(err);
                        if (err && err.errors) {
                            const msg = Object.values(err.errors).flat().join('\n');
                            alert(msg);
                        } else if (err && err.message) {
                            alert(err.message);
                        } else {
                            alert('Request failed');
                        }
                    });
                });

                // Add new item to DOM
                function addListItemToDom(item) {
                    const ul = document.getElementById('sub-list');
                    const li = document.createElement('li');
                    li.className = 'list-group-item d-flex justify-content-between align-items-start';
                    li.dataset.id = item.id;
                    li.innerHTML = `
				<div class="ms-2 me-auto">
					<div class="fw-bold">${item.order}.</div>
					<div class="sub-detail">${escapeHtml(item.detail)}</div>
				</div>
				<div class="btn-group btn-group-sm" role="group">
					<button class="btn btn-outline-secondary move-up" title="Move up">↑</button>
					<button class="btn btn-outline-secondary move-down" title="Move down">↓</button>
					
					<button class="btn btn-danger delete-sub" title="Delete">Delete</button>
				</div>
			`;
                    ul.appendChild(li);
                }

                // Event delegation for edit/delete/move
                document.getElementById('sub-list').addEventListener('click', function(e) {
                    const li = e.target.closest('li[data-id]');
                    if (!li) return;
                    const id = li.dataset.id;

                    if (e.target.matches('.delete-sub')) {
                        if (!confirm('Delete this item?')) return;
                        fetch(route('destroy', {
                            package: packageId,
                            itinerary: itineraryId,
                            subItinerary: id
                        }), {
                            method: 'DELETE',
                            headers: {
                                'X-CSRF-TOKEN': csrfToken(),
                                'Accept': 'application/json'
                            }
                        }).then(parseResponse).then(json => {
                            if (json.success) {
                                li.remove();
                                rebuildOrderOnServer();
                            } else {
                                alert('Delete failed');
                            }
                        }).catch(err => {
                            console.error(err);
                            if (err && err.message) alert(err.message);
                            else alert('Delete failed');
                        });
                    }

                    if (e.target.matches('.edit-sub')) {
                        document.getElementById('edit-id').value = id;
                        document.getElementById('edit-detail').value = li.querySelector('.sub-detail')
                            .innerText
                            .trim();
                        new bootstrap.Modal(document.getElementById('editModal')).show();
                    }

                    if (e.target.matches('.move-up') || e.target.matches('.move-down')) {
                        const ul = document.getElementById('sub-list');
                        if (e.target.matches('.move-up')) {
                            const prev = li.previousElementSibling;
                            if (prev) ul.insertBefore(li, prev);
                        } else {
                            const next = li.nextElementSibling;
                            if (next) ul.insertBefore(next, li);
                        }
                        rebuildOrderOnServer();
                    }
                });

                // Save edit
                document.getElementById('save-edit').addEventListener('click', function() {
                    const id = document.getElementById('edit-id').value;
                    const detail = document.getElementById('edit-detail').value.trim();
                    if (!detail) return alert('Detail required');

                    fetch(route('update', {
                        package: packageId,
                        itinerary: itineraryId,
                        subItinerary: id
                    }), {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': csrfToken(),
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({
                            detail
                        })
                    }).then(parseResponse).then(json => {
                        if (json.success) {
                            const li = document.querySelector(`#sub-list li[data-id='${id}']`);
                            if (li) li.querySelector('.sub-detail').innerText = json.subItinerary.detail;
                            bootstrap.Modal.getInstance(document.getElementById('editModal')).hide();
                        } else {
                            if (json.errors) {
                                const msg = Object.values(json.errors).flat().join('\n');
                                alert(msg);
                            } else alert('Update failed');
                        }
                    }).catch(err => {
                        console.error(err);
                        if (err && err.message) alert(err.message);
                        else alert('Update failed');
                    });
                });

                // Rebuild order array and send to server
                function rebuildOrderOnServer() {
                    const ids = Array.from(document.querySelectorAll('#sub-list li[data-id]')).map((li,
                    idx) => {
                        // update visible numbering
                        const num = li.querySelector('.fw-bold');
                        if (num) num.innerText = (idx + 1) + '.';
                        return parseInt(li.dataset.id);
                    });

                    fetch(route('reorder', {
                        package: packageId,
                        itinerary: itineraryId
                    }), {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': csrfToken(),
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({
                            order: ids
                        })
                    }).then(parseResponse).then(json => {
                        if (!json.success) alert('Reorder failed');
                    }).catch(err => {
                        console.error(err);
                        if (err && err.message) alert(err.message);
                        else alert('Reorder failed');
                    });
                }

                function escapeHtml(str) {
                    return str.replace(/[&<>\"']/g, function(m) {
                        return ({
                            '&': '&amp;',
                            '<': '&lt;',
                            '>': '&gt;',
                            '\"': '&quot;',
                            "'": '&#39;'
                        })[m];
                    });
                }
            })();
        });
    </script>

<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.admin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\Savi Aby\Desktop\New folder (2)\Tharu_tours_asiri_savi\ceylon_tharu_tours\resources\views/admin/package_iteneries/sub_itineraries.blade.php ENDPATH**/ ?>