@extends('admin.layouts.main')
@section('title')
    {{ __('translations.sales-report') }}
@endsection
@section('sub-title')
    {{ __('translations.financial-reports') }}
@endsection
@section('content')
<div class="content d-flex flex-column flex-column-fluid" id="kt_content">
    <div class="post d-flex flex-column-fluid" id="kt_post">
        <div id="kt_content_container" class="container-fluid">
            <div class="card shadow-xl border-0 mb-5 overflow-hidden">
                <div class="card-header bg-gradient-primary text-white py-5">
                    <div class="card-title m-0">
                        <h3 class="fw-bolder m-0 text-white">{{ __('translations.sales-report') }}</h3>
                    </div>
                    <div class="card-toolbar">
                        <a href="{{ route('admin.financial-reports.index') }}" class="btn btn-sm btn-light-primary btn-active-light-primary">
                            <i class="bi bi-arrow-left me-2"></i>{{ __('translations.back') }}
                        </a>
                    </div>
                </div>
                <div class="card-body p-5">
                    <!-- Filters Section -->
                    <div class="card bg-light-primary bg-opacity-50 shadow-sm border-0 mb-6">
                        <div class="card-body p-4">
                            <h4 class="mb-4 text-dark fw-bold"><i class="bi bi-funnel-fill me-2"></i>{{ __('translations.filter') }}</h4>
                            <form action="{{ route('admin.financial-reports.sales') }}" method="get">
                                <div class="row g-4">
                                    <div class="col-md-3">
                                        <label class="form-label fw-semibold">{{ __('translations.client') }}</label>
                                        <select name="client_id" class="form-select form-select-solid border-0 shadow-none">
                                            <option value="">{{ __('translations.all-clients') }}</option>
                                            @foreach (\App\Models\Client::all() as $client)
                                                <option value="{{ $client->id }}" {{ request('client_id') == $client->id ? 'selected' : '' }}>
                                                    {{ $client->first_name }} {{ $client->last_name }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label fw-semibold">{{ __('translations.payment-method') }}</label>
                                        <select name="payment_method_code" class="form-select form-select-solid border-0 shadow-none">
                                            <option value="">{{ __('translations.all-methods') }}</option>
                                            <option value="011" {{ request('payment_method_code') == '011' ? 'selected' : '' }}>{{ __('translations.cash') }}</option>
                                            <option value="021" {{ request('payment_method_code') == '021' || request('payment_method_code') == '21' ? 'selected' : '' }}>{{ __('translations.credit') }}</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label fw-semibold">{{ __('translations.status') }}</label>
                                        <select name="status" class="form-select form-select-solid border-0 shadow-none">
                                            <option value="">{{ __('translations.all-statuses') }}</option>
                                            <option value="pending" {{ request('status') == 'pending' ? 'selected' : '' }}>{{ __('translations.pending') }}</option>
                                            <option value="completed" {{ request('status') == 'completed' ? 'selected' : '' }}>{{ __('translations.completed') }}</option>
                                            <option value="cancelled" {{ request('status') == 'cancelled' ? 'selected' : '' }}>{{ __('translations.cancelled') }}</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label fw-semibold">{{ __('translations.start-date') }}</label>
                                        <div class="input-group">
                                            <span class="input-group-text bg-light border-0"><i class="bi bi-calendar3"></i></span>
                                            <input type="date" name="start_date" value="{{ request('start_date') }}" class="form-control form-control-solid border-0 shadow-none">
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label fw-semibold">{{ __('translations.end-date') }}</label>
                                        <div class="input-group">
                                            <span class="input-group-text bg-light border-0"><i class="bi bi-calendar3"></i></span>
                                            <input type="date" name="end_date" value="{{ request('end_date') }}" class="form-control form-control-solid border-0 shadow-none">
                                        </div>
                                    </div>
                                    <div class="col-md-9">
                                        <div class="d-flex gap-3 h-100 align-items-end">
                                            <button type="submit" class="btn btn-primary hover-scale">
                                                <i class="bi bi-search me-2"></i>{{ __('translations.filter') }}
                                            </button>
                                            <a href="{{ route('admin.financial-reports.sales') }}" class="btn btn-secondary">
                                                <i class="bi bi-x-circle me-2"></i>{{ __('translations.reset') }}
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="row g-5 g-xl-8 mb-6">
                        <div class="col-xl-4">
                            <div class="card bg-light-primary hover-elevate-up shadow-sm card-xl-stretch mb-xl-8">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="symbol symbol-50px me-5">
                                            <span class="symbol-label bg-primary">
                                                <i class="bi bi-cart-check fs-2 text-white"></i>
                                            </span>
                                        </div>
                                        <div class="d-flex flex-column">
                                            <span class="fs-2hx fw-bold">{{ number_format($totalSales, 0) }} {{ __('translations.currency') }}</span>
                                            <span class="text-muted fw-semibold mt-1">{{ __('translations.total-sales') }}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4">
                            <div class="card bg-light-warning hover-elevate-up shadow-sm card-xl-stretch mb-xl-8">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="symbol symbol-50px me-5">
                                            <span class="symbol-label bg-warning">
                                                <i class="bi bi-arrow-return-left fs-2 text-white"></i>
                                            </span>
                                        </div>
                                        <div class="d-flex flex-column">
                                            <span class="fs-2hx fw-bold">{{ number_format($totalReturns ?? 0, 0) }} {{ __('translations.currency') }}</span>
                                            <span class="text-muted fw-semibold mt-1">{{ __('translations.returns') }}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4">
                            <div class="card bg-light-success hover-elevate-up shadow-sm card-xl-stretch mb-xl-8">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="symbol symbol-50px me-5">
                                            <span class="symbol-label bg-success">
                                                <i class="bi bi-currency-exchange fs-2 text-white"></i>
                                            </span>
                                        </div>
                                        <div class="d-flex flex-column">
                                            <span class="fs-2hx fw-bold">{{ number_format($totalSales - ($totalReturns ?? 0), 0) }} {{ __('translations.currency') }}</span>
                                            <span class="text-muted fw-semibold mt-1">{{ __('translations.net-sales') }}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Charts Section -->
                    <div class="row g-5 g-xl-8 mb-6">
                        <div class="col-xl-6">
                            <div class="card card-xl-stretch mb-xl-8 shadow-sm hover-elevate-up">
                                <div class="card-header ribbon ribbon-top ribbon-vertical">
                                    <div class="ribbon-label bg-primary">
                                        <i class="bi bi-graph-up-arrow fs-2 text-white"></i>
                                    </div>
                                    <h3 class="card-title align-items-start flex-column">
                                        <span class="card-label fw-bold fs-3 mb-1">{{ __('translations.monthly-sales') }}</span>
                                        <span class="text-muted fw-semibold fs-7">{{ $selectedYear ?? date('Y') }}</span>
                                    </h3>
                                    <div class="card-toolbar">
                                        <form action="{{ route('admin.financial-reports.sales') }}" method="GET" class="d-flex align-items-center">
                                            <select name="year" class="form-select form-select-sm" onchange="this.form.submit()">
                                                @for($year = date('Y') + 5; $year >= date('Y') - 5; $year--)
                                                    <option value="{{ $year }}" {{ ($selectedYear ?? date('Y')) == $year ? 'selected' : '' }}>{{ $year }}</option>
                                                @endfor
                                            </select>
                                        </form>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div id="sales_monthly_chart" style="height: 350px"></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-6">
                            <div class="card card-xl-stretch mb-xl-8 shadow-sm hover-elevate-up">
                                <div class="card-header ribbon ribbon-top ribbon-vertical">
                                    <div class="ribbon-label bg-success">
                                        <i class="bi bi-pie-chart-fill fs-2 text-white"></i>
                                    </div>
                                    <h3 class="card-title align-items-start flex-column">
                                        <span class="card-label fw-bold fs-3 mb-1">{{ __('translations.sales-by-payment-method') }}</span>
                                    </h3>
                                </div>
                                <div class="card-body">
                                    <div id="sales_payment_chart" style="height: 350px"></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Sales Table -->
                    <div class="card shadow-sm border-0 hover-elevate-up">
                        <div class="card-header py-3 border-0 bg-light">
                            <div class="card-title">
                                <h3 class="card-label fw-bold"><i class="bi bi-receipt me-2 text-primary"></i>{{ __('translations.invoices-list') }}</h3>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-hover table-rounded gs-7">
                                    <thead>
                                        <tr class="fw-bold text-gray-800 border-bottom border-gray-200 bg-light-primary bg-opacity-50">
                                            <th>{{ __('translations.invoice-number') }}</th>
                                            <th>{{ __('translations.client') }}</th>
                                            <th>{{ __('translations.date') }}</th>
                                            <th>{{ __('translations.payment-method') }}</th>
                                            <th>{{ __('translations.amount') }}</th>
                                            <th>{{ __('translations.status') }}</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @forelse ($invoices as $invoice)
                                            <tr>
                                                <td class="fw-semibold">{{ $invoice->number }}</td>
                                                <td>
                                                    @if ($invoice->client)
                                                        {{ $invoice->client->first_name }} {{ $invoice->client->last_name }}
                                                    @else
                                                        N/A
                                                    @endif
                                                </td>
                                                <td>{{ $invoice->created_at->format('Y-m-d') }}</td>
                                                <td>
                                                    @if ($invoice->payment_method_code == '011')
                                                        <span class="badge badge-light-success">{{ __('translations.cash') }}</span>
                                                    @elseif ($invoice->payment_method_code == '021' || $invoice->payment_method_code == '21')
                                                        <span class="badge badge-light-info">{{ __('translations.credit') }}</span>
                                                    @else
                                                        <span class="badge badge-light-secondary">{{ $invoice->payment_method_code }}</span>
                                                    @endif
                                                </td>
                                                <td class="fw-bold fs-6">{{ number_format($invoice->total_price, 0) }} {{ __('translations.currency') }}</td>
                                                <td>
                                                    @php
                                                        $statusClass = '';
                                                        switch($invoice->status) {
                                                            case 'completed':
                                                                $statusClass = 'badge-light-success';
                                                                break;
                                                            case 'pending':
                                                                $statusClass = 'badge-light-warning';
                                                                break;
                                                            case 'cancelled':
                                                                $statusClass = 'badge-light-danger';
                                                                break;
                                                            default:
                                                                $statusClass = 'badge-light-secondary';
                                                        }
                                                    @endphp
                                                    <span class="badge {{ $statusClass }}">{{ __('translations.' . $invoice->status) }}</span>
                                                </td>
                                            </tr>
                                        @empty
                                            <tr>
                                                <td colspan="6" class="text-center py-5">
                                                    <div class="d-flex flex-column align-items-center">
                                                        <i class="bi bi-exclamation-circle text-muted fs-2"></i>
                                                        <span class="text-muted mt-2">{{ __('translations.no-invoices-found') }}</span>
                                                    </div>
                                                </td>
                                            </tr>
                                        @endforelse
                                    </tbody>
                                </table>
                            </div>
                            <div class="px-5 py-4">
                                {{ $invoices->withQueryString()->links() }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
@section('js')
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        // Check if data is empty
        var monthlyDataIsEmpty = true;
        var paymentDataIsEmpty = true;
        var rawPaymentData = @json($salesByPaymentMethod ?? []);

        console.log('Raw payment data before processing:', rawPaymentData);

        @if(isset($monthlySales) && isset($monthlySales['data']) && is_array($monthlySales['data']))
            monthlyDataIsEmpty = @json($monthlySales['data']).length === 0 || !@json($monthlySales['data']).some(function(value) { return value > 0; });
        @endif

        // Fix for Array(1) issue - directly check if the raw data exists and has elements
        paymentDataIsEmpty = !Array.isArray(rawPaymentData) || rawPaymentData.length === 0;
        console.log('Fixed payment data check. Is empty:', paymentDataIsEmpty);

        @if(isset($salesByPaymentMethod) && is_array($salesByPaymentMethod))
            console.log('Payment data from PHP:', @json($salesByPaymentMethod));
        @else
            console.log('Raw salesByPaymentMethod variable:', @json($salesByPaymentMethod ?? null));
        @endif

        console.log('Monthly sales data is empty:', monthlyDataIsEmpty);
        console.log('Payment method data is empty:', paymentDataIsEmpty);

        // Monthly Sales Chart
        if (!monthlyDataIsEmpty) {
            var monthlyOptions = {
                series: [{
                    name: '{{ __("translations.sales") }}',
                    data: @json($monthlySales['data'])
                }],
                chart: {
                    fontFamily: 'Tajawal, sans-serif',
                    type: 'area',
                    height: 350,
                    toolbar: {
                        show: false
                    },
                    animations: {
                        enabled: true,
                        easing: 'easeinout',
                        speed: 800,
                        animateGradually: {
                            enabled: true,
                            delay: 150
                        },
                        dynamicAnimation: {
                            enabled: true,
                            speed: 350
                        }
                    },
                    dropShadow: {
                        enabled: true,
                        color: '#000',
                        top: 18,
                        left: 7,
                        blur: 10,
                        opacity: 0.05
                    }
                },
                colors: ['#04424e'],
                dataLabels: {
                    enabled: false
                },
                stroke: {
                    curve: 'smooth',
                    width: 3
                },
                fill: {
                    type: 'gradient',
                    gradient: {
                        shade: 'light',
                        type: "vertical",
                        shadeIntensity: 0.5,
                        gradientToColors: undefined,
                        inverseColors: false,
                        opacityFrom: 0.7,
                        opacityTo: 0.3,
                        stops: [0, 90, 100]
                    }
                },
                markers: {
                    size: 5,
                    strokeWidth: 0,
                    hover: {
                        size: 7
                    }
                },
                xaxis: {
                    categories: @json($monthlySales['labels']),
                    labels: {
                        style: {
                            fontSize: '12px',
                            fontWeight: 500
                        }
                    }
                },
                yaxis: {
                    labels: {
                        formatter: function(val) {
                            return val.toLocaleString()
                        },
                        style: {
                            fontSize: '12px',
                            fontWeight: 500
                        }
                    }
                },
                tooltip: {
                    y: {
                        formatter: function (val) {
                            return val.toLocaleString() + ' {{ __("translations.currency") }}'
                        }
                    }
                }
            };

            var monthlyChart = new ApexCharts(document.querySelector("#sales_monthly_chart"), monthlyOptions);
            monthlyChart.render();
        } else {
            $("#sales_monthly_chart").html('<div class="d-flex justify-content-center align-items-center h-100"><span class="text-muted fs-3">{{ __("translations.no-sales-data") }}</span></div>');
        }

        // PAYMENT METHOD CHART - FIXED CODE
        if (!paymentDataIsEmpty) {
            try {
                console.log('Processing payment data for chart');
                var paymentData = rawPaymentData;

                // Simple format for the chart - direct use of array data
                var labels = [];
                var data = [];

                paymentData.forEach(function(item, index) {
                    console.log('Processing item', index, ':', item);

                    // Get the payment method code
                    var code = item.payment_method_code || '';
                    var amount = parseFloat(item.total_amount || 0);

                    if (isNaN(amount)) amount = 0;

                    // Set the label based on the code
                    var label = '';
                    if (code === '011') {
                        label = '{{ __("translations.cash") }}';
                    } else if (code === '021' || code === '21') {
                        label = '{{ __("translations.credit") }}';
                    } else {
                        label = code || 'Unknown';
                    }

                    labels.push(label);
                    data.push(amount);
                });

                console.log('Chart data prepared:', {labels: labels, data: data});

                if (data.length === 0 || data.every(val => val === 0)) {
                    console.warn('Chart data is empty or all zeros');
                    $("#sales_payment_chart").html('<div class="d-flex justify-content-center align-items-center h-100"><span class="text-muted fs-3">{{ __("translations.no-payment-data") }}</span></div>');
                    return;
                }

                // Create the chart
                var paymentOptions = {
                    series: data,
                    chart: {
                        fontFamily: 'Tajawal, sans-serif',
                        type: 'donut',
                        height: 350
                    },
                    labels: labels,
                    colors: ['#01d9cc', '#04424e', '#28a745'],
                    legend: {
                        position: 'bottom'
                    },
                    plotOptions: {
                        pie: {
                            donut: {
                                labels: {
                                    show: true,
                                    total: {
                                        show: true,
                                        label: '{{ __("translations.total") }}'
                                    }
                                }
                            }
                        }
                    },
                    tooltip: {
                        y: {
                            formatter: function (val) {
                                return val.toLocaleString() + ' {{ __("translations.currency") }}'
                            }
                        }
                    }
                };

                console.log('Creating payment chart with options:', paymentOptions);
                var paymentChart = new ApexCharts(document.querySelector("#sales_payment_chart"), paymentOptions);
                paymentChart.render();
                console.log('Payment chart rendered successfully');

            } catch (error) {
                console.error('Error creating payment chart:', error);
                $("#sales_payment_chart").html('<div class="d-flex justify-content-center align-items-center h-100"><span class="text-muted fs-3">{{ __("translations.chart-error") }}</span><br><pre>' + error.toString() + '</pre></div>');
            }
        } else {
            console.warn('No payment data available for chart');
            $("#sales_payment_chart").html('<div class="d-flex justify-content-center align-items-center h-100"><span class="text-muted fs-3">{{ __("translations.no-payment-data") }}</span></div>');
        }
    });
</script>
<style>
    .hover-elevate-up {
        transition: transform 0.3s ease;
    }
    .hover-elevate-up:hover {
        transform: translateY(-5px);
    }
    .hover-scale {
        transition: transform 0.3s ease;
    }
    .hover-scale:hover {
        transform: scale(1.05);
    }
</style>

@endsection
