@extends('layouts/base_view')
@section('title')
{!! $variables['header_routes'] !!}
@endsection
@section('content')
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-sync-alt"></i>
                            QAD Synchronization Dashboard
                        </h3>
                    </div>
                    <div class="card-body">

                        <!-- Connection Status -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <div class="card card-outline card-warning">
                                    <div class="card-header">
                                        <strong class="mb-0">
                                            <i class="fas fa-plug"></i>
                                            Connection Status
                                        </strong>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-8">
                                                <div id="connection-status">
                                                    <span class="badge badge-secondary">
                                                        <i class="fas fa-question-circle"></i>
                                                        Not Tested
                                                    </span>
                                                    <span id="connection-message" class="ml-2 text-muted">Click "Test Connection" to check QAD API status</span>
                                                </div>
                                                <div id="connection-details" class="mt-2" style="display: none;">
                                                    <small class="text-muted">
                                                        <strong>Last Test:</strong> <span id="last-test-time">-</span><br>
                                                        <strong>API Version:</strong> <span id="api-version">-</span>
                                                    </small>
                                                </div>
                                            </div>
                                            <div class="col-md-4 text-right">
                                                <button type="button" class="btn btn-info btn-sm" id="test-connection-btn">
                                                    <i class="fas fa-plug"></i>
                                                    Test Connection
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Sync Actions -->
                        <div class="row mb-4">
                            <div class="col-md-4">
                                <div class="card card-info">
                                    <div class="card-header">
                                        <strong class="mb-0">
                                            <i class="fas fa-store"></i>
                                            Master Store
                                        </strong>
                                    </div>
                                    <div class="card-body text-center">
                                        <p class="text-muted">Synchronize store data from QAD system</p>
                                        <button type="button" class="btn btn-info btn-sm" id="sync-stores-btn">
                                            <i class="fas fa-sync-alt"></i>
                                            Sync Stores
                                        </button>
                                        <div id="stores-result" class="mt-3" style="display: none;">
                                            <div class="alert">
                                                <strong>Last Sync:</strong><br>
                                                <span id="stores-summary">-</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="card card-info">
                                    <div class="card-header">
                                        <strong class="mb-0">
                                            <i class="fas fa-utensils"></i>
                                            Master Menu
                                        </strong>
                                    </div>
                                    <div class="card-body text-center">
                                        <p class="text-muted">Synchronize menu data from QAD system</p>
                                        <button type="button" class="btn btn-info btn-sm" id="sync-menus-btn">
                                            <i class="fas fa-sync-alt"></i>
                                            Sync Menus
                                        </button>
                                        <div id="menus-result" class="mt-3" style="display: none;">
                                            <div class="alert">
                                                <strong>Last Sync:</strong><br>
                                                <span id="menus-summary">-</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="card card-info">
                                    <div class="card-header">
                                        <strong class="mb-0">
                                            <i class="fas fa-sync"></i>
                                            Sync All
                                        </strong>
                                    </div>
                                    <div class="card-body text-center">
                                        <p class="text-muted">Synchronize all master data at once</p>
                                        <button type="button" class="btn btn-info btn-sm" id="sync-all-btn">
                                            <i class="fas fa-sync"></i>
                                            Sync All Data
                                        </button>
                                        <div id="all-result" class="mt-3" style="display: none;">
                                            <div class="alert">
                                                <strong>Last Full Sync:</strong><br>
                                                <span id="all-summary">-</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Sync Results -->
                        <div class="row">
                            <div class="col-md-8">
                                <div class="card card-outline card-warning">
                                    <div class="card-header">
                                        <strong class="mb-0">
                                            <i class="fas fa-list"></i>
                                            Sync Results
                                        </strong>
                                    </div>
                                    <div class="card-body">
                                        <div id="sync-results-container">
                                            <p class="text-muted text-center">No sync operations performed yet. Click any sync button above to see results.</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="card card-outline card-warning">
                                    <div class="card-header">
                                        <strong class="mb-0">
                                            <i class="fas fa-chart-pie"></i>
                                            Statistics (30 Days)
                                        </strong>
                                    </div>
                                    <div class="card-body">
                                        <div id="sync-statistics">
                                            <p class="text-muted text-center">Loading statistics...</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Sync History -->
                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="card card-outline card-warning">
                                    <div class="card-header">
                                        <strong class="mb-0">
                                            <i class="fas fa-history"></i>
                                            Sync History
                                            <button class="btn btn-sm btn-info float-right" id="refresh-history-btn">
                                                <i class="fas fa-refresh"></i> Refresh
                                            </button>
                                        </strong>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-hover table-sm" id="sync-history-table">
                                                <thead class="bg-warning">
                                                    <tr>
                                                        <th>Date/Time</th>
                                                        <th>Type</th>
                                                        <th>Status</th>
                                                        <th>Duration</th>
                                                        <th>Inserted</th>
                                                        <th>Updated</th>
                                                        <th>Errors</th>
                                                        <th>Triggered By</th>
                                                        <th>Details</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="sync-history-tbody">
                                                    <tr>
                                                        <td colspan="9" class="text-center text-muted">Loading history...</td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

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

