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

@section('css')
<!-- Add DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css">
<style>
    .selected {
        background-color: #acbad4 !important;
    }
    .product-thumbnail-small {
        max-width: 50px;
        height: auto;
    }
    /* Add these rules */
    .table td,
    .table th {
        text-align: center !important;
        vertical-align: middle !important;
    }
</style>
@endsection

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

<!-- Main content -->
<section class="content no-print">
    <div class="row">
        @component('components.filters', ['title' => __('report.filters')])
            <div class="col-md-2 mx-2">
                <a href="/additional_reports/wa_search" style="text-decoration: none;">
                    <button class="form-control bg-dark button" 
                            style="background: #e10f28 !important; color: white; border-radius: 50px; border-style: none; font-weight: 700;">
                        New Report
                    </button>
                </a>
            </div>
            <div class="col-md-3 mx-3">
                <button class="form-control bg-dark button" 
                        style="background: green !important; color: white; border-radius: 50px; border-style: none; font-weight: 700;" 
                        id="shareRows">
                    Share Selected Rows via WhatsApp
                </button>
            </div>
        @endcomponent
    </div>

    <div class="row">
        <div class="col-md-12">
            <div class="box">
                <div class="box-body">
                    <div class="table-responsive">
                        <table id="dtBasicExample" class="table table-bordered table-striped text-center">
                            <thead>
                                <tr>
                                    <th>Image</th>
                                    <th style="display:none">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>
                                @foreach($products as $product)
                                    <tr>
                                        <td><img src="https://static-egy.com/uploads/img/{{$product->product_image}}" alt="Product image" class="product-thumbnail-small"></td>
                                        <td style="display:none">https://static-egy.com/uploads/img/{{$product->product_image}}</td>
                                        <td>{{$product->product_sku}}</td>
                                        <td>{{$product->product_name}}</td>
                                        <td>{{$product->qty_available}}</td>
                                        <td>{{$product->sell_price_inc_tax}}</td>
                                        <td>{{$product->business_location}}</td>
                                        <td>{{$product->brand_names}}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
@endsection

