<?php $__env->startSection('title', $title . ' | Saai Cards'); ?>

<?php $__env->startSection('content'); ?>
<div class="max-w-container-max mx-auto space-y-lg">
    <!-- Breadcrumbs & Title Section -->
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-md mb-xl">
        <div>
            <nav class="flex items-center gap-xs text-secondary font-label-md text-label-md mb-xs">
                <a class="hover:text-primary transition-colors" href="#">Masters</a>
                <span class="material-symbols-outlined text-[16px]">chevron_right</span>
                <span class="text-on-surface"><?php echo e($title); ?></span>
            </nav>
            <h2 class="font-headline-md text-headline-md text-on-surface"><?php echo e($title); ?></h2>
            <p class="font-body-md text-body-md text-secondary">Manage and organize <?php echo e(strtolower($title)); ?> for workflows.</p>
        </div>
        <button onclick="addRecord()" class="bg-primary text-on-primary px-lg py-sm rounded-xl font-label-md text-label-md flex items-center gap-sm hover:shadow-lg transition-all active:scale-[0.98]">
            <span class="material-symbols-outlined text-[20px]">add_circle</span>
            Add New Record
        </button>
    </div>

    <!-- Master Table Section -->
    <div class="master-card bg-surface-container-lowest rounded-xl overflow-hidden border border-surface-container">
        <!-- Table Filters/Header -->
        <div class="p-md border-b border-surface-container flex flex-wrap items-center justify-between gap-md bg-white">
            <div class="flex items-center gap-sm">
                <div class="flex bg-surface-container-low rounded-lg p-1" id="statusFilterGroup">
                    <button class="px-md py-xs bg-white text-primary font-bold shadow-sm rounded-md font-label-md text-label-md filter-btn" data-status="">All</button>
                    <button class="px-md py-xs text-secondary hover:text-on-surface transition-colors font-label-md text-label-md filter-btn" data-status="1">Active</button>
                    <button class="px-md py-xs text-secondary hover:text-on-surface transition-colors font-label-md text-label-md filter-btn" data-status="0">Archived</button>
                </div>
            </div>
        </div>

        <!-- The Table -->
        <div class="overflow-x-auto p-md pt-0">
            <table id="dataTable" class="w-full text-left border-collapse stripe hover dataTable">
                <thead>
                    <tr class="bg-surface-container-low/50">
                        <th width="5%" class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container">#</th>
                        <th class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container">Name</th>
                        <?php if($slug === 'booking-categories'): ?>
                        <th width="12%" class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container text-right">Price</th>
                        <?php endif; ?>
                        <th class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container">Description</th>
                        <th width="10%" class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container text-center">Order</th>
                        <th width="15%" class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container">Status</th>
                        <th width="15%" class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container">Created</th>
                        <th width="10%" class="px-lg py-md font-label-md text-label-md text-secondary uppercase tracking-wider border-b border-surface-container text-right">Actions</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add/Edit Modal (Tailwind Style) -->
