@extends('admin.layouts.app')

@section('title', __('admin/baskets.buttons_add'))

@section('content')
<div class="container-fluid px-4">
    <x-admin.page-header
        :title="__('admin/baskets.buttons_add')"
        icon="fas fa-shopping-cart"
        :buttons="[
            ['label' => __('admin/common.back'), 'route' => route('admin.baskets.index'), 'icon' => 'fas fa-arrow-left', 'color' => 'outline-secondary'],
        ]"
    />

    <x-admin.alert />

    <form action="{{ route('admin.baskets.store') }}" method="POST" id="createBasketForm">
        @csrf

        <x-admin.card :title="__('admin/baskets.tabs_details')" icon="fas fa-info-circle">
            <div class="row mb-4">
                <div class="col-md-6">
                    <x-admin.fieldset :title="__('admin/baskets.tabs_details')" icon="fas fa-info-circle">
                        <div class="mb-3">
                            <label for="session_id" class="form-label">{{ __('admin/baskets.fields_session_id') }} <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="session_id" name="session_id"
                                   value="{{ Str::uuid() }}" required>
                                   @error('session_id') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                        <div class="mb-3">
                            <label for="ip_address" class="form-label">{{ __('admin/baskets.fields_ip_address') }}</label>
                            <input type="text" class="form-control" id="ip_address" name="ip_address"
                                   value="{{ request()->ip() }}" required>
                        </div>
                        <div class="mb-3">
                            <label for="client_id" class="form-label">{{ __('admin/baskets.fields_client') }}</label>
                            <select class="form-select" id="client_id" name="client_id">
                                <option value="">{{ __('admin/baskets.fields_anonymous') }}</option>
                                @foreach($clients as $client)
                                    <option value="{{ $client->id }}">
                                        {{ $client->name }} ({{ $client->id }})
                                    </option>
                                @endforeach
                            </select>
                        </div>
                    </x-admin.fieldset>
                </div>
                <div class="col-md-6">
                    <x-admin.fieldset :title="__('admin/baskets.tabs_activity')" icon="fas fa-clock">
                        <div class="mb-3">
                            <label for="last_activity_at" class="form-label">{{ __('admin/baskets.fields_last_activity') }}</label>
                            <input type="datetime-local" class="form-control" id="last_activity_at" name="last_activity_at"
                                   value="{{ now()->format('Y-m-d\TH:i') }}">
                        </div>
                        <div class="mb-3">
                            <label for="expires_at" class="form-label">{{ __('admin/baskets.fields_expires_at') }}</label>
                            <input type="datetime-local" class="form-control" id="expires_at" name="expires_at"
                                   value="{{ now()->addDays(config('basket.expiration_days', 30))->format('Y-m-d\TH:i') }}">
                        </div>
                    </x-admin.fieldset>
                </div>
            </div>

            <!-- Basket Items -->
            <x-admin.fieldset :title="__('admin/baskets.tabs_items')" icon="fas fa-box">
                <div class="table-responsive">
                    <table class="table table-bordered" id="basketItemsTable">
                        <thead>
                            <tr>
                                <th>{{ __('admin/baskets.fields_id') }}</th>
                                <th>{{ __('admin/baskets.fields_items') }}</th>
                                <th>{{ __('admin/baskets.fields_description') }}</th>
                                <th>{{ __('admin/baskets.fields_quantity') }}</th>
                                <th>{{ __('admin/baskets.fields_amount') }}</th>
                                <th>{{ __('admin/baskets.fields_setup_amount') }}</th>
                                <th>{{ __('admin/baskets.fields_period') }}</th>
                                <th>{{ __('admin/baskets.fields_period_type') }}</th>
                                <th>{{ __('admin/baskets.fields_actions') }}</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>

                <button type="button" class="btn btn-outline-success btn-sm" id="addItemBtn">
                    <i class="fas fa-plus me-1"></i>
                    {{ __('admin/baskets.actions_add_item') }}
                </button>
            </x-admin.fieldset>

            <!-- Basket Summary -->
            <x-admin.fieldset :title="__('admin/baskets.tabs_statistics')" icon="fas fa-chart-bar">
                <div class="row g-3">
                    <div class="col-md-3">
                        <x-admin.stat-card :title="__('admin/baskets.fields_item_count')" value="0" id="totalItems" icon="fas fa-hashtag" color="primary" />
                    </div>
                    <div class="col-md-3">
                        <x-admin.stat-card :title="__('admin/baskets.fields_total')" value="0.00" id="totalAmount" icon="fas fa-money-bill" color="success" />
                    </div>
                    <div class="col-md-3">
                        <x-admin.stat-card :title="__('admin/baskets.item_types_product')" value="0" id="totalProducts" icon="fas fa-box" color="info" />
                    </div>
                    <div class="col-md-3">
                        <x-admin.stat-card :title="__('admin/baskets.item_types_domain')" value="0" id="totalDomains" icon="fas fa-globe" color="warning" />
                    </div>
                </div>
            </x-admin.fieldset>

            <x-slot:footer>
                <x-admin.form-actions :cancel-url="route('admin.baskets.index')" />
            </x-slot:footer>
        </x-admin.card>
    </form>
