@extends('layouts.app')
@section('title', 'WA Search Creation (Beta)')

@section('css')
<!-- Add DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css">
<style>
    .selectize-dropdown, .selectize-dropdown.form-control {
        position: absolute !important;
    }
    .selected {
        background-color: #acbad4 !important;
    }
    .product-thumbnail-small {
        max-width: 50px;
        height: auto;
    }
    .table td,
    .table th {
        text-align: center !important;
        vertical-align: middle !important;
    }
    #results-section {
        display: none;
    }
    .selection-counter {
        font-weight: bold;
        color: green;
        margin-left: 10px;
    }
    .selection-info {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
    }
    .clear-selections {
        margin-left: 10px;
        color: #e10f28;
        cursor: pointer;
    }
</style>
@endsection

@section('content')

<!-- Content Header (Page header) -->
<section class="content-header no-print">
    <h1>WA Search Creation (Beta)</h1>
</section>

<!-- Main content -->
<section class="content no-print">

    <!-- Search Filters -->
    <div class="row">
        <div class="col-md-12">
            @component('components.filters', ['title' => __('report.filters')])
                
                <div class="col-md-8">
                    <div class="form-group">
                        <label for="quotation_token">Quotation Token:</label>
                        <div class="input-group" style="width: 100% !important;">
                            <div class="row">
                                <div class="col-md-3 p-0" style="padding: 0 !important">
                                    <span class="input-group-addon" style="border: none !important;">
                                        <i class="fa fa-search" style="font-size: 20px;"></i>
                                    </span>
                                </div>
                                <div class="col-md-9" style="padding: 0 !important">
                                    <input type="text" class="form-control" id="quotation_token" name="quotation_token" style="z-index: auto !important;">                    
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <button id="search-button" class="button" type="button" style="background: #e10f28 !important; color: white; border-radius: 50px; border-style: none; font-weight: 700; padding: 10px 60px; margin-top: 10px;">
                            Search
                        </button>                
                    </div>
                </div>
            @endcomponent
        </div>
    </div>
    
    <!-- Results Section (initially hidden) -->
    <div id="results-section" class="row">
        <div class="col-md-12">
            <div class="box">
                <div class="box-body">
                    <div class="table-responsive">
                        <table id="products-table" class="table table-bordered table-striped text-center">
                            <thead>
                                <tr>
                                    <th>token</th>
                                    <th>User</th>
                                    <th>Created At</th>
                                    <th>Expire At</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Table will be populated via AJAX -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Initial Message (will be hidden after search) -->
    <div id="initial-message" class="row">
        <div class="col-md-12">
            <div class="nav-tabs-custom">
                <div class="tab-content">
                    <h3 class="text-center">Please select the above data and click on the search button</h3>
                    <h3 class="text-center">برجاء اتمام الاختيارات والضغط على زر البحث</h3>
                </div>
            </div>
        </div>
    </div>
</section>
@endsection

@section('javascript')
<!-- Add required JS libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script>

<script type="text/javascript">
    $(document).ready(function() {
        // Initialize selectize on all select elements
        $('select').selectize({
            sortField: 'text'
        });
        
        // Initialize DataTable
        var productsTable = $('#products-table').DataTable({
            aLengthMenu: [["All", 10, 25, 50, 75, -1], ["All", 10, 25, 50, 75, 'All']],
            iDisplayLength: -1,
            order: [[2, 'asc']],
        });
        
        // Handle Search Button Click
        $('#search-button').on('click', function() {
            performSearch();
        });
 
        // Function to perform search using AJAX
        function performSearch() {
            // Show loading indicator
            $('#initial-message').html('<div class="text-center"><i class="fa fa-spinner fa-spin fa-3x"></i><h3>Loading...</h3></div>');
            
            // Collect form data
            var formData = {
                quotation_token: $('#quotation_token').val(),
                _token: $('meta[name="csrf-token"]').attr('content')
            };
            
            // Send AJAX request
            $.ajax({
                url: '/additional_reports/wa_search_creation_details',
                type: 'POST',
                data: formData,
                success: function(response) {
                    // Clear the table
                    productsTable.clear();
                    
                    // // Parse the HTML to extract product data
                    // var parser = new DOMParser();
                    // var doc = parser.parseFromString(response, "text/html");
                    // var rows = $(doc).find('#dtBasicExample tbody tr');
                    
                    // // Process each row and add to DataTable
                    // rows.each(function() {
                    //     var cells = $(this).find('td');
                    //     var rowData = [];
                        
                    //     // Process each cell individually with proper handling
                    //     // token cell (index 0)
                    //     rowData.push(cells.eq(0).html()); 
                        
                    //     // Username (index 1)
                    //     rowData.push(cells.eq(1).text());
                        
                    //     // created at (index 2)
                    //     rowData.push(cells.eq(2).text());
                        
                    //     // expired at (index 3)
                    //     rowData.push(cells.eq(3).text());
                        
                    //     productsTable.row.add(rowData);
                    // });
                    
                    // Process JSON data directly
                    if (response.data && response.data.length > 0) {
                        response.data.forEach(function(item) {
                            productsTable.row.add([
                                item.token,
                                item.username,
                                item.created_at,
                                item.expires_at
                            ]);
                        });
                    }
                    
                    productsTable.draw();
                    
                    // Hide initial message and show results
                    $('#initial-message').hide();
                    $('#results-section').show();
                
                },
                error: function(xhr, status, error) {
                    console.error('Search error:', error);
                    $('#initial-message').html('<div class="text-center"><h3 class="text-danger">Error loading data. Please try again.</h3></div>');
                }
            });
        }
        
    });
</script>
@endsection