<div class="fixed inset-0 bg-on-surface/40 backdrop-blur-sm z-50 hidden flex items-center justify-center p-md" id="modal-overlay">
    <div class="bg-white rounded-2xl w-full max-w-md master-card p-xl shadow-2xl transform transition-all">
        <div class="flex items-center justify-between mb-lg">
            <h3 class="font-headline-sm text-headline-sm text-on-surface" id="modalTitle">Add Record</h3>
            <button class="p-xs rounded-full hover:bg-surface-container transition-colors text-secondary" onclick="toggleModal()">
                <span class="material-symbols-outlined">close</span>
            </button>
        </div>
        <form id="masterForm" class="space-y-lg">
            <input type="hidden" id="record_id" name="id">
            
            <div>
                <label class="block font-label-md text-label-md text-on-surface-variant mb-xs">Name <span class="text-error">*</span></label>
                <input class="w-full border-outline-variant border rounded-lg p-sm text-body-md focus:border-primary focus:ring-2 focus:ring-primary/10 transition-all outline-none" id="name" name="name" placeholder="e.g. Standard" type="text" required/>
            </div>

            <?php if($slug === 'booking-categories'): ?>
            <div>
                <label class="block font-label-md text-label-md text-on-surface-variant mb-xs">Price (₹) <span class="text-error">*</span></label>
                <input class="w-full border-outline-variant border rounded-lg p-sm text-body-md focus:border-primary focus:ring-2 focus:ring-primary/10 transition-all outline-none" id="price" name="price" placeholder="0.00" type="number" step="0.01" min="0" value="0"/>
                <p class="mt-1 text-[11px] text-secondary">Used to auto-calculate quotation amount (Price × Quantity).</p>
            </div>
            <?php endif; ?>
            
            <div>
                <label class="block font-label-md text-label-md text-on-surface-variant mb-xs">Description</label>
                <textarea class="w-full border-outline-variant border rounded-lg p-sm text-body-md h-24 focus:border-primary focus:ring-2 focus:ring-primary/10 transition-all outline-none resize-none" id="description" name="description" placeholder="Brief description..."></textarea>
            </div>
            
            <div class="grid grid-cols-2 gap-md">
                <div>
                    <label class="block font-label-md text-label-md text-on-surface-variant mb-xs">Sort Order</label>
                    <input class="w-full border-outline-variant border rounded-lg p-sm text-body-md focus:border-primary focus:ring-2 focus:ring-primary/10 transition-all outline-none" type="number" id="sort_order" name="sort_order" placeholder="0" value="0"/>
                </div>
                <div class="flex flex-col justify-center pt-md">
                    <label class="flex items-center cursor-pointer gap-sm">
                        <div class="relative inline-block w-8 h-4 align-middle select-none transition duration-200 ease-in">
                            <input type="checkbox" id="status" name="status" value="1" class="toggle-checkbox absolute block w-0 h-0 opacity-0" checked/>
                            <div class="toggle-label block overflow-hidden h-4 rounded-full bg-outline-variant cursor-pointer relative"></div>
                        </div>
                        <span class="font-label-md text-label-md text-on-surface-variant" id="status_label_text">Active</span>
                    </label>
                </div>
            </div>
            
            <div class="flex items-center gap-md pt-md">
                <button type="button" class="flex-1 py-sm border border-outline-variant rounded-xl font-label-md text-label-md text-secondary hover:bg-surface-container-low transition-colors" onclick="toggleModal()">Cancel</button>
                <button type="submit" class="flex-1 py-sm bg-primary text-on-primary rounded-xl font-label-md text-label-md hover:shadow-lg transition-all" id="saveBtn">Save Record</button>
            </div>
        </form>
    </div>
</div>

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

