@extends('layouts.app')

@section('content')
<div class="container mx-auto px-4 py-6">
    <!-- Header -->
    <div class="mb-6">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-gray-900 dark:text-white">📱 TikTok Shop Management</h1>
                <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">Simplified view of your TikTok Shop sales and advertising costs</p>
            </div>
            <a href="{{ route('tiktok-shop.upload') }}" class="px-5 py-2.5 bg-blue-600 text-white text-base font-bold rounded-lg hover:bg-blue-700 shadow-md transition-all">
                Upload New Data
            </a>
        </div>
    </div>

    <!-- Shop Selector (if multiple shops available) -->
    @if($availableShops->count() > 1)
    <div class="mb-6">
        <form method="GET" action="{{ route('tiktok-shop.index') }}" class="flex items-center gap-4">
            <input type="hidden" name="start_date" value="{{ $startDate }}">
            <input type="hidden" name="end_date" value="{{ $endDate }}">

            <label class="text-sm font-medium text-gray-700 dark:text-gray-300">Filter by Shop:</label>
            <select name="shop_id" onchange="this.form.submit()" class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white">
                <option value="">All TikTok Shops</option>
                @foreach($availableShops as $shop)
                    <option value="{{ $shop->id }}" {{ $selectedShopId == $shop->id ? 'selected' : '' }}>
                        {{ $shop->name }}
                    </option>
                @endforeach
            </select>

            @if($selectedShopId)
                <a href="{{ route('tiktok-shop.index', ['start_date' => $startDate, 'end_date' => $endDate]) }}"
                   class="text-sm text-blue-600 hover:text-blue-800 dark:text-blue-400">
                    Clear Filter
                </a>
            @endif
        </form>
    </div>
    @endif

    <!-- Multi-Shop Summary Card (shown when viewing all shops) -->
    @if($shopSummaries && $shopSummaries->count() > 0)
    <div class="bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-6 mb-6">
        <h3 class="text-lg font-bold text-blue-900 dark:text-blue-200 mb-4">
            📊 All TikTok Shops Summary ({{ \Carbon\Carbon::parse($startDate)->format('M d') }} - {{ \Carbon\Carbon::parse($endDate)->format('M d, Y') }})
        </h3>

        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            @php
                $totalOrders = 0;
                $totalRevenue = 0;
                $totalSettlement = 0;
            @endphp

            @foreach($availableShops as $shop)
                @php
                    $shopData = $shopSummaries->get($shop->id);
                    $orders = $shopData->total_orders ?? 0;
                    $revenue = $shopData->total_revenue ?? 0;
                    $settlement = $shopData->total_settlement ?? 0;

                    $totalOrders += $orders;
                    $totalRevenue += $revenue;
                    $totalSettlement += $settlement;
                @endphp

                <a href="{{ route('tiktok-shop.index', ['shop_id' => $shop->id, 'start_date' => $startDate, 'end_date' => $endDate]) }}"
                   class="block bg-white dark:bg-gray-800 rounded-lg p-4 border-2 border-transparent hover:border-blue-500 transition-all shadow-sm hover:shadow-md">
                    <div class="flex items-start justify-between mb-2">
                        <h4 class="font-semibold text-gray-900 dark:text-white">{{ $shop->name }}</h4>
                        <svg class="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                        </svg>
                    </div>
                    <div class="space-y-1 text-sm">
                        <div class="flex justify-between">
                            <span class="text-gray-600 dark:text-gray-400">Orders:</span>
                            <span class="font-semibold text-gray-900 dark:text-white">{{ number_format($orders) }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600 dark:text-gray-400">Revenue:</span>
                            <span class="font-semibold text-green-600 dark:text-green-400">RM {{ number_format($revenue, 2) }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600 dark:text-gray-400">Settlement:</span>
                            <span class="font-semibold text-indigo-600 dark:text-indigo-400">RM {{ number_format($settlement, 2) }}</span>
                        </div>
                    </div>
                </a>
            @endforeach
        </div>

        <!-- Grand Total -->
        @if($availableShops->count() > 1)
        <div class="mt-4 pt-4 border-t-2 border-blue-300 dark:border-blue-700">
            <div class="flex justify-between items-center">
                <span class="text-sm font-bold text-blue-900 dark:text-blue-200">TOTAL (All Shops):</span>
                <div class="flex gap-6 text-sm font-bold">
                    <span class="text-gray-900 dark:text-white">{{ number_format($totalOrders) }} orders</span>
                    <span class="text-green-600 dark:text-green-400">RM {{ number_format($totalRevenue, 2) }}</span>
                    <span class="text-indigo-600 dark:text-indigo-400">RM {{ number_format($totalSettlement, 2) }}</span>
                </div>
            </div>
        </div>
        @endif
    </div>
    @endif

    <!-- Summary Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white dark:bg-gray-800 shadow rounded-lg p-4">
            <div class="text-xs text-gray-600 dark:text-gray-400">Total Orders</div>
            <div class="text-2xl font-bold text-gray-900 dark:text-white">{{ number_format($summary->total_orders ?? 0) }}</div>
            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ $summary->total_refunds ?? 0 }} refunds</div>
        </div>

        <div class="bg-white dark:bg-gray-800 shadow rounded-lg p-4">
            <div class="text-xs text-gray-600 dark:text-gray-400">Gross Revenue</div>
            <div class="text-2xl font-bold text-green-600 dark:text-green-400">RM {{ number_format($summary->total_revenue ?? 0, 2) }}</div>
            @if(($summary->total_refund_amount ?? 0) > 0)
            <div class="text-xs text-red-600 dark:text-red-400 mt-1">- RM {{ number_format($summary->total_refund_amount ?? 0, 2) }} refunds</div>
            @else
            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">Avg: RM {{ number_format($summary->avg_order_value ?? 0, 2) }}</div>
            @endif
        </div>

        <div class="bg-white dark:bg-gray-800 shadow rounded-lg p-4">
            <div class="text-xs text-gray-600 dark:text-gray-400">TikTok Fees</div>
            <div class="text-2xl font-bold text-orange-600 dark:text-orange-400">RM {{ number_format(abs($summary->total_fees ?? 0), 2) }}</div>
            @php $feePercent = ($summary->total_revenue ?? 0) > 0 ? (abs($summary->total_fees ?? 0) / ($summary->total_revenue ?? 0)) * 100 : 0; @endphp
            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ number_format($feePercent, 1) }}% of gross</div>
        </div>

        <div class="bg-white dark:bg-gray-800 shadow rounded-lg p-4 border-2 border-indigo-500">
            <div class="text-xs text-gray-600 dark:text-gray-400 flex items-center">
                <span>💰 Bank Transfer Amount</span>
            </div>
            <div class="text-2xl font-bold text-indigo-600 dark:text-indigo-400">RM {{ number_format($summary->total_settlement ?? 0, 2) }}</div>
            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">After refunds & fees</div>
        </div>
    </div>

    <!-- Revenue Breakdown (Optional: Show calculation) -->
    @if(($summary->total_refund_amount ?? 0) > 0)
    <div class="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mb-6">
        <h3 class="text-sm font-semibold text-blue-900 dark:text-blue-200 mb-3">💡 Settlement Calculation</h3>
        <div class="space-y-2 text-sm">
            <div class="flex justify-between text-gray-700 dark:text-gray-300">
                <span>Gross Revenue ({{ number_format($summary->total_orders ?? 0) }} orders)</span>
                <span class="font-mono">RM {{ number_format($summary->total_revenue ?? 0, 2) }}</span>
            </div>
            <div class="flex justify-between text-red-600 dark:text-red-400">
                <span>Less: Refunds ({{ $summary->total_refunds ?? 0 }} refunds)</span>
                <span class="font-mono">- RM {{ number_format($summary->total_refund_amount ?? 0, 2) }}</span>
            </div>
            <div class="flex justify-between text-orange-600 dark:text-orange-400">
                <span>Less: TikTok Fees</span>
                <span class="font-mono">- RM {{ number_format(abs($summary->total_fees ?? 0), 2) }}</span>
            </div>
            <div class="border-t border-blue-300 dark:border-blue-700 pt-2 mt-2"></div>
            <div class="flex justify-between text-indigo-600 dark:text-indigo-400 font-bold text-base">
                <span>= Bank Transfer Amount</span>
                <span class="font-mono">RM {{ number_format($summary->total_settlement ?? 0, 2) }}</span>
            </div>
        </div>
    </div>
    @endif

    <!-- Ads Spending Summary -->
    @if($adsSpending && count($adsSpending) > 0)
    <div class="bg-white dark:bg-gray-800 shadow rounded-lg p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">💰 Ads Spending by Month</h2>

        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                <thead class="bg-purple-50 dark:bg-purple-900/20">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-purple-900 dark:text-purple-200">Month</th>
                        <th class="px-6 py-3 text-right text-xs font-semibold text-purple-900 dark:text-purple-200">Transactions</th>
                        <th class="px-6 py-3 text-right text-xs font-semibold text-purple-900 dark:text-purple-200">Total Spent</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                    @foreach($adsSpending as $month)
                    <tr class="hover:bg-purple-50 dark:hover:bg-purple-900/10">
                        <td class="px-6 py-3 text-sm font-medium text-gray-900 dark:text-white">
                            {{ \Carbon\Carbon::parse($month->month . '-01')->format('F Y') }}
                        </td>
                        <td class="px-6 py-3 text-sm text-right text-gray-600 dark:text-gray-400">
                            {{ number_format($month->transaction_count) }} payments
                        </td>
                        <td class="px-6 py-3 text-sm text-right font-mono font-bold text-purple-600 dark:text-purple-400">
                            RM {{ number_format($month->total_spent, 2) }}
                        </td>
                    </tr>
                    @endforeach
                    <tr class="bg-purple-100 dark:bg-purple-900/30 font-bold">
                        <td class="px-6 py-3 text-sm text-gray-900 dark:text-white">Total</td>
                        <td class="px-6 py-3 text-sm text-right text-gray-900 dark:text-white">
                            {{ number_format($adsSpending->sum('transaction_count')) }} payments
                        </td>
                        <td class="px-6 py-3 text-sm text-right font-mono text-purple-700 dark:text-purple-300">
                            RM {{ number_format($adsSpending->sum('total_spent'), 2) }}
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <p class="text-xs text-gray-500 dark:text-gray-400 mt-3">
            💡 This shows your TikTok Ads spending. Use this for manual ROI calculations across all sales channels.
        </p>
    </div>
    @endif

    <!-- Filter -->
    <div class="bg-white dark:bg-gray-800 shadow rounded-lg p-4 mb-6">
        <!-- Quick Filter Buttons -->
        <div class="mb-4">
            <label class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2 block">Quick Filters:</label>
            <div class="flex flex-wrap gap-2">
                @php
                    $quickFilters = [
                        'this_month' => ['label' => 'This Month', 'start' => now()->startOfMonth()->format('Y-m-d'), 'end' => now()->endOfMonth()->format('Y-m-d')],
                        'last_month' => ['label' => 'Last Month', 'start' => now()->subMonth()->startOfMonth()->format('Y-m-d'), 'end' => now()->subMonth()->endOfMonth()->format('Y-m-d')],
                        '6_months' => ['label' => '6 Months', 'start' => now()->subMonths(6)->startOfMonth()->format('Y-m-d'), 'end' => now()->endOfMonth()->format('Y-m-d')],
                        'this_year' => ['label' => 'This Year', 'start' => now()->startOfYear()->format('Y-m-d'), 'end' => now()->endOfYear()->format('Y-m-d')],
                        'last_year' => ['label' => 'Last Year', 'start' => now()->subYear()->startOfYear()->format('Y-m-d'), 'end' => now()->subYear()->endOfYear()->format('Y-m-d')],
                    ];
                    $isCustom = true;
                @endphp

                @foreach($quickFilters as $key => $filter)
                    @php
                        $isActive = ($startDate === $filter['start'] && $endDate === $filter['end']);
                        if ($isActive) $isCustom = false;
                    @endphp
                    <a href="{{ route('tiktok-shop.index', array_merge(['start_date' => $filter['start'], 'end_date' => $filter['end']], $selectedShopId ? ['shop_id' => $selectedShopId] : [])) }}"
                       class="px-4 py-2 text-sm font-medium rounded-lg transition-all {{ $isActive ? 'bg-blue-600 text-white shadow-md' : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600' }}">
                        {{ $filter['label'] }}
                    </a>
                @endforeach

                <button type="button" onclick="toggleCustomRange()" id="customRangeBtn"
                        class="px-4 py-2 text-sm font-medium rounded-lg transition-all {{ $isCustom ? 'bg-blue-600 text-white shadow-md' : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600' }}">
                    Custom Range
                </button>
            </div>
        </div>

        <!-- Custom Range Form (Hidden by default, shown when Custom Range is active) -->
        <div id="customRangeForm" style="display: {{ $isCustom ? 'block' : 'none' }};" class="border-t border-gray-200 dark:border-gray-700 pt-4">
            <form method="GET" action="{{ route('tiktok-shop.index') }}" class="flex gap-3 items-end">
                @if($selectedShopId)
                    <input type="hidden" name="shop_id" value="{{ $selectedShopId }}">
                @endif
                <div class="flex-1">
                    <label class="text-xs text-gray-600 dark:text-gray-400">Settlement Start Date</label>
                    <input type="date" name="start_date" value="{{ $startDate }}" required class="w-full px-3 py-2 text-sm border rounded dark:bg-gray-700 dark:border-gray-600">
                </div>
                <div class="flex-1">
                    <label class="text-xs text-gray-600 dark:text-gray-400">Settlement End Date</label>
                    <input type="date" name="end_date" value="{{ $endDate }}" required class="w-full px-3 py-2 text-sm border rounded dark:bg-gray-700 dark:border-gray-600">
                </div>
                <button type="submit" class="px-5 py-2.5 bg-blue-600 text-white text-base font-bold rounded-lg hover:bg-blue-700 shadow-md transition-all">Filter</button>
            </form>
        </div>

        <p class="text-xs text-gray-500 dark:text-gray-400 mt-3">💡 Filtering by settlement date (when TikTok paid you), not order date</p>
    </div>

    <script>
        function toggleCustomRange() {
            const form = document.getElementById('customRangeForm');
            const isHidden = form.style.display === 'none';
            form.style.display = isHidden ? 'block' : 'none';
        }
    </script>

    <!-- Transactions List -->
    <div class="bg-white dark:bg-gray-800 shadow rounded-lg overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
            <h2 class="text-lg font-semibold text-gray-900 dark:text-white">Transactions ({{ $transactions->total() }})</h2>
        </div>

        @if($transactions->count() > 0)
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                <thead class="bg-gray-50 dark:bg-gray-700">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 dark:text-gray-300">Settled Date</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 dark:text-gray-300">Order ID</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 dark:text-gray-300">Type</th>
                        <th class="px-6 py-3 text-right text-xs font-semibold text-gray-700 dark:text-gray-300">Revenue</th>
                        <th class="px-6 py-3 text-right text-xs font-semibold text-gray-700 dark:text-gray-300">Fees</th>
                        <th class="px-6 py-3 text-right text-xs font-semibold text-gray-700 dark:text-gray-300">Net</th>
                        <th class="px-6 py-3 text-center text-xs font-semibold text-gray-700 dark:text-gray-300">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                    @foreach($transactions as $transaction)
                    <tr class="hover:bg-gray-50 dark:hover:bg-gray-700">
                        <td class="px-6 py-3 text-sm text-gray-900 dark:text-white">
                            {{ $transaction->settled_date ? $transaction->settled_date->format('Y-m-d') : '-' }}
                            @if($transaction->order_date != $transaction->settled_date)
                            <span class="text-xs text-gray-500 dark:text-gray-400 block">Order: {{ $transaction->order_date->format('Y-m-d') }}</span>
                            @endif
                        </td>
                        <td class="px-6 py-3 text-sm font-mono text-gray-600 dark:text-gray-400">{{ Str::limit($transaction->order_id, 20) }}</td>
                        <td class="px-6 py-3">
                            @if($transaction->type === 'Order')
                                <span class="px-2 py-1 text-xs rounded bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">Order</span>
                            @else
                                <span class="px-2 py-1 text-xs rounded bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200">{{ $transaction->type }}</span>
                            @endif
                        </td>
                        <td class="px-6 py-3 text-sm text-right font-mono text-gray-900 dark:text-white">RM {{ number_format($transaction->total_revenue, 2) }}</td>
                        <td class="px-6 py-3 text-sm text-right font-mono text-red-600">RM {{ number_format(abs($transaction->total_fees), 2) }}</td>
                        <td class="px-6 py-3 text-sm text-right font-mono font-semibold text-indigo-600">RM {{ number_format($transaction->net_settlement, 2) }}</td>
                        <td class="px-6 py-3 text-center">
                            <form action="{{ route('tiktok-shop.destroy', $transaction->id) }}" method="POST" class="inline" onsubmit="return confirm('Delete this transaction?')">
                                @csrf
                                @method('DELETE')
                                <button type="submit" class="px-3 py-1.5 bg-red-600 text-white text-xs font-semibold rounded hover:bg-red-700 transition-all">Delete</button>
                            </form>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>

        <div class="px-6 py-4 border-t border-gray-200 dark:border-gray-700">
            {{ $transactions->links() }}
        </div>
        @else
        <div class="p-12 text-center">
            <div class="text-4xl mb-4">📱</div>
            <p class="text-gray-600 dark:text-gray-400 mb-4 text-lg font-medium">No TikTok Shop data yet</p>
            <a href="{{ route('tiktok-shop.upload') }}" class="px-6 py-3 bg-blue-600 text-white text-base font-bold rounded-lg hover:bg-blue-700 shadow-md transition-all inline-block">
                Upload Your First Report
            </a>
        </div>
        @endif
    </div>
</div>
@endsection
