@extends('layouts.app')
@section('title', 'Product Sales Summary Report')

@section('content')
<section class="content-header no-print">
    <h1><i class="fa fa-chart-bar"></i> Product Sales Summary Report</h1>
</section>

<section class="content no-print">
    <div class="box box-solid box-primary" id="accordion">
        <div class="box-header with-border" style="cursor: pointer;">
            <h3 class="box-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseFilter">
                    <i class="fa fa-filter" aria-hidden="true"></i> Filters
                </a>
            </h3>
        </div>
        <div id="collapseFilter" class="panel-collapse active collapse in" aria-expanded="true">
            <div class="box-body">
                <form id="product_sales_filter_form" method="GET" action="{{ route('reports.product_sales_summary') }}">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="start_date">Start Date:</label>
                                <input type="text" name="start_date" id="start_date" class="form-control" readonly placeholder="Select start date" value="{{ request('start_date') ?: \Carbon\Carbon::today()->format('Y-m-d') }}">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="end_date">End Date:</label>
                                <input type="text" name="end_date" id="end_date" class="form-control" readonly placeholder="Select end date" value="{{ request('end_date') ?: \Carbon\Carbon::today()->format('Y-m-d') }}">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="export_format">Export:</label>
                                <div class="btn-group" role="group">
                                    <button type="submit" name="export" value="csv" class="btn btn-success">
                                        <i class="fa fa-file-csv"></i> CSV
                                    </button>
                                    <button type="submit" name="export" value="pdf" class="btn btn-danger">
                                        <i class="fa fa-file-pdf"></i> PDF
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-12 text-right">
                            <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i> Apply Filters</button>
                            <a href="{{ route('reports.product_sales_summary') }}" class="btn btn-default"><i class="fa fa-refresh"></i> Clear Filters</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row" style="margin-top: 20px;">
        <div class="col-md-3">
            <div class="info-box bg-gradient-blue">
                <span class="info-box-icon"><i class="fa fa-boxes"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Total Products</span>
                    <span class="info-box-number">{{ $total_products }}</span>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="info-box bg-gradient-green">
                <span class="info-box-icon"><i class="fa fa-chart-line"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Day Sales Value</span>
                    <span class="info-box-number">{{ number_format($day_sales_value, session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}</span>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="info-box bg-gradient-yellow">
                <span class="info-box-icon"><i class="fa fa-calendar"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Month-to-Date Value</span>
                    <span class="info-box-number">{{ number_format($month_to_date_value, session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}</span>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="info-box bg-gradient-red">
                <span class="info-box-icon"><i class="fa fa-percentage"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Performance Ratio</span>
                    <span class="info-box-number">{{ number_format($performance_ratio, 1) }}%</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Product Sales Table -->
    <div class="box box-primary" style="margin-top: 20px;">
        <div class="box-header with-border">
            <h3 class="box-title">Product Sales Summary (Day vs. Month-to-Date)</h3>
        </div>
        <div class="box-body">
            <!-- Desktop/Tablet View -->
            <div class="table-responsive hidden-xs">
                <table id="product_sales_table" class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>SKU</th>
                            <th>Trade Price</th>
                            <th>Day Sales (Qty)</th>
                            <th>Day Sales (Value)</th>
                            <th>Month-to-Date (Qty)</th>
                            <th>Month-to-Date (Value)</th>
                            <th>Performance</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($product_sales_data as $product)
                            <tr>
                                <td>{{ $product['product_name'] }}</td>
                                <td>{{ $product['sku'] }}</td>
                                <td>{{ number_format($product['trade_price'], session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}</td>
                                <td>{{ $product['day_sales_qty'] }}</td>
                                <td>{{ number_format($product['day_sales_value'], session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}</td>
                                <td>{{ $product['month_to_date_qty'] }}</td>
                                <td>{{ number_format($product['month_to_date_value'], session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}</td>
                                <td>
                                    @if($product['performance_ratio'] > 100)
                                        <span class="label label-success"><i class="fa fa-arrow-up"></i> {{ number_format($product['performance_ratio'], 1) }}%</span>
                                    @elseif($product['performance_ratio'] > 50)
                                        <span class="label label-warning"><i class="fa fa-arrow-right"></i> {{ number_format($product['performance_ratio'], 1) }}%</span>
                                    @else
                                        <span class="label label-danger"><i class="fa fa-arrow-down"></i> {{ number_format($product['performance_ratio'], 1) }}%</span>
                                    @endif
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="8" class="text-center">
                                    <div class="alert alert-info">
                                        <i class="fa fa-info-circle"></i> No product sales data found for the selected criteria.
                                    </div>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            <!-- Mobile View -->
            <div class="visible-xs">
                <div id="mobile_product_sales_cards">
                    @forelse($product_sales_data as $product)
                        <div class="card" style="margin-bottom: 15px;">
                            <div class="card-header">
                                <h4 class="card-title">{{ $product['product_name'] }}</h4>
                                <small class="text-muted">SKU: {{ $product['sku'] }}</small>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-xs-6">
                                        <strong>Trade Price:</strong><br>
                                        {{ number_format($product['trade_price'], session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}
                                    </div>
                                    <div class="col-xs-6">
                                        <strong>Day Sales (Qty):</strong><br>
                                        {{ $product['day_sales_qty'] }}
                                    </div>
                                </div>
                                <div class="row" style="margin-top: 10px;">
                                    <div class="col-xs-6">
                                        <strong>Day Sales (Value):</strong><br>
                                        {{ number_format($product['day_sales_value'], session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}
                                    </div>
                                    <div class="col-xs-6">
                                        <strong>Month-to-Date (Qty):</strong><br>
                                        {{ $product['month_to_date_qty'] }}
                                    </div>
                                </div>
                                <div class="row" style="margin-top: 10px;">
                                    <div class="col-xs-6">
                                        <strong>Month-to-Date (Value):</strong><br>
                                        {{ number_format($product['month_to_date_value'], session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}
                                    </div>
                                    <div class="col-xs-6">
                                        <strong>Performance:</strong><br>
                                        @if($product['performance_ratio'] > 100)
                                            <span class="label label-success"><i class="fa fa-arrow-up"></i> {{ number_format($product['performance_ratio'], 1) }}%</span>
                                        @elseif($product['performance_ratio'] > 50)
                                            <span class="label label-warning"><i class="fa fa-arrow-right"></i> {{ number_format($product['performance_ratio'], 1) }}%</span>
                                        @else
                                            <span class="label label-danger"><i class="fa fa-arrow-down"></i> {{ number_format($product['performance_ratio'], 1) }}%</span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </div>
                    @empty
                        <div class="alert alert-info">
                            <i class="fa fa-info-circle"></i> No product sales data found for the selected criteria.
                        </div>
                    @endforelse
                </div>
            </div>
        </div>
    </div>
</section>
@stop

@section('javascript')
<script>
    $(function() {
        // Date pickers
        $('#start_date, #end_date').datepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayHighlight: true
        });
        
        // Auto-submit form when dates change
        $('#start_date, #end_date').on('changeDate', function() {
            $('#product_sales_filter_form').submit();
        });

        // Initialize DataTable for desktop/tablet view
        $('#product_sales_table').DataTable({
            "pageLength": 25,
            "order": [[7, "desc"]], // Sort by performance ratio descending
            "language": {
                "search": "Search:",
                "lengthMenu": "Show _MENU_ entries",
                "info": "Showing _START_ to _END_ of _TOTAL_ entries",
                "infoEmpty": "Showing 0 to 0 of 0 entries",
                "infoFiltered": "(filtered from _MAX_ total entries)",
                "emptyTable": "No data available in table",
                "zeroRecords": "No matching records found",
                "paginate": {
                    "first": "First",
                    "last": "Last",
                    "next": "Next",
                    "previous": "Previous"
                }
            },
            "dom": '<"row"<"col-sm-6"l><"col-sm-6"f>>rtip',
            "responsive": true,
            "autoWidth": false
        });

        // Mobile pagination logic
        var mobileCards = $('#mobile_product_sales_cards .card');
        var cardsPerPage = 5;
        var currentPage = 1;
        var totalPages = Math.ceil(mobileCards.length / cardsPerPage);

        function showMobilePage(page) {
            mobileCards.hide();
            var startIndex = (page - 1) * cardsPerPage;
            var endIndex = startIndex + cardsPerPage;
            mobileCards.slice(startIndex, endIndex).show();
        }

        function updateMobilePagination() {
            var paginationHtml = '<div class="text-center" style="margin-top: 20px;">';
            if (totalPages > 1) {
                if (currentPage > 1) {
                    paginationHtml += '<button class="btn btn-default" onclick="showMobilePage(' + (currentPage - 1) + ')">Previous</button> ';
                }
                paginationHtml += '<span>Page ' + currentPage + ' of ' + totalPages + '</span>';
                if (currentPage < totalPages) {
                    paginationHtml += ' <button class="btn btn-default" onclick="showMobilePage(' + (currentPage + 1) + ')">Next</button>';
                }
            }
            paginationHtml += '</div>';
            $('#mobile_product_sales_cards').after(paginationHtml);
        }

        if (mobileCards.length > 0) {
            showMobilePage(1);
            updateMobilePagination();
        }

        // Global function for mobile pagination
        window.showMobilePage = function(page) {
            currentPage = page;
            showMobilePage(page);
            $('#mobile_product_sales_cards').next('.text-center').remove();
            updateMobilePagination();
        };
    });
</script>
@stop
