@extends('admin.layouts.main')
@section('title')
    {{ __('translations.expenses-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.expenses-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.expenses') }}" method="get">
                                <div class="row g-4">
                                    <div class="col-md-3">
                                        <label class="form-label fw-semibold">{{ __('translations.category') }}</label>
                                        <select name="category_id" class="form-select form-select-solid border-0 shadow-none">
                                            <option value="">{{ __('translations.all-categories') }}</option>
                                            @foreach ($categories as $category)
                                                <option value="{{ $category->id }}" {{ request('category_id') == $category->id ? 'selected' : '' }}>
                                                    {{ $category->name }}
                                                </option>
                                            @endforeach
                                        </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="approved" {{ request('status') == 'approved' ? 'selected' : '' }}>{{ __('translations.approved') }}</option>
                                            <option value="pending" {{ request('status') == 'pending' ? 'selected' : '' }}>{{ __('translations.pending') }}</option>
                                            <option value="rejected" {{ request('status') == 'rejected' ? 'selected' : '' }}>{{ __('translations.rejected') }}</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-3">
                                        <label class="form-label fw-semibold">{{ __('translations.amount-min') }}</label>
                                        <div class="input-group">
                                            <span class="input-group-text bg-light border-0"><i class="bi bi-cash"></i></span>
                                            <input type="number" name="amount_min" value="{{ request('amount_min') }}" class="form-control form-control-solid border-0 shadow-none">
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label fw-semibold">{{ __('translations.amount-max') }}</label>
                                        <div class="input-group">
                                            <span class="input-group-text bg-light border-0"><i class="bi bi-cash"></i></span>
                                            <input type="number" name="amount_max" value="{{ request('amount_max') }}" class="form-control form-control-solid border-0 shadow-none">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <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.expenses') }}" 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-cash-stack fs-2 text-white"></i>
                                            </span>
                                        </div>
                                        <div class="d-flex flex-column">
                                            <span class="fs-2hx fw-bold">{{ number_format($totalAmount, 0) }} {{ __('translations.currency') }}</span>
                                            <span class="text-muted fw-semibold mt-1">{{ __('translations.total-expenses') }}</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-expenses') }}</span>
                                        <span class="text-muted mt-1 fw-semibold fs-7">{{ $selectedYear ?? date('Y') }}</span>
                                    </h3>
                                    <div class="card-toolbar">
                                        <form action="{{ route('admin.financial-reports.expenses') }}" 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="expenses_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.expenses-by-category') }}</span>
                                    </h3>
                                </div>
                                <div class="card-body">
                                    <div id="expenses_category_chart" style="height: 350px"></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Expenses 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-list-ul me-2 text-primary"></i>{{ __('translations.expenses-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.expense-title') }}</th>
                                            <th>{{ __('translations.category') }}</th>
                                            <th>{{ __('translations.amount') }}</th>
                                            <th>{{ __('translations.date') }}</th>
                                            <th>{{ __('translations.status') }}</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @forelse ($expenses as $expense)
                                            <tr>
                                                <td class="fw-semibold">{{ $expense->title }}</td>
                                                <td>{{ $expense->category->name ?? 'N/A' }}</td>
                                                <td class="fw-bold fs-6">{{ number_format($expense->amount, 0) }} {{ __('translations.currency') }}</td>
                                                <td>{{ $expense->expense_date->format('Y-m-d') }}</td>
                                                <td>
                                                    @php
                                                        $statusClass = '';
                                                        switch($expense->status) {
                                                            case 'approved':
                                                                $statusClass = 'badge-light-success';
                                                                break;
                                                            case 'pending':
                                                                $statusClass = 'badge-light-warning';
                                                                break;
                                                            case 'rejected':
                                                                $statusClass = 'badge-light-danger';
                                                                break;
                                                            default:
                                                                $statusClass = 'badge-light-secondary';
                                                        }
                                                    @endphp
                                                    <span class="badge {{ $statusClass }}">{{ __('translations.' . $expense->status) }}</span>
                                                </td>
                                            </tr>
                                        @empty
                                            <tr>
                                                <td colspan="5" 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-expenses-found') }}</span>
                                                    </div>
                                                </td>
                                            </tr>
                                        @endforelse
                                    </tbody>
                                </table>
                            </div>
                            <div class="px-5 py-4">
                                {{ $expenses->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() {
        // Debug data
        console.log('Monthly Data:', @json($monthlyData));
        console.log('Category Data:', @json($expensesByCategory));

        // Check if monthly data is empty
        var monthlyDataIsEmpty = true;
        @if(isset($monthlyData) && isset($monthlyData['data']) && is_array($monthlyData['data']))
            monthlyDataIsEmpty = @json($monthlyData['data']).length === 0 || !@json($monthlyData['data']).some(function(value) { return value > 0; });
        @endif

        // Check if category data is empty
        var categoryDataIsEmpty = true;
        @if(isset($expensesByCategory) && $expensesByCategory->count() > 0)
            categoryDataIsEmpty = false;
        @endif

        console.log('Monthly data is empty:', monthlyDataIsEmpty);
        console.log('Category data is empty:', categoryDataIsEmpty);

        // Monthly Expenses Chart
        if (!monthlyDataIsEmpty) {
            var monthlyOptions = {
                series: [{
                    name: '{{ __("translations.expenses") }}',
                    data: @json($monthlyData['data'])
                }],
                chart: {
                    fontFamily: 'Tajawal, sans-serif',
                    type: 'bar',
                    height: 350,
                    toolbar: {
                        show: false
                    },
                    animations: {
                        enabled: true,
                        easing: 'easeinout',
                        speed: 800,
                        animateGradually: {
                            enabled: true,
                            delay: 150
                        },
                        dynamicAnimation: {
                            enabled: true,
                            speed: 350
                        }
                    }
                },
                plotOptions: {
                    bar: {
                        horizontal: false,
                        columnWidth: '55%',
                        borderRadius: 5,
                        endingShape: 'rounded'
                    },
                },
                colors: ['#01d9cc'],
                dataLabels: {
                    enabled: false
                },
                stroke: {
                    show: true,
                    width: 2,
                    colors: ['transparent']
                },
                xaxis: {
                    categories: @json($monthlyData['labels']),
                    labels: {
                        style: {
                            fontSize: '12px',
                            fontWeight: 500
                        }
                    }
                },
                yaxis: {
                    labels: {
                        formatter: function(val) {
                            return val.toLocaleString()
                        },
                        style: {
                            fontSize: '12px',
                            fontWeight: 500
                        }
                    }
                },
                fill: {
                    opacity: 1,
                    type: 'gradient',
                    gradient: {
                        shade: 'light',
                        type: "vertical",
                        shadeIntensity: 0.2,
                        gradientToColors: undefined,
                        inverseColors: false,
                        opacityFrom: 0.85,
                        opacityTo: 0.85,
                        stops: [0, 100]
                    },
                },
                tooltip: {
                    y: {
                        formatter: function (val) {
                            return val.toLocaleString() + ' {{ __("translations.currency") }}'
                        }
                    }
                }
            };

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

        // Category Expenses Chart
        if (!categoryDataIsEmpty) {
            var categoryData = @json($expensesByCategory);
            var labels = categoryData.map(function(item) { return item.category ? item.category.name : 'Unknown'; });
            var data = categoryData.map(function(item) { return parseFloat(item.total_amount); });

            var categoryOptions = {
                series: data,
                chart: {
                    fontFamily: 'Tajawal, sans-serif',
                    type: 'pie',
                    height: 350,
                    toolbar: {
                        show: false
                    },
                    animations: {
                        enabled: true,
                        easing: 'ease',
                        speed: 800,
                        animateGradually: {
                            enabled: true,
                            delay: 150
                        }
                    }
                },
                labels: labels,
                colors: ['#01d9cc', '#04424e', '#28a745', '#ffc107', '#dc3545', '#6c757d', '#007bff'],
                legend: {
                    position: 'bottom',
                    fontSize: '14px',
                    fontWeight: 600,
                    markers: {
                        width: 12,
                        height: 12,
                        radius: 12
                    }
                },
                plotOptions: {
                    pie: {
                        dataLabels: {
                            offset: -5
                        },
                        donut: {
                            labels: {
                                show: true,
                                total: {
                                    show: true,
                                    showAlways: false,
                                    label: '{{ __("translations.total") }}',
                                    fontSize: '20px',
                                    fontWeight: 'bold',
                                    formatter: function (w) {
                                        return w.globals.seriesTotals.reduce(function(a, b) { return a + b; }, 0).toLocaleString() + ' {{ __("translations.currency") }}';
                                    }
                                }
                            }
                        }
                    }
                },
                dataLabels: {
                    enabled: true,
                    formatter: function (val, opts) {
                        return opts.w.config.labels[opts.seriesIndex] + ': ' + Math.round(val) + '%';
                    },
                    style: {
                        fontSize: '12px',
                        fontWeight: 'bold',
                        colors: ['#fff']
                    },
                    dropShadow: {
                        enabled: true,
                        color: '#000',
                        top: 1,
                        left: 1,
                        blur: 3,
                        opacity: 0.3
                    }
                },
                stroke: {
                    width: 2,
                    colors: ['#fff']
                },
                responsive: [{
                    breakpoint: 480,
                    options: {
                        chart: {
                            width: 300
                        },
                        legend: {
                            position: 'bottom'
                        }
                    }
                }],
                tooltip: {
                    y: {
                        formatter: function (val) {
                            return val.toLocaleString() + ' {{ __("translations.currency") }}'
                        }
                    }
                }
            };

            var categoryChart = new ApexCharts(document.querySelector("#expenses_category_chart"), categoryOptions);
            categoryChart.render();
        } else {
            document.querySelector("#expenses_category_chart").innerHTML = '<div class="d-flex justify-content-center align-items-center h-100"><span class="text-muted fs-3">{{ __("translations.no-category-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