@section('javascript')
<!-- Add required JS libraries -->
<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 src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.15/jspdf.plugin.autotable.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize DataTable
    var table = $('#dtBasicExample').DataTable({
        aLengthMenu: [["All", 10, 25, 50, 75, -1], ["All", 10, 25, 50, 75, 'All']],
        iDisplayLength: -1,
        order: [[6, 'asc']],
    });

    var selectedRows = [];

    // Handle row selection
    $('#dtBasicExample tbody').on('click', 'tr', function() {
        $(this).toggleClass('selected');
        selectedRows = table.rows('.selected').data().toArray();
        console.log(selectedRows);
    });

    // Handle share button click
    // $('#shareRows').on('click', async function() {
    //     if (selectedRows.length === 0) {
    //         alert('Please select rows to share.');
    //         return;
    //     }
    
    //     try {
    //         // Create PDF document
    //         const { jsPDF } = window.jspdf;
    //         const doc = new jsPDF();
    
    //         // Add company header
    //         doc.setFontSize(18);
    //         doc.setTextColor(40, 40, 40);
    //         doc.text('Products Report', 15, 15);
            
    //         // Add generation date
    //         doc.setFontSize(10);
    //         doc.setTextColor(100, 100, 100);
    //         doc.text('Generated: ' + new Date().toLocaleString(), 15, 22);
    
    //         // Prepare data for PDF table
    //         const tableData = selectedRows.map(row => {
    //             const price = parseFloat(row[5]);
    //             const roundedPrice = Math.ceil(price / 5) * 5;
                
    //             const fullImageUrl = row[1]; // Full image URL
    //             const imageFilename = fullImageUrl.split('/').pop(); // Get just the filename
                
    //             return [
    //                 fullImageUrl,
    //                 row[2], // SKU
    //                 row[3], // Name
    //                 roundedPrice.toString(), // Rounded Price
    //                 row[6]  // Location
    //             ];
    //         });
    
    //         // Add table to PDF
    //         doc.autoTable({
    //             startY: 30,
    //             head: [['Image', 'SKU', 'Product Name', 'Price', 'Location']],
    //             body: tableData,
    //             theme: 'grid',
    //             styles: {
    //                 fontSize: 9,
    //                 cellPadding: 5
    //             },
    //             headStyles: {
    //                 fillColor: [51, 122, 183],
    //                 textColor: 255,
    //                 fontSize: 10,
    //                 fontStyle: 'bold'
    //             },
    //             alternateRowStyles: {
    //                 fillColor: [245, 245, 245]
    //             },
    //             didDrawCell: function(data) {
    //                 // Check if it's the last cell of the first row
    //                 if (data.section === 'body' && 
    //                     data.row.index === 0 && 
    //                     data.column.index === data.table.body[0].length - 1) {
                        
    //                     // Get the full image URL from the original selected row
    //                     const fullImageUrl = selectedRows[0][1];
                        
    //                     // Draw the URL on a new row
    //                     const urlText = `Full Image URL: ${fullImageUrl}`;
    //                     const pageWidth = doc.internal.pageSize.width;
    //                     const margin = data.settings.margin.left;
                        
    //                     doc.setFontSize(8);
    //                     doc.setTextColor(100, 100, 100);
                        
    //                     // Draw the full URL text
    //                     doc.text(urlText, margin, data.cell.y + data.cell.height + 10);
    //                 }
    //             }
    //         });
    
    //         // Generate blob from PDF
    //         const pdfBlob = doc.output('blob');
            
    //         // Create FormData and append PDF
    //         const formData = new FormData();
    //         formData.append('pdf', pdfBlob, 'products_report.pdf');
    
    //         // Upload PDF to server
    //         const response = await fetch('/additional_reports/upload-pdf', {
    //             method: 'POST',
    //             body: formData,
    //             headers: {
    //                 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
    //                 'X-Requested-With': 'XMLHttpRequest'
    //             }
    //         });
    
    //         const responseText = await response.text();
            
    //         // Try to extract JSON from the response
    //         let jsonData;
    //         try {
    //             // Look for JSON object in the response
    //             const jsonMatch = responseText.match(/\{[^{]*"success":[^}]*\}/);
    //             if (jsonMatch) {
    //                 jsonData = JSON.parse(jsonMatch[0]);
    //             } else {
    //                 throw new Error('No JSON data found in response');
    //             }
    //         } catch (e) {
    //             console.error('Error parsing response:', responseText);
    //             throw new Error('Failed to parse server response');
    //         }
    
    //         if (!jsonData.success) {
    //             throw new Error(jsonData.error || 'Server error occurred');
    //         }
    
    //         if (!jsonData.pdfUrl) {
    //             throw new Error('No PDF URL returned from server');
    //         }
    
    //         // Share via WhatsApp
    //         const message = 'Please check our products catalog: ' + jsonData.pdfUrl;
    //         const whatsappLink = 'https://wa.me/?text=' + encodeURIComponent(message);
    //         window.open(whatsappLink, '_blank');
    
    //     } catch (error) {
    //         console.error('Detailed error:', error);
    //         alert('Error generating PDF: ' + (error.message || 'Unknown error occurred'));
    //     }
    // });
    
    
    // Handle share button click
    $('#shareRows').on('click', async function() {
        
        if (selectedRows.length === 0) {
            alert('Please select rows to share.');
            return;
        }
    
        try {
            // Create a map to track SKUs and keep only unique entries
            const uniqueProductMap = new Map();
            
            // Process selected rows to keep only unique SKUs
            // This will keep the last selected instance of each SKU
            selectedRows.forEach(row => {
                const sku = row[2]; // SKU is at index 2
                uniqueProductMap.set(sku, row);
            });
            
            // Get unique products array from the map values
            const uniqueProducts = Array.from(uniqueProductMap.values());
            
            // Prepare data for sharing using only unique products
            const productsData = uniqueProducts.map(row => {
                return {
                    image_url: row[1], // Image URL
                    sku: row[2],       // SKU
                    name: row[3],      // Product Name
                    price: row[5],     // Price
                    stock: row[4],     // Stock
                    location: row[6]   // Location
                };
            });
    
            // 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 = 'Please check our products catalog: ' + result.shareUrl;
            const whatsappLink = 'https://wa.me/?text=' + encodeURIComponent(message);
            window.open(whatsappLink, '_blank');
            
            // Clear selections after sharing
            selectedRows = []; // Empty the array
            $('#dtBasicExample tbody tr').removeClass('selected'); // Remove visual selection
            table.draw(); // Redraw table if needed
            
            // Redirect after 1 second (adjust if needed)
            setTimeout(function() {
                window.location.href = "https://static-egy.com/additional_reports/wa_search";
            }, 1000);
        
        } catch (error) {
            console.error('Detailed error:', error);
            alert('Error creating share link: ' + (error.message || 'Unknown error occurred'));
        }
    });
    
});
</script>
@endsection