@extends('layouts.app')

@section('content')
<div class="container mx-auto px-4 py-6">
    <div class="max-w-5xl mx-auto">
        <!-- Header -->
        <div class="mb-6">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 dark:text-white">Upload TikTok Data</h1>
                    <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">Upload sales data and ads spending - two separate uploads below</p>
                </div>
                <a href="{{ route('tiktok-shop.index') }}" class="px-5 py-2.5 bg-red-600 text-white text-base font-bold rounded-lg hover:bg-red-700 shadow-md transition-all">
                    ← Back to List
                </a>
            </div>
        </div>

        <!-- Sales Data Upload Section -->
        <div class="mb-6">
            <h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-2">📱 Upload TikTok Shop Sales Data</h2>
            <p class="text-sm text-gray-600 dark:text-gray-400">Import your TikTok Shop income report (Excel file)</p>
        </div>

        <!-- Upload Card -->
        <div class="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
            <form action="{{ route('tiktok-shop.upload.process') }}" method="POST" enctype="multipart/form-data">
                @csrf

                <!-- Instructions -->
                <div class="mb-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded border border-blue-200 dark:border-blue-800">
                    <h3 class="text-sm font-semibold text-blue-900 dark:text-blue-200 mb-2">📋 How to get your TikTok Shop income report:</h3>
                    <ol class="text-xs text-blue-800 dark:text-blue-300 space-y-1 ml-4 list-decimal">
                        <li>Go to TikTok Shop Seller Center</li>
                        <li>Navigate to: <strong>Finance → Income</strong></li>
                        <li>Select your date range</li>
                        <li>Click <strong>"Export"</strong> button</li>
                        <li>Download the Excel file (income_*.xlsx)</li>
                        <li>Upload it here</li>
                    </ol>
                </div>

                <!-- TikTok Shop Selection -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Select TikTok Shop <span class="text-red-500">*</span>
                    </label>
                    <select name="tiktok_shop_id"
                            id="tiktok_shop_id_sales"
                            required
                            onchange="updateUploadAsDropdown('sales')"
                            class="block w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-white">
                        <option value="">-- Select Shop --</option>
                        @foreach($tiktokShops as $shop)
                            <option value="{{ $shop->id }}" {{ old('tiktok_shop_id') == $shop->id ? 'selected' : '' }}>
                                {{ $shop->name }}
                            </option>
                        @endforeach
                    </select>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Choose which TikTok Shop these transactions belong to
                    </p>
                    @error('tiktok_shop_id')
                        <p class="mt-1 text-xs text-red-600 dark:text-red-400">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Upload As (Admin Only) -->
                @if(auth()->user()->isAdmin())
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Upload As (Credit Assignment)
                    </label>
                    <select name="upload_as"
                            id="upload_as_sales"
                            class="block w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-white">
                        <option value="">-- Select Manager (Optional) --</option>
                    </select>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Choose which manager should receive KPI credit for this upload. Leave empty to credit yourself.
                    </p>
                    @error('upload_as')
                        <p class="mt-1 text-xs text-red-600 dark:text-red-400">{{ $message }}</p>
                    @enderror
                </div>
                @endif

                <!-- File Upload -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Select TikTok Excel File <span class="text-red-500">*</span>
                    </label>
                    <input type="file"
                           name="file"
                           accept=".xlsx,.xls"
                           required
                           class="block w-full text-sm text-gray-900 dark:text-white
                                  border border-gray-300 dark:border-gray-600 rounded-lg cursor-pointer
                                  bg-gray-50 dark:bg-gray-700
                                  file:mr-4 file:py-2 file:px-4
                                  file:rounded-l-lg file:border-0
                                  file:text-sm file:font-semibold
                                  file:bg-indigo-500 file:text-white
                                  hover:file:bg-indigo-600">
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Excel files only (.xlsx, .xls) - Max 10MB
                    </p>
                    @error('file')
                        <p class="mt-1 text-xs text-red-600 dark:text-red-400">{{ $message }}</p>
                    @enderror
                </div>

                <!-- What happens next -->
                <div class="mb-6 p-4 bg-gray-50 dark:bg-gray-700 rounded">
                    <h3 class="text-sm font-semibold text-gray-900 dark:text-white mb-2">✨ What happens next:</h3>
                    <ul class="text-xs text-gray-600 dark:text-gray-400 space-y-1 ml-4 list-disc">
                        <li>We'll read your Excel file and extract the important data</li>
                        <li>You'll see a preview with summary (revenue, fees, orders count)</li>
                        <li>You can review before importing to the system</li>
                        <li>Duplicate orders will be automatically skipped</li>
                        <li>Data will appear in your dashboard automatically</li>
                    </ul>
                </div>

                <!-- Submit Button -->
                <div class="flex gap-3">
                    <button type="submit"
                            class="flex-1 px-6 py-3 bg-blue-600 text-white text-base font-bold rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 shadow-md transition-all">
                        Upload & Preview
                    </button>
                    <a href="{{ route('tiktok-shop.index') }}"
                       class="px-6 py-3 bg-red-600 text-white text-base font-semibold rounded-lg hover:bg-red-700 text-center shadow-md transition-all">
                        Cancel
                    </a>
                </div>
            </form>
        </div>

        <!-- Help Note -->
        <div class="mt-4 p-4 bg-yellow-50 dark:bg-yellow-900/20 rounded border border-yellow-200 dark:border-yellow-800">
            <p class="text-xs text-yellow-800 dark:text-yellow-300">
                <strong>💡 Note:</strong> The TikTok Excel file contains 50+ columns. We only extract what matters:
                <strong>Date, Revenue, Fees, and Net Settlement</strong>. This makes it much easier to understand your TikTok Shop performance!
            </p>
        </div>

        <!-- Divider -->
        <div class="my-8 border-t-2 border-gray-300 dark:border-gray-600"></div>

        <!-- Ads Spending Upload Section -->
        <div class="mb-6">
            <h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-2">💰 Upload Ads Spending Data</h2>
            <p class="text-sm text-gray-600 dark:text-gray-400">Import your TikTok Ads transaction/billing data</p>
        </div>

        <!-- Ads Upload Card -->
        <div class="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
            <form action="{{ route('tiktok-shop.ads.upload') }}" method="POST" enctype="multipart/form-data">
                @csrf

                <!-- Instructions -->
                <div class="mb-6 p-4 bg-purple-50 dark:bg-purple-900/20 rounded border border-purple-200 dark:border-purple-800">
                    <h3 class="text-sm font-semibold text-purple-900 dark:text-purple-200 mb-2">📋 How to get your TikTok Ads billing data:</h3>
                    <ol class="text-xs text-purple-800 dark:text-purple-300 space-y-1 ml-4 list-decimal">
                        <li>Go to TikTok Ads Manager</li>
                        <li>Navigate to: <strong>Billing → Transaction History</strong></li>
                        <li>Select your date range</li>
                        <li>Click <strong>"Export"</strong> or download button</li>
                        <li>Download the Excel file (Transaction_*.xlsx)</li>
                        <li>Upload it here</li>
                    </ol>
                </div>

                <!-- TikTok Shop Selection -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Select TikTok Shop <span class="text-red-500">*</span>
                    </label>
                    <select name="tiktok_shop_id"
                            id="tiktok_shop_id_ads"
                            required
                            onchange="updateUploadAsDropdown('ads')"
                            class="block w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:text-white">
                        <option value="">-- Select Shop --</option>
                        @foreach($tiktokShops as $shop)
                            <option value="{{ $shop->id }}" {{ old('tiktok_shop_id') == $shop->id ? 'selected' : '' }}>
                                {{ $shop->name }}
                            </option>
                        @endforeach
                    </select>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Choose which TikTok Shop these ads transactions belong to
                    </p>
                    @error('tiktok_shop_id')
                        <p class="mt-1 text-xs text-red-600 dark:text-red-400">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Upload As (Admin Only) -->
                @if(auth()->user()->isAdmin())
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Upload As (Credit Assignment)
                    </label>
                    <select name="upload_as"
                            id="upload_as_ads"
                            class="block w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:text-white">
                        <option value="">-- Select Manager (Optional) --</option>
                    </select>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Choose which manager should receive KPI credit for this upload. Leave empty to credit yourself.
                    </p>
                    @error('upload_as')
                        <p class="mt-1 text-xs text-red-600 dark:text-red-400">{{ $message }}</p>
                    @enderror
                </div>
                @endif

                <!-- File Upload -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Select Ads Spending Excel File <span class="text-red-500">*</span>
                    </label>
                    <input type="file"
                           name="ads_file"
                           accept=".xlsx,.xls"
                           required
                           class="block w-full text-sm text-gray-900 dark:text-white
                                  border border-gray-300 dark:border-gray-600 rounded-lg cursor-pointer
                                  bg-gray-50 dark:bg-gray-700
                                  file:mr-4 file:py-2 file:px-4
                                  file:rounded-l-lg file:border-0
                                  file:text-sm file:font-semibold
                                  file:bg-purple-500 file:text-white
                                  hover:file:bg-purple-600">
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Excel files only (.xlsx, .xls) - Max 10MB
                    </p>
                    @error('ads_file')
                        <p class="mt-1 text-xs text-red-600 dark:text-red-400">{{ $message }}</p>
                    @enderror
                </div>

                <!-- What happens next -->
                <div class="mb-6 p-4 bg-gray-50 dark:bg-gray-700 rounded">
                    <h3 class="text-sm font-semibold text-gray-900 dark:text-white mb-2">✨ What happens next:</h3>
                    <ul class="text-xs text-gray-600 dark:text-gray-400 space-y-1 ml-4 list-disc">
                        <li>We'll extract: Transaction Date, Amount, Payment Method, and Status</li>
                        <li>You'll see a preview with monthly spending summary</li>
                        <li>You can review before importing to the system</li>
                        <li>Duplicate transactions will be automatically skipped</li>
                        <li>Data will be displayed alongside your TikTok Shop sales data</li>
                    </ul>
                </div>

                <!-- Submit Button -->
                <div class="flex gap-3">
                    <button type="submit"
                            class="flex-1 px-6 py-3 bg-purple-600 text-white text-base font-bold rounded-lg hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 shadow-md transition-all">
                        Upload Ads Data & Preview
                    </button>
                    <a href="{{ route('tiktok-shop.index') }}"
                       class="px-6 py-3 bg-red-600 text-white text-base font-semibold rounded-lg hover:bg-red-700 text-center shadow-md transition-all">
                        Cancel
                    </a>
                </div>
            </form>
        </div>
    </div>
