@extends('layouts.app')

@section('title', 'Dashboard')

@section('breadcrumb')
    @include('components.breadcrumb', ['items' => ['Dashboard' => null]])
@endsection

@section('content')
<div class="space-y-6">

    {{-- Welcome Banner --}}
    <div class="relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary-600 via-primary-700 to-purple-700 p-6 lg:p-8 shadow-card">
        <div class="absolute -top-20 -right-20 w-72 h-72 bg-white/10 rounded-full blur-3xl"></div>
        <div class="absolute -bottom-16 -left-16 w-72 h-72 bg-purple-400/20 rounded-full blur-3xl"></div>
        <div class="relative flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
                <p class="text-primary-100 text-sm font-medium">
                    Good {{ now()->hour < 12 ? 'Morning' : (now()->hour < 17 ? 'Afternoon' : 'Evening') }}, {{ auth()->user()?->name ?? 'Admin' }} 👋
                </p>
                <h2 class="text-2xl lg:text-3xl font-bold text-white mt-1">Welcome to {{ App\Models\CompanySetting::current()->company_name }}</h2>
                <p class="text-primary-100 mt-2 text-sm">Here's what's happening with your business today, {{ now()->format('l, F d, Y') }}.</p>
            </div>
            <div class="flex flex-wrap gap-2">
                <x-button variant="secondary" icon="download">Report</x-button>
                <x-button variant="primary" icon="plus" class="!bg-white !text-primary-700 hover:!bg-primary-50">
                    Quick Entry
                </x-button>
            </div>
        </div>
    </div>

    {{-- Top Summary Cards --}}
    <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <x-stat-card title="Today's Purchase" :value="$summary['today_purchase']" icon="shopping-cart" iconBg="primary" :change="$summary['last_month_purchase'] > 0 ? round((($summary['this_month_purchase'] - $summary['last_month_purchase']) / $summary['last_month_purchase']) * 100, 1) . '%' : null" />
        <x-stat-card title="Today's Sales" :value="$summary['today_sales']" icon="trending-up" iconBg="success" :change="$summary['last_month_sales'] > 0 ? round((($summary['this_month_sales'] - $summary['last_month_sales']) / $summary['last_month_sales']) * 100, 1) . '%' : null" />
        <x-stat-card title="Current Stock" :value="$summary['current_stock']" prefix="" icon="package" iconBg="info" />
        <x-stat-card title="Stock Value" :value="$summary['stock_value']" icon="circle-dollar-sign" iconBg="purple" />
    </div>

    <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <x-stat-card title="Today's Profit" :value="$summary['today_profit']" icon="award" iconBg="success" />
        <x-stat-card title="Receivable" :value="$summary['accounts_receivable']" icon="arrow-down-left" iconBg="warning" />
        <x-stat-card title="Payable" :value="$summary['accounts_payable']" icon="arrow-up-right" iconBg="danger" />
        <x-stat-card title="Cash Balance" :value="$summary['cash_balance']" icon="wallet" iconBg="primary" />
    </div>

    {{-- Charts Row --}}
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <x-card title="Monthly Purchase Overview" subtitle="Last 12 months" icon="shopping-bag">
            <div id="chart-purchase" class="h-72"></div>
        </x-card>
        <x-card title="Monthly Sales Overview" subtitle="Last 12 months" icon="bar-chart-3">
            <div id="chart-sales" class="h-72"></div>
        </x-card>
    </div>

    {{-- Purchase vs Sales + Stock Movement --}}
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <x-card title="Purchase vs Sales" subtitle="Comparison" icon="scale" class="lg:col-span-2">
            <div id="chart-purchase-vs-sales" class="h-80"></div>
        </x-card>
        <x-card title="Stock Movement" subtitle="Monthly in/out" icon="repeat">
            <div id="chart-stock-movement" class="h-80"></div>
        </x-card>
    </div>

    {{-- Profit Analysis + AI Insights --}}
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <x-card title="Profit Analysis" subtitle="Monthly trend" icon="trending-up" class="lg:col-span-2">
            <div id="chart-profit" class="h-72"></div>
        </x-card>

        <x-card title="AI Insights" subtitle="Smart Analytics" icon="sparkles">
            <x-slot:headerActions>
                <x-badge variant="purple" icon="sparkles">AI</x-badge>
            </x-slot:headerActions>
            <div class="space-y-3">
                @forelse($aiInsights['low_stock'] as $item)
                    <div class="p-3 rounded-xl bg-amber-50 dark:from-amber-500/10 dark:to-orange-500/10 border border-amber-200/50">
                        <div class="flex items-start gap-2">
                            <i data-lucide="alert-triangle" class="w-4 h-4 text-amber-600 mt-0.5"></i>
                            <div>
                                <p class="text-xs font-semibold text-amber-900 dark:text-amber-300">{{ $item->name }}</p>
                                <p class="text-xs text-amber-700 dark:text-amber-400/80 mt-0.5">
                                    Stock: {{ number_format($item->current_stock) }} {{ $item->unit }} — {{ $item->stock_status === 'out_of_stock' ? 'Out of Stock!' : 'Below reorder level' }}
                                </p>
                            </div>
                        </div>
                    </div>
                @empty
                    <p class="text-xs text-slate-500 text-center py-4">All stock levels are healthy.</p>
                @endforelse

                @if($aiInsights['top_selling']->isNotEmpty())
                    <div class="p-3 rounded-xl bg-emerald-50 dark:emerald-500/10 border border-emerald-200/50">
                        <p class="text-xs font-semibold text-emerald-900 dark:text-emerald-300 mb-2">🏆 Top Selling</p>
                        @foreach($aiInsights['top_selling'] as $top)
                            <div class="flex justify-between text-xs text-emerald-700 dark:text-emerald-400">
                                <span>{{ $top->name }}</span>
                                <span class="font-semibold">{{ number_format($top->total_qty) }} kg</span>
                            </div>
                        @endforeach
                    </div>
                @endif

                <a href="{{ route('ai.dashboard') }}" class="flex items-center justify-center gap-2 w-full py-2 text-xs font-semibold text-primary-600 hover:bg-primary-50 dark:hover:bg-primary-500/10 rounded-lg transition">
                    View All Insights <i data-lucide="arrow-right" class="w-3.5 h-3.5"></i>
                </a>
            </div>
        </x-card>
    </div>

    {{-- Recent Tables Row --}}
    <div class="grid grid-cols-1 xl:grid-cols-2 gap-6">

        <x-card title="Recent Purchase" subtitle="Latest transactions" icon="shopping-cart" :padding="false">
            <x-slot:headerActions>
                <a href="{{ route('purchase.index') }}" class="text-xs font-semibold text-primary-600 hover:text-primary-700">View All →</a>
            </x-slot:headerActions>
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="bg-slate-50 dark:bg-slate-900/50 border-b border-slate-200 dark:border-slate-800">
                            <th class="px-4 py-2.5 text-left text-[10px] font-bold uppercase tracking-wider text-slate-500">Date</th>
                            <th class="px-4 py-2.5 text-left text-[10px] font-bold uppercase tracking-wider text-slate-500">Supplier</th>
                            <th class="px-4 py-2.5 text-left text-[10px] font-bold uppercase tracking-wider text-slate-500">Yarn</th>
                            <th class="px-4 py-2.5 text-right text-[10px] font-bold uppercase tracking-wider text-slate-500">Amount</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                        @forelse($recentPurchases as $p)
                            <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/50 transition">
                                <td class="px-4 py-3 text-xs text-slate-500">{{ $p->purchase_date->format('M d') }}</td>
                                <td class="px-4 py-3 text-sm font-medium text-slate-900 dark:text-white">{{ $p->party->name }}</td>
                                <td class="px-4 py-3 text-xs text-slate-600 dark:text-slate-400">
                                    @foreach($p->items->take(2) as $item)
                                        {{ $item->yarn->name }}{{ !$loop->last ? ', ' : '' }}
                                    @endforeach
                                </td>
                                <td class="px-4 py-3 text-right text-sm font-bold text-primary-600 dark:text-primary-400 counter-num">৳{{ number_format($p->grand_total) }}</td>
                            </tr>
                        @empty
                            <tr><td colspan="4" class="text-center py-6 text-sm text-slate-500">No purchases yet</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </x-card>

        <x-card title="Recent Sales" subtitle="Latest transactions" icon="receipt" :padding="false">
            <x-slot:headerActions>
                <a href="{{ route('sales.index') }}" class="text-xs font-semibold text-primary-600 hover:text-primary-700">View All →</a>
            </x-slot:headerActions>
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="bg-slate-50 dark:bg-slate-900/50 border-b border-slate-200 dark:border-slate-800">
                            <th class="px-4 py-2.5 text-left text-[10px] font-bold uppercase tracking-wider text-slate-500">Date</th>
                            <th class="px-4 py-2.5 text-left text-[10px] font-bold uppercase tracking-wider text-slate-500">Customer</th>
                            <th class="px-4 py-2.5 text-left text-[10px] font-bold uppercase tracking-wider text-slate-500">Yarn</th>
                            <th class="px-4 py-2.5 text-right text-[10px] font-bold uppercase tracking-wider text-slate-500">Amount</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                        @forelse($recentSales as $s)
                            <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/50 transition">
                                <td class="px-4 py-3 text-xs text-slate-500">{{ $s->sales_date->format('M d') }}</td>
                                <td class="px-4 py-3 text-sm font-medium text-slate-900 dark:text-white">{{ $s->party->name }}</td>
                                <td class="px-4 py-3 text-xs text-slate-600 dark:text-slate-400">
                                    @foreach($s->items->take(2) as $item)
                                        {{ $item->yarn->name }}{{ !$loop->last ? ', ' : '' }}
                                    @endforeach
                                </td>
                                <td class="px-4 py-3 text-right text-sm font-bold text-emerald-600 dark:text-emerald-400 counter-num">৳{{ number_format($s->grand_total) }}</td>
                            </tr>
                        @empty
                            <tr><td colspan="4" class="text-center py-6 text-sm text-slate-500">No sales yet</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </x-card>
    </div>

    {{-- Stock Summary --}}
    <x-card title="Stock Summary" subtitle="Current inventory" icon="boxes" :padding="false">
        <x-slot:headerActions>
            <a href="{{ route('stock.index') }}" class="text-xs font-semibold text-primary-600 hover:text-primary-700">View All →</a>
        </x-slot:headerActions>
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead>
                    <tr class="bg-slate-50 dark:bg-slate-900/50 border-b border-slate-200 dark:border-slate-800">
                        <th class="px-4 py-3 text-left text-[11px] font-bold uppercase tracking-wider text-slate-500">Yarn Name</th>
                        <th class="px-4 py-3 text-right text-[11px] font-bold uppercase tracking-wider text-slate-500">Qty (kg)</th>
                        <th class="px-4 py-3 text-right text-[11px] font-bold uppercase tracking-wider text-slate-500">Avg Cost</th>
                        <th class="px-4 py-3 text-right text-[11px] font-bold uppercase tracking-wider text-slate-500">Value</th>
                        <th class="px-4 py-3 text-center text-[11px] font-bold uppercase tracking-wider text-slate-500">Status</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                    @php $stockList = app(\App\Services\StockService::class)->getStockList(); @endphp
                    @foreach($stockList->take(6) as $stock)
                        <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/50 transition">
                            <td class="px-4 py-3.5 text-sm font-medium text-slate-900 dark:text-white">{{ $stock->name }}</td>
                            <td class="px-4 py-3.5 text-right text-sm counter-num">{{ number_format($stock->quantity) }}</td>
                            <td class="px-4 py-3.5 text-right text-sm counter-num">৳{{ number_format($stock->avg_cost) }}</td>
                            <td class="px-4 py-3.5 text-right text-sm font-bold text-primary-600 dark:text-primary-400 counter-num">৳{{ number_format($stock->stock_value) }}</td>
                            <td class="px-4 py-3.5 text-center">
                                <x-badge :variant="match($stock->status) { 'in_stock' => 'success', 'low_stock' => 'warning', default => 'danger' }">
                                    {{ ucwords(str_replace('_', ' ', $stock->status)) }}
                                </x-badge>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </x-card>
