@extends('layouts.app')
@section('title', 'WA Search (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 (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-3">
                    <div class="form-group">
                        <label for="business_locations">Select Business Location:</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">
                                    <select id="business_locations" name="business_locations[]" class="form-control bg-dark" multiple="multiple">
                                        <option value="" selected>All</option>
                                        @foreach($business_locations as $business_location)
                                        @php
                                            $selected = !empty($user_default_locations) && 
                                                         stripos($business_location->name, $user_default_locations) !== false ? 
                                                         'selected' : '';
                                        @endphp
                                        <option value="{{$business_location->id}}" {{$selected}}>{{$business_location->name}} ({{ $business_location->location_id }})</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="brands">Select Brand:</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">
                                    <select id="brands" name="brands[]" class="form-control bg-dark" multiple="multiple">
                                        <option value="" selected>All</option>
                                        @foreach($brands as $brand)
                                        <option value="{{$brand->id}}">{{$brand->name}}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="categories">Select Category:</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">
                                    <select id="categories" name="categories[]" class="form-control bg-dark" multiple="multiple">
                                        <option value="" selected>All</option>
                                        @foreach($data as $category)
                                            @if($category->parent_id == 0)
                                        <option value="{{$category->id}}">{{$category->name}}</option>
                                            @endif
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="subcategories">Select Sub-Category:</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">
                                    <select id="subcategories" name="subcategories[]" class="form-control bg-dark" multiple="multiple">
                                        <option value="" selected>All</option>
                                        @foreach($data as $subcategory)
                                            @if($subcategory->parent_id != 0)
                                        <option value="{{$subcategory->id}}">{{$subcategory->name}}</option>
                                            @endif
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="product_sku">Product SKU:</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="product_sku" name="product_sku" style="z-index: auto !important;">                    
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="search_products">Search Products:</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="search_products" name="search_products" style="z-index: auto !important;">                    
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <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 Products
                        </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-header with-border">
                    <h3 class="box-title">Search Results</h3>
                    <div class="box-tools">
                        <div class="selection-info">
                            <span id="selection-counter" class="selection-counter">0 products selected</span>
                            <span id="clear-selections" class="clear-selections">Clear selections</span>
                        </div>
                        <button id="shareWhatsApp" class="btn" style="background: green !important; color: white; border-radius: 50px; border-style: none; font-weight: 700;">
                            Share Selected via WhatsApp
                        </button>
                    </div>
                </div>
                <div class="box-body">
                    <div class="table-responsive">
                        <table id="products-table" class="table table-bordered table-striped text-center">
                            <thead>
                                <tr>
                                    <th>Image</th>
                                    <!--<th>Product Image URL</th>-->
                                    <th>SKU</th>
                                    <th>Name</th>
                                    <th>Current Stock</th>
                                    <th>Price</th>
                                    <th>Location(s)</th>
                                    <th>Brand Name(s)</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: [[6, 'asc']],
        });
        
        // Store selected products
        var selectedProducts = new Map();
        
        // Handle Search Button Click
        $('#search-button').on('click', function() {
            performSearch();
        });
        
        // Allow enter key to trigger search
        $('#search_products, #product_sku').on('keypress', function(e) {
            if (e.which === 13) {
                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 = {
                business_locations: $('#business_locations').val(),
                brands: $('#brands').val(),
                categories: $('#categories').val(),
                subcategories: $('#subcategories').val(),
                product_sku: $('#product_sku').val(),
                search_products: $('#search_products').val(),
                _token: $('meta[name="csrf-token"]').attr('content')
            };
            
            // Send AJAX request
            $.ajax({
                url: '/additional_reports/wa_search_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
                        // Image cell (index 0)
                        rowData.push(cells.eq(0).html()); 
                        
                        // // Hidden image URL (index 1)
                        // rowData.push(cells.eq(1).text());
                        
                        // SKU (index 2)
                        rowData.push(cells.eq(2).text());
                        
                        // Name (index 3)
                        rowData.push(cells.eq(3).text());
                        
                        // Stock (index 4)
                        rowData.push(cells.eq(4).text());
                        
                        // Price (index 5)
                        rowData.push(cells.eq(5).text());
                        
                        // Location (index 6)
                        rowData.push(cells.eq(6).text());
                        
                        // Brand Names (index 7)
                        rowData.push(cells.eq(7).text());
                        
                        productsTable.row.add(rowData);
                    });
                    
                    productsTable.draw();
                    
                    // Hide initial message and show results
                    $('#initial-message').hide();
                    $('#results-section').show();
                    
                    // Restore selected state for previously selected products
                    markSelectedRows();
                },
                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>');
                }
            });
        }
        
        // Handle row selection
        $('#products-table tbody').on('click', 'tr', function() {
            var row = productsTable.row(this).data();
            if (row) {
                var sku = row[2]; // SKU is at index 2
                // Extract the image URL from the image tag
                var imgElement = $(row[0]); // Create jQuery object from the HTML string
                var imageUrl = imgElement.attr('src'); // Get the src attribute value
                
                if (selectedProducts.has(sku)) {
                    // If already selected, remove it
                    selectedProducts.delete(sku);
                    $(this).removeClass('selected');
                } else {
                    // Add to selection
                    selectedProducts.set(sku, {
                        image_url: imageUrl, // Image URL
                        sku: row[1],       // SKU
                        name: row[2],      // Product Name
                        stock: row[3],     // Stock
                        price: row[4],     // Price
                        location: row[5]   // Location
                    });
                    $(this).addClass('selected');
                }
                
                // Update selection counter
                updateSelectionCounter();
            }
        });
        
        // Mark rows as selected based on stored selection
        function markSelectedRows() {
            $('#products-table tbody tr').each(function() {
                var row = productsTable.row(this).data();
                if (row && selectedProducts.has(row[2])) {
                    $(this).addClass('selected');
                }
            });
            
            // Update selection counter
            updateSelectionCounter();
        }
        
        // Update selection counter
        function updateSelectionCounter() {
            $('#selection-counter').text(selectedProducts.size + ' products selected');
        }
        
        // Clear selections
        $('#clear-selections').on('click', function() {
            selectedProducts.clear();
            $('#products-table tbody tr').removeClass('selected');
            updateSelectionCounter();
        });
        
        // Handle WhatsApp share button
        $('#shareWhatsApp').on('click', async function() {
            if (selectedProducts.size === 0) {
                alert('Please select at least one product to share.');
                return;
            }
            
            try {
                // Prepare data for sharing
                const productsData = Array.from(selectedProducts.values());
                
                // Send data to server to create public share link
                const response = await fetch('/additional_reports/create-public-share', {
                    method: 'POST',
                    body: JSON.stringify({
                        products: productsData
                    }),
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });
                
                const result = await response.json();
                
                if (!result.success) {
                    throw new Error(result.error || 'Server error occurred');
                }
                
                // Share via WhatsApp
                const message = 'برجاء مراجعه المنتجات المطلوبه ومعرفه السعر والفرع من خلال الرابط الاتي:   ' + result.shareUrl;
                const whatsappLink = 'https://wa.me/?text=' + encodeURIComponent(message);
                window.open(whatsappLink, '_blank');
                
                 // Clear the selected rows
                $('#clear-selections').click();
                
                // Redirect after 1 second
                setTimeout(function() {
                    window.location.href = "https://static-egy.com/additional_reports/wa_search";
                }, 1000);

            } catch (error) {
                console.error('Error creating share link:', error);
                alert('Error creating share link: ' + (error.message || 'Unknown error occurred'));
            }
        });
        
        // Keyboard shortcuts for locations
        $(document).keydown(function(e) {
            // Ctrl+1 for Queen locations
            if ((e.ctrlKey || e.metaKey) && e.which === 49) { // 49 is key code for 1
                handleLocationSelection('queen');
                return false;
            }
            
            // Ctrl+2 for Bustan locations
            if ((e.ctrlKey || e.metaKey) && e.which === 50) { // 50 is key code for 2
                handleLocationSelection('bustan');
                return false;
            }
        });
        
        function handleLocationSelection(pattern) {
            // Get the select element
            const locationSelect = $('#business_locations')[0];
            const selectize = locationSelect.selectize;
            
            // Clear current selections
            selectize.clear();
            
            // Find and select matching options
            selectize.$dropdown_content.find('.option').each(function() {
                const optionText = $(this).text().toLowerCase();
                if (optionText.includes(pattern)) {
                    const value = $(this).data('value');
                    selectize.addItem(value);
                }
            });
        }
    });
</script>
@endsection