@extends('admin.layouts.app')

@section('title', __('admin/baskets.buttons_edit') . ' - ' . __('admin/baskets.singular') . ' #' . $basket->id)

@section('content')
<div class="container-fluid px-4">
    <x-admin.page-header
        :title="__('admin/baskets.buttons_edit') . ' - ' . __('admin/baskets.singular') . ' #' . $basket->id"
        icon="fas fa-shopping-cart"
        :buttons="[
            ['label' => __('admin/baskets.buttons_view'), 'route' => route('admin.baskets.show', $basket), 'icon' => 'fas fa-eye', 'color' => 'outline-info'],
            ['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.update', $basket) }}" method="POST" id="editBasketForm">
        @csrf
        @method('PUT')

        <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') }}</label>
                            <input type="text" class="form-control" id="session_id" name="session_id" value="{{ $basket->session_id }}" required>
                        </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="{{ $basket->ip_address }}" 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 }}" @selected($basket->client_id == $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="{{ $basket->last_activity_at ? $basket->last_activity_at->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="{{ $basket->expires_at ? $basket->expires_at->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>
                            @foreach($basket->items as $index => $item)
                                <tr data-item-index="{{ $index }}">
                                    <td>{{ $index + 1 }}</td>
                                    <td>
                                        <input type="text" class="form-control form-control-sm"
                                               name="basket_data[items][{{ $index }}][name]"
                                               value="{{ $item['name'] ?? '' }}" placeholder="Ürün adı">
                                        <select class="form-select form-select-sm mt-1"
                                                name="basket_data[items][{{ $index }}][type]">
                                            <option value="product" @selected(($item['type'] ?? '') === 'product')>
                                                {{ __('admin/baskets.item_types_product') }}
                                            </option>
                                            <option value="domain" @selected(($item['type'] ?? '') === 'domain')>
                                                {{ __('admin/baskets.item_types_domain') }}
                                            </option>
                                        </select>
                                    </td>
                                    <td>
                                        <textarea class="form-control form-control-sm"
                                                  name="basket_data[items][{{ $index }}][description]"
                                                  rows="2" placeholder="Açıklama">{{ $item['description'] ?? '' }}</textarea>
                                    </td>
                                    <td>
                                        <input type="number" class="form-control form-control-sm"
                                               name="basket_data[items][{{ $index }}][quantity]"
                                               value="{{ $item['quantity'] ?? 1 }}" min="1" max="99">
                                    </td>
                                    <td>
                                        <input type="number" class="form-control form-control-sm"
                                               name="basket_data[items][{{ $index }}][price]"
                                               value="{{ $item['price'] ?? 0 }}" min="0" step="0.01">
                                    </td>
                                    <td>
                                        <input type="number" class="form-control form-control-sm"
                                               name="basket_data[items][{{ $index }}][setup_amount]"
                                               value="{{ $item['setup_amount'] ?? 0 }}" min="0" step="0.01">
                                    </td>
                                    <td>
                                        <input type="number" class="form-control form-control-sm"
                                               name="basket_data[items][{{ $index }}][period]"
                                               value="{{ $item['period'] ?? 1 }}" min="1">
                                    </td>
                                    <td>
                                        <select class="form-select form-select-sm"
                                                name="basket_data[items][{{ $index }}][period_type]">
                                            <option value="month" @selected(($item['period_type'] ?? '') === 'month')>
                                                {{ __('admin/baskets.period_types_month') }}
                                            </option>
                                            <option value="year" @selected(($item['period_type'] ?? '') === '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>
                                </tr>
                            @endforeach
                        </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 düzenleme sayfası için JavaScript kodları
    document.addEventListener('DOMContentLoaded', function() {
        initializeBasketEdit();
    });

    function initializeBasketEdit() {
        // Ü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('editBasketForm')?.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ı">
                <select class="form-select form-select-sm mt-1"
                        name="basket_data[items][${itemCount}][type]">
                    <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">
            </td>
            <td>
                <input type="number" class="form-control form-control-sm"
                       name="basket_data[items][${itemCount}][price]"
                       value="0" min="0" step="0.01">
            </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">
            </td>
            <td>
                <select class="form-select form-select-sm"
                        name="basket_data[items][${itemCount}][period_type]">
                    <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