</div>
@endsection

@push('scripts')
<script>
    const baseOptions = {
        chart: { fontFamily: 'Inter, sans-serif', toolbar: { show: false }, animations: { enabled: true, speed: 800 } },
        grid: { borderColor: '#e2e8f0', strokeDashArray: 4 },
        dataLabels: { enabled: false },
        stroke: { curve: 'smooth', width: 3 },
    };

    new ApexCharts(document.querySelector("#chart-purchase"), {
        ...baseOptions, type: 'area',
        series: [{ name: 'Purchase', data: @json(array_values($chartData['purchase'])) }],
        colors: ['#2563eb'],
        fill: { type: 'gradient', gradient: { shadeIntensity: 1, opacityFrom: 0.4, opacityTo: 0.1 } },
        xaxis: { categories: @json($chartData['categories']) },
        yaxis: { labels: { formatter: v => '৳' + (v/1000).toFixed(0) + 'k' } },
    }).render();

    new ApexCharts(document.querySelector("#chart-sales"), {
        ...baseOptions, type: 'bar',
        series: [{ name: 'Sales', data: @json(array_values($chartData['sales'])) }],
        colors: ['#10b981'],
        plotOptions: { bar: { borderRadius: 6, columnWidth: '50%' } },
        xaxis: { categories: @json($chartData['categories']) },
        yaxis: { labels: { formatter: v => '৳' + (v/1000).toFixed(0) + 'k' } },
    }).render();

    new ApexCharts(document.querySelector("#chart-purchase-vs-sales"), {
        ...baseOptions, type: 'line',
        series: [
            { name: 'Purchase', data: @json(array_values($chartData['purchase'])) },
            { name: 'Sales', data: @json(array_values($chartData['sales'])) }
        ],
        colors: ['#2563eb', '#10b981'],
        xaxis: { categories: @json($chartData['categories']) },
        yaxis: { labels: { formatter: v => '৳' + (v/1000).toFixed(0) + 'k' } },
    }).render();

    new ApexCharts(document.querySelector("#chart-stock-movement"), {
        chart: { type: 'donut', fontFamily: 'Inter, sans-serif' },
        series: [@json($stockMovement['inflow']), @json($stockMovement['outflow'])],
        labels: ['Inflow', 'Outflow'],
        colors: ['#3b82f6', '#10b981'],
        legend: { position: 'bottom' },
        plotOptions: { pie: { donut: { size: '70%', labels: { show: true, total: { show: true, label: 'Total', fontSize: '14px' } } } } },
    }).render();

    new ApexCharts(document.querySelector("#chart-profit"), {
        ...baseOptions, type: 'area',
        series: [{ name: 'Profit', data: @json(array_values($profitAnalysis['profit'])) }],
        colors: ['#8b5cf6'],
        fill: { type: 'gradient', gradient: { shadeIntensity: 1, opacityFrom: 0.4, opacityTo: 0.1 } },
        xaxis: { categories: @json($profitAnalysis['categories']) },
        yaxis: { labels: { formatter: v => '৳' + (v/1000).toFixed(0) + 'k' } },
    }).render();
</script>
@endpush