</div>
@endsection

@push('scripts')
<script>
    // Sepet oluşturma sayfası için JavaScript kodları
    document.addEventListener('DOMContentLoaded', function() {
        initializeBasketCreate();
    });

    function initializeBasketCreate() {
        // Ürün ekleme butonu
        document.getElementById('addItemBtn')?.addEventListener('click', addNewItem);

        // Ürün silme butonları
        document.addEventListener('click', function(e) {
            if (e.target.closest('.remove-item')) {
                removeItem(e.target.closest('tr'));
            }
        });

        // Form değişikliklerinde özeti güncelle
        document.getElementById('createBasketForm')?.addEventListener('input', updateSummary);

        // İlk yüklemede özeti güncelle
        updateSummary();
    }

    function addNewItem() {
        const tbody = document.querySelector('#basketItemsTable tbody');
        const itemCount = tbody.children.length;

        const newRow = document.createElement('tr');
        newRow.setAttribute('data-item-index', itemCount);
        newRow.innerHTML = `
            <td>${itemCount + 1}</td>
            <td>
                <input type="text" class="form-control form-control-sm"
                       name="basket_data[items][${itemCount}][name]"
                       placeholder="Ürün adı" required>
                <select class="form-select form-select-sm mt-1"
                        name="basket_data[items][${itemCount}][type]" required>
                    <option value="product">{{ __('admin/baskets.item_types_product') }}</option>
                    <option value="domain">{{ __('admin/baskets.item_types_domain') }}</option>
                </select>
            </td>
            <td>
                <textarea class="form-control form-control-sm"
                          name="basket_data[items][${itemCount}][description]"
                          rows="2" placeholder="Açıklama"></textarea>
            </td>
            <td>
                <input type="number" class="form-control form-control-sm"
                       name="basket_data[items][${itemCount}][quantity]"
                       value="1" min="1" max="99" required>
            </td>
            <td>
                <input type="number" class="form-control form-control-sm"
                       name="basket_data[items][${itemCount}][price]"
                       value="0" min="0" step="0.01" required>
            </td>
            <td>
                <input type="number" class="form-control form-control-sm"
                       name="basket_data[items][${itemCount}][setup_amount]"
                       value="0" min="0" step="0.01">
            </td>
            <td>
                <input type="number" class="form-control form-control-sm"
                       name="basket_data[items][${itemCount}][period]"
                       value="1" min="1" required>
            </td>
            <td>
                <select class="form-select form-select-sm"
                        name="basket_data[items][${itemCount}][period_type]" required>
                    <option value="month">{{ __('admin/baskets.period_types_month') }}</option>
                    <option value="year">{{ __('admin/baskets.period_types_year') }}</option>
                </select>
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-outline-danger remove-item">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;

        tbody.appendChild(newRow);
        updateSummary();
    }

    function removeItem(row) {
        if (confirm('Bu ürünü silmek istediğinizden emin misiniz?')) {
            row.remove();
            updateSummary();
            updateRowNumbers();
        }
    }

    function updateRowNumbers() {
        const rows = document.querySelectorAll('#basketItemsTable tbody tr');
        rows.forEach((row, index) => {
            row.setAttribute('data-item-index', index);
            row.cells[0].textContent = index + 1;

            // Input name'lerini güncelle
            const inputs = row.querySelectorAll('input, select, textarea');
            inputs.forEach(input => {
                const name = input.getAttribute('name');
                if (name) {
                    input.setAttribute('name', name.replace(/\[\d+\]/, `[${index}]`));
                }
            });
        });
    }

    function updateSummary() {
        const rows = document.querySelectorAll('#basketItemsTable tbody tr');
        let totalItems = 0;
        let totalAmount = 0;
        let totalProducts = 0;
        let totalDomains = 0;

        rows.forEach(row => {
            const quantity = parseInt(row.querySelector('input[name*="[quantity]"]')?.value || 1);
            const price = parseFloat(row.querySelector('input[name*="[price]"]')?.value || 0);
            const type = row.querySelector('select[name*="[type]"]')?.value || 'product';

            totalItems += quantity;
            totalAmount += quantity * price;

            if (type === 'product') {
                totalProducts += quantity;
            } else if (type === 'domain') {
                totalDomains += quantity;
            }
        });

        document.getElementById('totalItems').textContent = totalItems;
        document.getElementById('totalAmount').textContent = totalAmount.toFixed(2);
        document.getElementById('totalProducts').textContent = totalProducts;
        document.getElementById('totalDomains').textContent = totalDomains;
    }
</script>
@endpush