<!-- Loading Modal -->
<div class="modal fade" id="loading-modal" tabindex="-1" role="dialog" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-body text-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="sr-only">Loading...</span>
                </div>
                <p class="mt-2 mb-0">Synchronizing data...</p>
                <small class="text-muted">Please wait, this may take a few moments.</small>
            </div>
        </div>
    </div>
</div>
<script>
    $(function() {

        // Load initial data
        loadSyncStatistics();
        loadSyncHistory();

        // Test Connection
        $('#test-connection-btn').click(function() {
            const btn = $(this);
            const originalText = btn.html();

            btn.html('<i class="fas fa-spinner fa-spin"></i> Testing...').prop('disabled', true);

            $.ajax({
                url: '{{ route("qad_sync.test_connection") }}',
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        $('#connection-status').html(
                            '<span class="badge badge-success"><i class="fas fa-check-circle"></i> Connected</span>'
                        );
                        $('#connection-message').text(response.message).removeClass('text-muted').addClass('text-success');
                        $('#connection-details').show();
                        $('#last-test-time').text(new Date(response.timestamp).toLocaleString());
                        $('#api-version').text(response.version || 'N/A');
                    } else {
                        $('#connection-status').html(
                            '<span class="badge badge-danger"><i class="fas fa-times-circle"></i> Failed</span>'
                        );
                        $('#connection-message').text(response.message).removeClass('text-muted').addClass('text-danger');
                    }
                },
                error: function(xhr) {
                    const response = xhr.responseJSON || {};
                    $('#connection-status').html(
                        '<span class="badge badge-danger"><i class="fas fa-times-circle"></i> Error</span>'
                    );
                    $('#connection-message').text(response.message || 'Connection test failed').removeClass('text-muted').addClass('text-danger');
                },
                complete: function() {
                    btn.html(originalText).prop('disabled', false);
                }
            });
        });

        // Sync Stores
        $('#sync-stores-btn').click(function() {
            performSync('stores', $(this));
        });

        // Sync Menus
        $('#sync-menus-btn').click(function() {
            performSync('menus', $(this));
        });

        // Sync All
        $('#sync-all-btn').click(function() {
            performSync('all', $(this));
        });

        // Refresh History
        $('#refresh-history-btn').click(function() {
            loadSyncHistory();
            loadSyncStatistics();
        });

        function performSync(type, btn) {
            const originalText = btn.html();
            const urls = {
                'stores': '{{ route("qad_sync.sync_stores") }}',
                'menus': '{{ route("qad_sync.sync_menus") }}',
                'all': '{{ route("qad_sync.sync_all") }}'
            };

            btn.html('<i class="fas fa-spinner fa-spin"></i> Syncing...').prop('disabled', true);
            $('#loading-modal').modal('show');

            $.ajax({
                url: urls[type],
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    displaySyncResults(type, response);
                    updateSummary(type, response);
                    // Refresh history and statistics after sync
                    setTimeout(function() {
                        loadSyncHistory();
                        loadSyncStatistics();
                    }, 1000);
                },
                error: function(xhr) {
                    const response = xhr.responseJSON || {};
                    displaySyncResults(type, response, true);
                },
                complete: function() {
                    btn.html(originalText).prop('disabled', false);
                    $('#loading-modal').modal('hide');
                }
            });
        }

        function displaySyncResults(type, response, isError = false) {
            // let html = '<div class="alert ' + (isError ? 'alert-danger' : 'alert-success') + '">';
            let html = '<div class="alert">';
            html += '<strong><i class="fas fa-' + (isError ? 'exclamation-triangle' : 'check-circle') + '"></i> ';
            html += type.charAt(0).toUpperCase() + type.slice(1) + ' Sync Results</strong>';

            if (type === 'all' && response.stores && response.menus) {
                // Handle sync all results
                html += '<div class="row">';
                html += '<div class="col-md-6">';
                html += '<strong>Stores:</strong><br>';
                html += 'Inserted: ' + response.stores.inserted + '<br>';
                html += 'Updated: ' + response.stores.updated + '<br>';
                html += 'Errors: ' + response.stores.errors.length;
                html += '</div>';
                html += '<div class="col-md-6">';
                html += '<strong>Menus:</strong><br>';
                html += 'Inserted: ' + response.menus.inserted + '<br>';
                html += 'Updated: ' + response.menus.updated + '<br>';
                html += 'Errors: ' + response.menus.errors.length;
                html += '</div>';
                html += '</div>';
            } else {
                // Handle individual sync results
                html += '<strong>Message:</strong> ' + (response.message || 'Unknown error') + '<br>';
                if (response.inserted !== undefined) {
                    html += '<strong>Inserted:</strong> ' + response.inserted + '<br>';
                }
                if (response.updated !== undefined) {
                    html += '<strong>Updated:</strong> ' + response.updated + '<br>';
                }
                if (response.errors && response.errors.length > 0) {
                    html += '<strong>Errors:</strong> ' + response.errors.length + '<br>';
                    html += '<details><summary>View Errors</summary>';
                    response.errors.forEach(function(error) {
                        html += '<small>' + (error.error || JSON.stringify(error)) + '</small><br>';
                    });
                    html += '</details>';
                }
            }

            html += '<small class="text-muted">Completed at: ' + new Date().toLocaleString() + '</small>';
            html += '</div>';

            $('#sync-results-container').html(html);
        }

        function updateSummary(type, response) {
            if (type === 'stores' && response.inserted !== undefined) {
                $('#stores-result').show();
                $('#stores-summary').text(response.inserted + ' inserted, ' + response.updated + ' updated');
            } else if (type === 'menus' && response.inserted !== undefined) {
                $('#menus-result').show();
                $('#menus-summary').text(response.inserted + ' inserted, ' + response.updated + ' updated');
            } else if (type === 'all' && response.summary) {
                $('#all-result').show();
                $('#all-summary').text(response.summary.total_inserted + ' inserted, ' + response.summary.total_updated + ' updated');
            }
        }

        function loadSyncStatistics() {
            $.ajax({
                url: '{{ route("qad_sync.sync_statistics") }}',
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        displayStatistics(response.statistics);
                    } else {
                        $('#sync-statistics').html('<p class="text-danger">Failed to load statistics</p>');
                    }
                },
                error: function() {
                    $('#sync-statistics').html('<p class="text-danger">Error loading statistics</p>');
                }
            });
        }

        function displayStatistics(stats) {
            let html = '<div class="row">';
            html += '<div class="col-6"><strong>Total Syncs:</strong><br><span class="strong text-primary">' + (stats.total_syncs || 0) + '</span></div>';
            html += '<div class="col-6"><strong>Success Rate:</strong><br><span class="strong text-success">' +
                (stats.total_syncs > 0 ? Math.round((stats.successful_syncs / stats.total_syncs) * 100) : 0) + '%</span></div>';
            html += '</div><hr>';
            html += '<div class="row">';
            html += '<div class="col-6"><strong>Records Synced:</strong><br><span class="text-info">' + (stats.total_records_synced || 0) + '</span></div>';
            html += '<div class="col-6"><strong>Avg Duration:</strong><br><span class="text-warning">' +
                (stats.avg_duration ? Math.round(stats.avg_duration) + 's' : 'N/A') + '</span></div>';
            html += '</div>';

            $('#sync-statistics').html(html);
        }

        function loadSyncHistory() {
            $.ajax({
                url: '{{ route("qad_sync.sync_history") }}',
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        displaySyncHistory(response.logs);
                    } else {
                        $('#sync-history-tbody').html('<tr><td colspan="9" class="text-center text-danger">Failed to load history</td></tr>');
                    }
                },
                error: function() {
                    $('#sync-history-tbody').html('<tr><td colspan="9" class="text-center text-danger">Error loading history</td></tr>');
                }
            });
        }

        function displaySyncHistory(logs) {
            let html = '';

            // Store logs data globally for response details
            window.syncLogsData = {};

            if (logs.length === 0) {
                html = '<tr><td colspan="9" class="text-center text-muted">No sync history available</td></tr>';
            } else {
                logs.forEach(function(log) {
                    // Store log data for modal
                    window.syncLogsData[log.id] = log;

                    const statusBadge = log.status === 'Success' ? 'badge-success' :
                        (log.status === 'Failed' ? 'badge-danger' :
                            (log.status === 'Partial' ? 'badge-secondary' : 'badge-secondary'));

                    // Create combined details button
                    const hasRequest = log.request_details && Object.keys(log.request_details).length > 0;
                    const hasResponse = (log.error_details && log.error_details.length > 0) ||
                        (log.sync_details && Object.keys(log.sync_details).length > 0);

                    let detailsBtn = '<span class="text-muted">-</span>';
                    if (hasRequest || hasResponse) {
                        detailsBtn = '<button class="btn btn-xs btn-outline-info" onclick="showSyncDetails(' + log.id + ')">';
                        detailsBtn += '<i class="fas fa-exchange-alt"></i> View';
                        detailsBtn += '</button>';
                    }

                    html += '<tr>';
                    html += '<td><small>' + log.started_at + '</small></td>';
                    html += '<td><span class="badge badge-info">' + log.sync_type + '</span></td>';
                    html += '<td><span class="badge ' + statusBadge + '">' + log.status + '</span></td>';
                    html += '<td>' + (log.duration_seconds ? parseFloat(log.duration_seconds).toFixed(2) + 's' : '-') + '</td>';
                    html += '<td>' + log.total_inserted + '</td>';
                    html += '<td>' + log.total_updated + '</td>';
                    html += '<td>' + (log.total_errors > 0 ? '<span class="text-danger">' + log.total_errors + '</span>' : '0') + '</td>';
                    html += '<td><small>' + (log.triggered_by || 'System') + '</small></td>';
                    html += '<td>' + detailsBtn + '</td>';
                    html += '</tr>';
                });
            }

            $('#sync-history-tbody').html(html);
        }

        // Store logs data globally for response details
        window.syncLogsData = {};

        // Function to show sync details (request & response)
        window.showSyncDetails = function(logId) {
            const log = window.syncLogsData[logId];
            if (!log) {
                alert('Log details not found');
                return;
            }

            let modalContent = '<div class="modal fade" id="sync-details-modal" tabindex="-1">';
            modalContent += '<div class="modal-dialog modal-xl"><div class="modal-content">';
            modalContent += '<div class="modal-header bg-warning text-white">';
            modalContent += '<strong class="modal-title">QAD Sync Details - ' + log.sync_type.toUpperCase() + '</strong>';
            modalContent += '<button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button></div>';
            modalContent += '<div class="modal-body">';

            // Sync basic info
            modalContent += '<div class="row mb-3">';
            modalContent += '<div class="col-md-12">';
            modalContent += '<div class="card">';
            modalContent += '<div class="card-header card-outline card-warning"><strong class="mb-0">Sync Information</strong></div>';
            modalContent += '<div class="card-body">';
            modalContent += '<div class="row">';
            modalContent += '<div class="col-md-3"><strong>Type:</strong> ' + log.sync_type + '</div>';
            modalContent += '<div class="col-md-3"><strong>Status:</strong> <span class="badge ' +
                (log.status === 'Success' ? 'badge-success' :
                    log.status === 'Failed' ? 'badge-danger' :
                    log.status === 'Partial' ? 'badge-secondary' : 'badge-secondary') + '">' + log.status + '</span></div>';
            modalContent += '<div class="col-md-3"><strong>Started:</strong> ' + log.started_at + '</div>';
            modalContent += '<div class="col-md-3"><strong>Duration:</strong> ' + (log.duration_seconds ? parseFloat(log.duration_seconds).toFixed(2) + 's' : '-') + '</div>';
            modalContent += '</div>';
            modalContent += '<div class="row mt-2">';
            modalContent += '<div class="col-md-3"><strong>From QAD:</strong> ' + log.total_from_qad + '</div>';
            modalContent += '<div class="col-md-3"><strong>Inserted:</strong> ' + log.total_inserted + '</div>';
            modalContent += '<div class="col-md-3"><strong>Updated:</strong> ' + log.total_updated + '</div>';
            modalContent += '<div class="col-md-3"><strong>Errors:</strong> ' + log.total_errors + '</div>';
            modalContent += '</div>';
            modalContent += '</div></div></div></div>';

            // Request & Response columns
            modalContent += '<div class="row">';

            // LEFT COLUMN - REQUEST
            modalContent += '<div class="col-md-6">';
            modalContent += '<div class="card h-100">';
            modalContent += '<div class="card-header bg-warning">';
            modalContent += '<strong class="mb-0"><i class="fas fa-arrow-up"></i> Request to QAD</strong>';
            modalContent += '</div>';
            modalContent += '<div class="card-body" style="max-height: 500px; overflow-y: auto;">';

            if (log.request_details && Object.keys(log.request_details).length > 0) {
                // Request info
                modalContent += '<strong>Request Information</strong>';
                modalContent += '<table class="table table-sm mb-3">';
                modalContent += '<tr><td><strong>Method:</strong></td><td><code>' + (log.request_details.method || 'N/A') + '</code></td></tr>';
                modalContent += '<tr><td><strong>URL:</strong></td><td><code style="word-break: break-all;">' + (log.request_details.url || 'N/A') + '</code></td></tr>';
                modalContent += '<tr><td><strong>Timeout:</strong></td><td>' + (log.request_details.timeout || 'N/A') + 's</td></tr>';
                modalContent += '<tr><td><strong>Timestamp:</strong></td><td>' + (log.request_details.timestamp || 'N/A') + '</td></tr>';
                modalContent += '</table>';

                // Headers
                if (log.request_details.headers) {
                    modalContent += '<strong>Headers</strong>';
                    modalContent += '<table class="table table-sm mb-3">';
                    Object.keys(log.request_details.headers).forEach(function(key) {
                        modalContent += '<tr>';
                        modalContent += '<td><code>' + key + '</code></td>';
                        modalContent += '<td><code style="word-break: break-all;">' + log.request_details.headers[key] + '</code></td>';
                        modalContent += '</tr>';
                    });
                    modalContent += '</table>';
                }

                // Body/Parameters
                if (log.request_details.body || log.request_details.params) {
                    modalContent += '<strong>Body/Parameters</strong>';
                    modalContent += '<pre style="font-size: 11px; background: #f8f9fa; padding: 10px; border-radius: 4px;">';
                    modalContent += JSON.stringify(log.request_details.body || log.request_details.params || {}, null, 2);
                    modalContent += '</pre>';
                }

                // Postman example
                modalContent += '<strong>Postman Example</strong>';
                modalContent += '<div class="alert p-2">';
                modalContent += '<small>';
                modalContent += '<strong>Method:</strong> ' + (log.request_details.method || 'GET') + '<br>';
                modalContent += '<strong>URL:</strong> <code>' + (log.request_details.url || '') + '</code><br>';
                modalContent += '<strong>Headers:</strong><br>';
                if (log.request_details.headers) {
                    Object.keys(log.request_details.headers).forEach(function(key) {
                        modalContent += '<code>' + key + ': ' + log.request_details.headers[key] + '</code><br>';
                    });
                }
                modalContent += '</small>';
                modalContent += '</div>';
            } else {
                modalContent += '<p class="text-muted">No request details available</p>';
            }

            modalContent += '</div></div></div>';

            // RIGHT COLUMN - RESPONSE
            modalContent += '<div class="col-md-6">';
            modalContent += '<div class="card h-100">';
            modalContent += '<div class="card-header bg-warning">';
            modalContent += '<strong class="mb-0"><i class="fas fa-arrow-down"></i> Response from QAD</strong>';
            modalContent += '</div>';
            modalContent += '<div class="card-body" style="max-height: 500px; overflow-y: auto;">';

            // Response timing
            modalContent += '<strong>Response Information</strong>';
            modalContent += '<table class="table table-sm mb-3">';
            modalContent += '<tr><td><strong>Response Time:</strong></td><td>' + (log.qad_response_time ? parseFloat(log.qad_response_time).toFixed(2) + 'ms' : 'N/A') + '</td></tr>';
            modalContent += '<tr><td><strong>Status:</strong></td><td><span class="badge ' +
                (log.status === 'Success' ? 'badge-success' :
                    log.status === 'Failed' ? 'badge-danger' :
                    log.status === 'Partial' ? 'badge-secondary' : 'badge-secondary') + '">' + log.status + '</span></td></tr>';
            modalContent += '<tr><td><strong>Completed:</strong></td><td>' + (log.completed_at || 'N/A') + '</td></tr>';
            modalContent += '</table>';

            // Error details
            if (log.error_details && log.error_details.length > 0) {
                modalContent += '<strong>Error Details</strong>';
                modalContent += '<div style="max-height: 200px; overflow-y: auto;">';
                modalContent += '<table class="table table-hover table-sm">';
                modalContent += '<thead><tr><th>QAD Code</th><th>Error Message</th></tr></thead><tbody>';

                log.error_details.forEach(function(error) {
                    modalContent += '<tr>';
                    modalContent += '<td><code>' + (error.qad_code || error.type || 'N/A') + '</code></td>';
                    modalContent += '<td><small style="word-break: break-word;">' + (error.error || JSON.stringify(error)) + '</small></td>';
                    modalContent += '</tr>';
                });

                modalContent += '</tbody></table></div>';
            }

            // Sync details
            if (log.sync_details && Object.keys(log.sync_details).length > 0) {
                modalContent += '<strong>Sync Details</strong>';
                modalContent += '<pre style="max-height: 200px; overflow-y: auto; font-size: 11px; background: #f8f9fa; padding: 10px; border-radius: 4px;">';
                modalContent += JSON.stringify(log.sync_details, null, 2);
                modalContent += '</pre>';
            }

            if ((!log.error_details || log.error_details.length === 0) &&
                (!log.sync_details || Object.keys(log.sync_details).length === 0)) {
                modalContent += '<p class="text-muted">No response details available</p>';
            }

            modalContent += '</div></div></div>';
            modalContent += '</div>'; // End row

            modalContent += '</div>';
            modalContent += '<div class="modal-footer">';
            modalContent += '<button type="button" class="btn btn-warning btn-sm" data-dismiss="modal">Close</button>';
            modalContent += '</div></div></div></div>';

            // Remove existing modal and add new one
            $('#sync-details-modal').remove();
            $('body').append(modalContent);
            $('#sync-details-modal').modal('show');
        };

    });
</script>
@endsection