</div>

@if(auth()->user()->isAdmin())
<script>
    // Data structure: Map shops to their assigned managers
    const shopManagersData = {
        @foreach($tiktokShops as $shop)
            {{ $shop->id }}: [
                @foreach($shop->users ?? [] as $user)
                    {id: {{ $user->id }}, name: "{{ $user->name }}"},
                @endforeach
            ],
        @endforeach
    };

    // All managers with TikTok shop access
    const allManagers = [
        @foreach($managers as $manager)
            {id: {{ $manager->id }}, name: "{{ $manager->name }}", shopIds: [{{ implode(',', $manager->getTikTokShopIds()) }}]},
        @endforeach
    ];

    /**
     * Update the "Upload as" dropdown based on selected shop
     * @param {string} type - 'sales' or 'ads'
     */
    function updateUploadAsDropdown(type) {
        const shopSelect = document.getElementById('tiktok_shop_id_' + type);
        const uploadAsSelect = document.getElementById('upload_as_' + type);

        if (!shopSelect || !uploadAsSelect) return;

        const selectedShopId = parseInt(shopSelect.value);

        // Clear current options
        uploadAsSelect.innerHTML = '<option value="">-- Select Manager (Optional) --</option>';

        if (!selectedShopId) return;

        // Filter managers who have access to this shop
        const availableManagers = allManagers.filter(manager =>
            manager.shopIds.includes(selectedShopId)
        );

        // Populate dropdown
        availableManagers.forEach(manager => {
            const option = document.createElement('option');
            option.value = manager.id;
            option.textContent = manager.name;
            uploadAsSelect.appendChild(option);
        });

        // Show message if no managers available
        if (availableManagers.length === 0) {
            const option = document.createElement('option');
            option.value = '';
            option.textContent = 'No managers assigned to this shop';
            option.disabled = true;
            uploadAsSelect.appendChild(option);
        }
    }

    // Initialize dropdowns on page load
    document.addEventListener('DOMContentLoaded', function() {
        updateUploadAsDropdown('sales');
        updateUploadAsDropdown('ads');
    });
</script>
@endif

@endsection