<?php echo $__env->yieldPushContent('scripts'); ?>
<script>
    let customStatusFilter = '';
    
    function toggleModal() {
        const modal = document.getElementById('modal-overlay');
        modal.classList.toggle('hidden');
    }

    document.addEventListener("DOMContentLoaded", function() {
        let table = $('#dataTable').DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: "<?php echo e(url('master/'.$slug)); ?>",
                data: function(d) {
                    d.status = customStatusFilter;
                }
            },
            columns: [
                {data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false, render: function(data) {
                    return '<span class="text-secondary font-label-md text-label-md">'+data+'</span>';
                }},
                {data: 'name', name: 'name', render: function(data) {
                    return '<div class="flex items-center gap-sm"><div class="w-8 h-8 rounded-full bg-secondary-container flex items-center justify-center font-bold text-on-secondary-container text-[10px]">'+data.substring(0,2).toUpperCase()+'</div><span class="font-label-md text-label-md text-on-surface">'+data+'</span></div>';
                }},
                <?php if($slug === 'booking-categories'): ?>
                {data: 'price', name: 'price', className: 'text-right', render: function(data) {
                    return '<span class="font-label-md text-label-md text-on-surface font-bold">₹'+parseFloat(data || 0).toFixed(2)+'</span>';
                }},
                <?php endif; ?>
                {data: 'description', name: 'description', orderable: false, render: function(data) {
                    return '<span class="font-body-md text-body-md text-on-surface-variant line-clamp-2" title="'+(data ? data : '')+'">'+(data ? data : '<span class="italic text-outline">No description</span>')+'</span>';
                }},
                {data: 'sort_order', name: 'sort_order', className: 'text-center', render: function(data) {
                    return '<span class="inline-flex items-center justify-center w-8 h-8 bg-surface-container rounded-full font-label-md text-label-md text-secondary">'+data+'</span>';
                }},
                {data: 'status', name: 'status', orderable: false, searchable: false, render: function(data, type, row) {
                    let isChecked = data == 1 ? 'checked' : '';
                    let labelText = data == 1 ? '<span class="ml-sm font-label-sm text-[12px] font-bold text-green-600 bg-green-50 px-2 py-1 rounded-md">Active</span>' : '<span class="ml-sm font-label-sm text-[12px] font-bold text-outline bg-gray-50 px-2 py-1 rounded-md">Archived</span>';
                    
                    return `<div class="flex items-center">
                                <div class="relative inline-block w-8 h-4 align-middle select-none transition duration-200 ease-in">
                                    <input type="checkbox" class="toggle-checkbox absolute block w-0 h-0 opacity-0 status-toggle" data-id="${row.id}" ${isChecked}/>
                                    <label class="toggle-label block overflow-hidden h-4 rounded-full bg-outline-variant cursor-pointer relative"></label>
                                </div>
                                ${labelText}
                            </div>`;
                }},
                {data: 'created_at', name: 'created_at', render: function(data) {
                    return '<span class="font-body-md text-[13px] text-secondary">'+data+'</span>';
                }},
                {data: 'action', name: 'action', orderable: false, searchable: false, className: 'text-right', render: function(data, type, row) {
                    // Extract data for edit securely
                    let escName = row.name ? String(row.name).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;') : '';
                    let escDesc = row.description ? String(row.description).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;') : '';
                    let priceAttr = <?php echo e($slug === 'booking-categories' ? 'true' : 'false'); ?> ? ` data-price="${row.price || 0}"` : '';
                    
                    return `<div class="flex items-center justify-end gap-xs">
                                <button class="w-8 h-8 flex items-center justify-center rounded-lg bg-surface hover:bg-primary-container hover:text-on-primary text-secondary hover:shadow-md transition-all edit-btn" data-id="${row.id}" data-name="${escName}" data-desc="${escDesc}" data-sort="${row.sort_order}" data-status="${row.status}"${priceAttr} title="Edit">
                                    <span class="material-symbols-outlined text-[18px]">edit</span>
                                </button>
                                <button class="w-8 h-8 flex items-center justify-center rounded-lg bg-surface hover:bg-error hover:text-on-error text-secondary hover:shadow-md transition-all delete-btn" data-id="${row.id}" title="Delete">
                                    <span class="material-symbols-outlined text-[18px]">delete</span>
                                </button>
                            </div>`;
                }},
            ],
            dom: '<"flex justify-between items-center mb-4 px-md"lf>rt<"flex justify-between items-center mt-4 px-md"ip>',
            pageLength: 25,
            responsive: true,
            createdRow: function(row, data, dataIndex) {
                $(row).addClass('hover:bg-surface-container-low transition-colors duration-150');
                $(row).find('td').addClass('px-lg py-md border-b border-surface-container');
            }
        });

        // Filter button clicks
        $('.filter-btn').on('click', function() {
            $('.filter-btn').removeClass('bg-white text-primary font-bold shadow-sm rounded-md').addClass('text-secondary hover:text-on-surface');
            $(this).removeClass('text-secondary hover:text-on-surface').addClass('bg-white text-primary font-bold shadow-sm rounded-md');
            customStatusFilter = $(this).data('status');
            table.draw();
        });

        // Add Record
        window.addRecord = function() {
            $('#masterForm')[0].reset();
            $('#record_id').val('');
            $('#modalTitle').text('Add <?php echo e($title); ?>');
            $('#status').prop('checked', true);
            $('#status_label_text').text('Active');
            <?php if($slug === 'booking-categories'): ?>
            $('#price').val(0);
            <?php endif; ?>
            toggleModal();
        }

        // Edit Record
        $('body').on('click', '.edit-btn', function () {
            let id = $(this).data('id');
            $('#record_id').val(id);
            $('#name').val($(this).data('name'));
            $('#description').val($(this).data('desc'));
            $('#sort_order').val($(this).data('sort'));
            <?php if($slug === 'booking-categories'): ?>
            $('#price').val($(this).data('price') || 0);
            <?php endif; ?>
            
            let status = $(this).data('status');
            if(status == 1) {
                $('#status').prop('checked', true);
                $('#status_label_text').text('Active');
            } else {
                $('#status').prop('checked', false);
                $('#status_label_text').text('Inactive');
            }
            
            $('#modalTitle').text('Edit <?php echo e($title); ?>');
            toggleModal();
        });

        // Form Submit
        $('#masterForm').on('submit', function (e) {
            e.preventDefault();
            let id = $('#record_id').val();
            let url = id ? "<?php echo e(url('master/'.$slug)); ?>/" + id : "<?php echo e(url('master/'.$slug)); ?>";
            let type = id ? "PUT" : "POST";
            let btn = $('#saveBtn');
            
            btn.prop('disabled', true).text('Saving...');
            
            // Fix checkbox value if unchecked
            let formData = $(this).serializeArray();
            if(!$('#status').is(':checked')) {
                formData.push({name: 'status', value: 0});
            }
            
            $.ajax({
                data: $.param(formData),
                url: url,
                type: type,
                success: function (data) {
                    toggleModal();
                    table.draw();
                    Swal.fire({icon: 'success', title: 'Success', text: data.message, timer: 1500, showConfirmButton: false});
                    btn.prop('disabled', false).text('Save Record');
                },
                error: function (xhr) {
                    btn.prop('disabled', false).text('Save Record');
                    let msg = 'Something went wrong!';
                    if(xhr.responseJSON && xhr.responseJSON.message) msg = xhr.responseJSON.message;
                    Swal.fire({icon: 'error', title: 'Error', text: msg});
                }
            });
        });

        // Delete Record
        $('body').on('click', '.delete-btn', function () {
            let id = $(this).data('id');
            Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ba1a1a',
                cancelButtonColor: '#737686',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: "<?php echo e(url('master/'.$slug)); ?>/" + id,
                        type: 'DELETE',
                        success: function (data) {
                            table.draw();
                            Swal.fire({icon: 'success', title: 'Deleted!', text: data.message, timer: 1500, showConfirmButton: false});
                        },
                        error: function (xhr) {
                            Swal.fire({icon: 'error', title: 'Error', text: 'Cannot delete this record.'});
                        }
                    });
                }
            });
        });

        // Toggle Status in Table
        $('body').on('change', '.status-toggle', function () {
            let id = $(this).data('id');
            let status = $(this).prop('checked') ? 1 : 0;
            let labelSpan = $(this).closest('div').next('span');
            
            if(status == 1) {
                labelSpan.text('Active').removeClass('text-outline').addClass('text-primary');
            } else {
                labelSpan.text('Inactive').removeClass('text-primary').addClass('text-outline');
            }
            
            $.ajax({
                url: "<?php echo e(url('master/'.$slug)); ?>/" + id + "/status",
                type: 'PATCH',
                data: { status: status },
                success: function (data) {
                    Swal.fire({
                        toast: true, position: 'top-end', icon: 'success', title: data.message, showConfirmButton: false, timer: 1500
                    });
                }
            });
        });

        // Toggle label text inside modal
        $('#status').on('change', function() {
            if($(this).is(':checked')) {
                $('#status_label_text').text('Active');
            } else {
                $('#status_label_text').text('Inactive');
            }
        });
    });
</script>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH E:\xampp\htdocs\saai-cards\resources\views/master/index.blade.php ENDPATH**/ ?>