@extends('layouts.app')

@section('content')
<div class="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 py-8 px-4 md:px-8">
    <div class="max-w-7xl mx-auto">
        <!-- Page Header -->
        <div class="mb-8">
            <div class="flex items-center justify-between mb-6">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">توقع التدفق النقدي</h1>
                    <p class="text-gray-600">تحليل التدفقات النقدية المتوقعة بناءً على فواتير الموردين المستحقة</p>
                </div>
                <div class="flex gap-3">
                    @if($data && count($data) > 0)
                        <form method="GET" action="{{ route('reports.purchase.cash-flow-forecast') }}" class="inline-block">
                            <select name="format" onchange="this.form.submit()" class="px-4 py-2 rounded-lg border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 transition-colors duration-200">
                                <option value="">تصدير</option>
                                <option value="excel">Excel</option>
                                <option value="pdf">PDF</option>
                                <option value="csv">CSV</option>
                            </select>
                        </form>
                    @endif
                    <a href="{{ route('reports.purchase.index') }}" class="px-4 py-2 rounded-lg bg-gray-200 text-gray-700 hover:bg-gray-300 transition-colors duration-200">
                        <i class="fas fa-arrow-right ml-1"></i>العودة
                    </a>
                </div>
            </div>
        </div>

        <!-- Alert Messages -->
        @if(session('success'))
            <div class="bg-green-50 border-l-4 border-green-500 p-4 mb-6 rounded-r-lg">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-check-circle text-green-500 text-xl"></i>
                    </div>
                    <div class="mr-3">
                        <p class="text-green-700 font-medium">{{ session('success') }}</p>
                    </div>
                </div>
            </div>
        @endif

        <!-- Date Filter -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6 border border-gray-200">
            <form method="GET" action="{{ route('reports.purchase.cash-flow-forecast') }}" class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label for="start_date" class="block text-sm font-medium text-gray-700 mb-2">تاريخ البداية</label>
                    <input type="date" id="start_date" name="start_date" value="{{ request('start_date', now()->toDateString()) }}" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                </div>
                <div>
                    <label for="end_date" class="block text-sm font-medium text-gray-700 mb-2">تاريخ النهاية</label>
                    <input type="date" id="end_date" name="end_date" value="{{ request('end_date', now()->addMonth()->toDateString()) }}" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                </div>
                <div class="flex items-end">
                    <button type="submit" class="w-full px-6 py-2 bg-gradient-to-r from-blue-600 to-blue-700 text-white font-semibold rounded-lg hover:from-blue-700 hover:to-blue-800 transition-all duration-200 shadow-lg hover:shadow-xl transform hover:scale-105">
                        <i class="fas fa-search ml-2"></i>البحث
                    </button>
                </div>
            </form>
        </div>

        @if($data && count($data) > 0)
            <!-- Statistics Cards -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
                <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-blue-500">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">إجمالي التدفق الخارج</p>
                            <p class="text-2xl font-bold text-gray-900 mt-2">{{ number_format($data->sum('forecast_outflow'), 2) }} ر.س</p>
                        </div>
                        <i class="fas fa-arrow-down text-blue-500 text-3xl opacity-20"></i>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-green-500">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">عدد الأيام</p>
                            <p class="text-2xl font-bold text-gray-900 mt-2">{{ $data->count() }}</p>
                        </div>
                        <i class="fas fa-calendar text-green-500 text-3xl opacity-20"></i>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-yellow-500">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">إجمالي الفواتير</p>
                            <p class="text-2xl font-bold text-gray-900 mt-2">{{ $data->sum('invoice_count') }}</p>
                        </div>
                        <i class="fas fa-file-invoice-dollar text-yellow-500 text-3xl opacity-20"></i>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-purple-500">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">متوسط التدفق اليومي</p>
                            <p class="text-2xl font-bold text-gray-900 mt-2">{{ number_format($data->count() > 0 ? $data->sum('forecast_outflow') / $data->count() : 0, 2) }} ر.س</p>
                        </div>
                        <i class="fas fa-chart-line text-purple-500 text-3xl opacity-20"></i>
                    </div>
                </div>
            </div>

            <!-- Chart -->
            <div class="bg-white rounded-xl shadow-lg p-6 mb-8 border border-gray-200">
                <h2 class="text-xl font-bold text-gray-900 mb-6">رسم بياني للتدفق النقدي</h2>
                <div class="relative" style="height: 400px;">
                    <canvas id="cashFlowChart"></canvas>
                </div>
            </div>

            <!-- Data Table -->
            <div class="bg-white rounded-xl shadow-lg overflow-hidden border border-gray-200">
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gradient-to-r from-gray-800 to-gray-900 text-white">
                            <tr>
                                <th class="px-6 py-4 text-right font-semibold text-sm">#</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm">التاريخ</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm">يوم الأسبوع</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm">عدد الفواتير</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm">التدفق الخارج</th>
                                <th class="px-6 py-4 text-center font-semibold text-sm">نسبة</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            @forelse($data as $item)
                                <tr class="hover:bg-blue-50 transition-colors duration-150 border-b border-gray-100">
                                    <td class="px-6 py-4 text-gray-600 font-medium">{{ $loop->iteration }}</td>
                                    <td class="px-6 py-4">
                                        <span class="font-semibold text-gray-900">{{ \Carbon\Carbon::createFromFormat('Y-m-d', $item['date'])->format('Y-m-d') }}</span>
                                    </td>
                                    <td class="px-6 py-4 text-gray-600">
                                        {{ \Carbon\Carbon::createFromFormat('Y-m-d', $item['date'])->translatedFormat('dddd') }}
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-700">
                                            {{ $item['invoice_count'] }}
                                        </span>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="font-semibold text-red-600">{{ number_format($item['forecast_outflow'], 2) }} ر.س</span>
                                    </td>
                                    <td class="px-6 py-4 text-center">
                                        @php
                                            $totalOutflow = $data->sum('forecast_outflow');
                                            $percentage = $totalOutflow > 0 ? ($item['forecast_outflow'] / $totalOutflow) * 100 : 0;
                                        @endphp
                                        <div class="w-full bg-gray-200 rounded-full h-2">
                                            <div class="bg-red-500 h-2 rounded-full" style="width: {{ $percentage }}%"></div>
                                        </div>
                                        <span class="text-xs text-gray-600 mt-1">{{ number_format($percentage, 1) }}%</span>
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="6" class="px-6 py-12 text-center">
                                        <div class="flex flex-col items-center justify-center">
                                            <i class="fas fa-inbox text-gray-400 text-4xl mb-3"></i>
                                            <p class="text-gray-600 font-medium">لا توجد بيانات للعرض</p>
                                            <p class="text-gray-500 text-sm mt-1">حاول تغيير نطاق التواريخ</p>
                                        </div>
                                    </td>
                                </tr>
                            @endforelse
                        </tbody>
                        <tfoot class="bg-gray-50 border-t-2 border-gray-200">
                            <tr>
                                <td colspan="4" class="px-6 py-4 text-right font-bold text-gray-900">الإجمالي</td>
                                <td class="px-6 py-4 font-bold">
                                    <span class="text-lg text-red-600">{{ number_format($data->sum('forecast_outflow'), 2) }} ر.س</span>
                                </td>
                                <td class="px-6 py-4 text-center">100%</td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        @else
            <!-- Empty State -->
            <div class="bg-white rounded-xl shadow-lg p-12 border border-gray-200 text-center">
                <i class="fas fa-chart-line text-gray-400 text-5xl mb-4"></i>
                <p class="text-gray-600 font-medium text-lg">لا توجد بيانات للعرض</p>
                <p class="text-gray-500 mt-2">حاول تغيير نطاق التواريخ أو التحقق من وجود فواتير موردين</p>
            </div>
        @endif
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        @if($data && count($data) > 0)
            const dates = {!! json_encode($data->pluck('date')) !!};
            const outflows = {!! json_encode($data->pluck('forecast_outflow')) !!};

            const ctx = document.getElementById('cashFlowChart').getContext('2d');
            
            const formattedDates = dates.map(date => {
                const d = new Date(date);
                return d.toLocaleDateString('ar-SA', { month: 'short', day: 'numeric' });
            });

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: formattedDates,
                    datasets: [{
                        label: 'التدفق الخارج المتوقع (ر.س)',
                        data: outflows,
                        borderColor: 'rgb(239, 68, 68)',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        borderWidth: 2,
                        fill: true,
                        tension: 0.4,
                        pointRadius: 4,
                        pointBackgroundColor: 'rgb(239, 68, 68)',
                        pointBorderColor: 'white',
                        pointBorderWidth: 2,
                        pointHoverRadius: 6
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return value.toLocaleString('ar-SA') + ' ر.س';
                                }
                            }
                        }
                    }
                }
            });
        @endif
    });
</script>
@endpush

@endsection
