@extends('layout')

@section('title', __('store.checkout_title'))

@section('content')
<div class="container py-4">
    <div class="row">
        <div class="col-lg-8">
            
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-shopping-cart me-2"></i>
                        {{ __('store.checkout_order_summary') }}
                    </h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>{{ __('store.checkout_item') }}</th>
                                    <th class="text-center">{{ __('store.checkout_period') }}</th>
                                    <th class="text-end">{{ __('store.checkout_price') }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($basketItems as $item)
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-start">
                                            <div class="flex-grow-1">
                                                <h6 class="mb-1">{{ $item['name'] }}</h6>
                                                @if($item['type'] === 'domain')
                                                    <small class="text-muted">
                                                        <i class="fas fa-globe me-1"></i>
                                                        {{ ucfirst($item['domain_action'] ?? 'register') }}: {{ $item['domain_name'] }}
                                                    </small>
                                                @endif
                                                @if(!empty($item['configurableOptions']))
                                                    <div class="mt-1">
                                                        @foreach($item['configurableOptions'] as $config)
                                                            <small class="text-muted d-block">
                                                                <i class="fas fa-cog me-1"></i>
                                                                {{ $config['name'] ?? $config['option_name'] ?? 'Option' }}
                                                                @if(isset($config['quantity']) && $config['quantity'] > 1)
                                                                    (x{{ $config['quantity'] }})
                                                                @endif
                                                            </small>
                                                        @endforeach
                                                    </div>
                                                @endif
                                            </div>
                                        </div>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge bg-secondary">
                                            {{ $item['period_text'] ?? ($item['period'] . ' ' . __('store.basket_period_' . ($item['period_type'] ?? 'month'))) }}
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        <strong>{{ $currency->symbol }}{{ number_format($item['price'], 2) }}</strong>
                                        @if(($item['quantity'] ?? 1) > 1)
                                            <br><small class="text-muted">({{ $item['quantity'] }}x)</small>
                                        @endif
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-user me-2"></i>
                        {{ __('store.checkout_customer_information') }}
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            @if($defaultBillingAddress)
                                <p class="mb-2"><strong>{{ __('store.checkout_name') }}:</strong> {{ $defaultBillingAddress->first_name }} {{ $defaultBillingAddress->last_name }}</p>
                                <p class="mb-2"><strong>{{ __('store.checkout_email') }}:</strong> {{ $defaultBillingAddress->email }}</p>
                                @if($defaultBillingAddress->company_name)
                                    <p class="mb-2"><strong>{{ __('store.checkout_company') }}:</strong> {{ $defaultBillingAddress->company_name }}</p>
                                @endif
                                @if($defaultBillingAddress->phone)
                                    <p class="mb-2"><strong>{{ __('store.checkout_phone') }}:</strong> {{ $defaultBillingAddress->phone }}</p>
                                @endif
                                @if($defaultBillingAddress->tax_id)
                                    <p class="mb-2"><strong>{{ __('store.checkout_tax_id') }}:</strong> {{ $defaultBillingAddress->tax_id }}</p>
                                @endif
                            @else
                                <p class="mb-2"><strong>{{ __('store.checkout_name') }}:</strong> {{ $client->first_name }} {{ $client->last_name }}</p>
                                <p class="mb-2"><strong>{{ __('store.checkout_email') }}:</strong> {{ $client->email }}</p>
                                @if($client->company_name)
                                    <p class="mb-2"><strong>{{ __('store.checkout_company') }}:</strong> {{ $client->company_name }}</p>
                                @endif
                                @if($client->phone)
                                    <p class="mb-2"><strong>{{ __('store.checkout_phone') }}:</strong> {{ $client->phone }}</p>
                                @endif
                            @endif
                        </div>
                        <div class="col-md-6">
                            @if($defaultBillingAddress)
                                <p class="mb-1"><strong>{{ __('store.checkout_billing_address') }}:</strong></p>
                                <address class="mb-0">
                                    @if($defaultBillingAddress->address1){{ $defaultBillingAddress->address1 }}<br>@endif
                                    @if($defaultBillingAddress->address2){{ $defaultBillingAddress->address2 }}<br>@endif
                                    @if($defaultBillingAddress->city){{ $defaultBillingAddress->city }}@endif
                                    @if($defaultBillingAddress->state), {{ $defaultBillingAddress->state }}@endif
                                    @if($defaultBillingAddress->postcode) {{ $defaultBillingAddress->postcode }}@endif
                                    @if($defaultBillingAddress->city || $defaultBillingAddress->state || $defaultBillingAddress->postcode)<br>@endif
                                    @if($defaultBillingAddress->country){{ $defaultBillingAddress->country->common_name }}@endif
                                </address>

                                
                                @if($orderCustomFields->isNotEmpty())
                                    @php $customFieldValues = $defaultBillingAddress->getOrderCustomFieldValues(); @endphp
                                    @foreach($customFieldValues as $fieldData)
                                        @if($fieldData['value'])
                                            <p class="mb-1">
                                                <strong>{{ $fieldData['field']->getTranslatedName() }}:</strong>
                                                {{ $fieldData['value'] }}
                                            </p>
                                        @endif
                                    @endforeach
                                @endif
                            @elseif($client->address1 || $client->city || $client->country)
                                <p class="mb-1"><strong>{{ __('store.checkout_billing_address') }}:</strong></p>
                                <address class="mb-0">
                                    @if($client->address1){{ $client->address1 }}<br>@endif
                                    @if($client->address2){{ $client->address2 }}<br>@endif
                                    @if($client->city){{ $client->city }}@endif
                                    @if($client->state), {{ $client->state }}@endif
                                    @if($client->postcode) {{ $client->postcode }}@endif
                                    @if($client->city || $client->state || $client->postcode)<br>@endif
                                    @if($client->country){{ $client->country->common_name }}@endif
                                </address>
                            @endif
                        </div>
                    </div>
                    <div class="text-end">
                        <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#editBillingModal">
                            <i class="fas fa-edit me-1"></i>
                            {{ __('store.checkout_edit_information') }}
                        </button>
                    </div>
                </div>
            </div>

            
            @if($allowNotesOnCheckout)
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-sticky-note me-2"></i>
                        {{ __('store.checkout_order_notes') }}
                        <small class="text-muted">({{ __('store.checkout_optional') }})</small>
                    </h5>
                </div>
                <div class="card-body">
                    <form method="POST" action="{{ route('store.checkout.process') }}" id="checkoutForm">
                        @csrf
                        <div class="mb-3">
                            <label for="notes" class="form-label">{{ __('store.checkout_special_instructions') }}</label>
                            <textarea class="form-control" id="notes" name="notes" rows="3"
                                      placeholder="{{ __('store.checkout_notes_placeholder') }}">{{ old('notes') }}</textarea>
                        </div>
                    </form>
                </div>
            </div>
            @endif

            
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-credit-card me-2"></i>
                        {{ __('store.checkout_payment_method') }}
                    </h5>
                </div>
                <div class="card-body">
                    @if(empty($paymentGateways))
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            {{ __('store.checkout_no_payment_methods') }}
                        </div>
                    @else
                        <div class="row">
                            @foreach($paymentGateways as $gateway)
                            <div class="col-md-6 mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="payment_gateway_id"
                                           id="gateway_{{ $gateway['name'] }}" value="{{ $gateway['name'] }}"
                                           {{ $loop->first ? 'checked' : '' }} required>
                                    <label class="form-check-label d-flex align-items-center" for="gateway_{{ $gateway['name'] }}">
                                        @if(!empty($gateway['logo']))
                                            <img src="{{ $gateway['logo'] }}" alt="{{ $gateway['display_name'] }}"
                                                 class="me-2" style="height: 24px;">
                                        @else
                                            <i class="fas fa-credit-card me-2"></i>
                                        @endif
                                        <div>
                                            <strong>{{ $gateway['display_name'] }}</strong>
                                            @if(!empty($gateway['description']))
                                                <br><small class="text-muted">{{ $gateway['description'] }}</small>
                                            @endif
                                        </div>
                                    </label>
                                </div>
                            </div>
                            @endforeach
                        </div>
                    @endif
                </div>
            </div>
        </div>

        
        <div class="col-lg-4">
            <div class="card sticky-top" style="top: 1rem;">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-calculator me-2"></i>
                        {{ __('store.checkout_order_total') }}
                    </h5>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between mb-2">
                        <span>{{ __('store.checkout_subtotal') }}:</span>
                        <span>{{ $currency->symbol }}{{ number_format($summary['subtotal'], 2) }}</span>
                    </div>
                    @if($summary['setup_fee'] > 0)
                    <div class="d-flex justify-content-between mb-2">
                        <span>{{ __('store.basket_setup_fee') }}:</span>
                        <span>{{ $currency->symbol }}{{ number_format($summary['setup_fee'], 2) }}</span>
                    </div>
                    @endif
                    @if($summary['tax_amount'] > 0)
                    <div class="d-flex justify-content-between mb-2">
                        <span>{{ __('store.checkout_tax') }}:</span>
                        <span>{{ $currency->symbol }}{{ number_format($summary['tax_amount'], 2) }}</span>
                    </div>
                    @endif
                    @if($summary['discount_amount'] > 0)
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-success">
                            <i class="fas fa-tag me-1"></i>
                            {{ $summary['discount']['discount_text'] ?? __('store.checkout_discount') }}:
                            @if(isset($summary['discount']['coupon_code']))
                                <small class="text-muted">({{ $summary['discount']['coupon_code'] }})</small>
                            @endif
                        </span>
                        <span class="text-success">-{{ $currency->symbol }}{{ number_format($summary['discount_amount'], 2) }}</span>
                    </div>
                    @endif
                    <hr>
                    <div class="d-flex justify-content-between mb-3">
                        <strong>{{ __('store.checkout_total') }}:</strong>
                        <strong class="text-primary fs-5">{{ $currency->symbol }}{{ number_format($summary['total'], 2) }}</strong>
                    </div>

                    
                    <div id="payment-method-fees" class="mb-3" style="display: none;">
                        <div class="d-flex justify-content-between mb-2 text-warning">
                            <span id="payment-fee-label">Ödeme Komisyonu:</span>
                            <span id="payment-fee-amount">{{ $currency->symbol }}0.00</span>
                        </div>
                        <div class="d-flex justify-content-between mb-3">
                            <strong>Toplam (Komisyon Dahil):</strong>
                            <strong class="text-success fs-5" id="total-with-fees">{{ $currency->symbol }}{{ number_format($summary['total'], 2) }}</strong>
                        </div>
                    </div>

                    @if($enableTosAcceptance)
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="final_terms_acceptance"
                                   name="terms_accepted" required form="checkoutForm">
                            <label class="form-check-label small" for="final_terms_acceptance">
                                {{ __('store.checkout_terms_agreement_start') }}
                                @if($tosUrl)
                                    <a href="{{ $tosUrl }}" target="_blank" class="text-decoration-none">
                                        {{ __('store.checkout_terms_of_service') }}
                                    </a>
                                @else
                                    {{ __('store.checkout_terms_of_service') }}
                                @endif
                                {{ __('store.checkout_terms_agreement_end') }}
                            </label>
                        </div>
                    </div>
                    @endif

                    <div class="d-grid">
                        <button type="submit" class="btn btn-success btn-lg" form="checkoutForm"
                                {{ empty($paymentGateways) ? 'disabled' : '' }}>
                            <i class="fas fa-lock me-2"></i>
                            {{ __('store.checkout_complete_order') }}
                        </button>
                    </div>

                    <div class="mt-3 text-center">
                        <small class="text-muted">
                            <i class="fas fa-shield-alt me-1"></i>
                            {{ __('store.checkout_secure_checkout') }}
                        </small>
                    </div>
                </div>
            </div>

            
            <div class="mt-3 text-center">
                <a href="{{ route('store.basket.index') }}" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-1"></i>
                    {{ __('store.checkout_back_to_basket') }}
                </a>
            </div>
        </div>
    </div>
</div>

@if(!$allowNotesOnCheckout)

<form method="POST" action="{{ route('store.checkout.process') }}" id="checkoutForm" style="display: none;">
    @csrf
    <input type="hidden" name="notes" value="">
</form>
@endif


<div class="modal fade" id="editBillingModal" tabindex="-1" aria-labelledby="editBillingModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editBillingModalLabel">
                    <i class="fas fa-address-book me-2"></i>
                    {{ __('store.checkout_manage_billing_info') }}
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="billingModalBody">
                <div class="row">
                    
                    <div class="col-md-5">
                        <h6 class="mb-3">{{ __('store.checkout_saved_addresses') }}</h6>

                        @if($billingAddresses->isEmpty())
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i>
                                {{ __('store.checkout_no_saved_addresses') }}
                            </div>
                        @else
                            @foreach($billingAddresses as $address)
                            <div class="card mb-2 billing-address-card {{ $address->is_default ? 'border-primary' : '' }}"
                                 data-address-id="{{ $address->id }}">
                                <div class="card-body p-3">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="flex-grow-1">
                                            <h6 class="mb-1">
                                                {{ $address->title }}
                                                @if($address->is_default)
                                                    <span class="badge bg-primary ms-2">{{ __('store.checkout_default') }}</span>
                                                @endif
                                            </h6>
                                            <small class="text-muted d-block">
                                                {{ $address->first_name }} {{ $address->last_name }}
                                                @if($address->company_name)
                                                    <br>{{ $address->company_name }}
                                                @endif
                                                <br>{{ $address->address1 }}
                                                @if($address->address2), {{ $address->address2 }}@endif
                                                <br>{{ $address->city }}, {{ $address->country->common_name }}
                                            </small>
                                        </div>
                                        <div class="text-end">
                                            <button type="button" class="btn btn-sm btn-outline-primary select-address-btn"
                                                    data-address-id="{{ $address->id }}">
                                                <i class="fas fa-check me-1"></i>
                                                {{ __('store.checkout_select') }}
                                            </button>
                                            <br>
                                            <button type="button" class="btn btn-sm btn-outline-secondary mt-1 edit-address-btn"
                                                    data-address-id="{{ $address->id }}">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            @endforeach
                        @endif

                        <button type="button" class="btn btn-outline-primary btn-sm w-100" id="addNewAddressBtn">
                            <i class="fas fa-plus me-1"></i>
                            {{ __('store.checkout_add_new_address') }}
                        </button>
                    </div>

                    
                    <div class="col-md-7">
                        <h6 class="mb-3" id="addressFormTitle">{{ __('store.checkout_address_details') }}</h6>

                        <form id="billingAddressForm">
                            @csrf
                            <input type="hidden" id="address_id" name="address_id" value="">
                            <input type="hidden" id="form_mode" name="form_mode" value="select">

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="address_title" class="form-label">{{ __('store.checkout_address_title') }} <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="address_title" name="title" required>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <div class="form-check mt-4">
                                            <input class="form-check-input" type="checkbox" id="is_default" name="is_default" value="1">
                                            <label class="form-check-label" for="is_default">
                                                {{ __('store.checkout_set_as_default') }}
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="address_first_name" class="form-label">{{ __('store.checkout_first_name') }} <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="address_first_name" name="first_name" required>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="address_last_name" class="form-label">{{ __('store.checkout_last_name') }} <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="address_last_name" name="last_name" required>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="address_company_name" class="form-label">{{ __('store.checkout_company_name') }}</label>
                                        <input type="text" class="form-control" id="address_company_name" name="company_name">
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="address_tax_id" class="form-label">{{ __('store.checkout_tax_id') }}</label>
                                        <input type="text" class="form-control" id="address_tax_id" name="tax_id">
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="address_email" class="form-label">{{ __('store.checkout_email') }} <span class="text-danger">*</span></label>
                                        <input type="email" class="form-control" id="address_email" name="email" required>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="address_phone" class="form-label">{{ __('store.checkout_phone') }} <span class="text-danger">*</span></label>
                                        <input type="tel" class="form-control" id="address_phone" name="phone" required>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="address_country_id" class="form-label">{{ __('store.checkout_country') }} <span class="text-danger">*</span></label>
                                        <select class="form-select" id="address_country_id" name="country_id" required>
                                            <option value="">{{ __('store.checkout_select_country') }}</option>
                                        </select>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="address_city" class="form-label">{{ __('store.checkout_city') }} <span class="text-danger">*</span></label>
                                        <select class="form-select d-none" id="address_city_select" name="" disabled>
                                            <option value="">{{ __('store.auth_select_city') }}</option>
                                        </select>
                                        <input type="text" class="form-control" id="address_city" name="city" required>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="address_address1" class="form-label">{{ __('store.checkout_address1') }} <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="address_address1" name="address1" required>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="address_address2" class="form-label">{{ __('store.checkout_address2') }}</label>
                                        <input type="text" class="form-control" id="address_address2" name="address2">
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="address_state" class="form-label">{{ __('store.checkout_state') }}</label>
                                        <input type="text" class="form-control" id="address_state" name="state">
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="address_postcode" class="form-label">{{ __('store.checkout_postcode') }} <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="address_postcode" name="postcode" required>
                                        <div class="invalid-feedback"></div>
                                    </div>
                                </div>
                            </div>

                            
                            @if($orderCustomFields->isNotEmpty())
                                <h6 class="mb-3 mt-4">{{ __('store.checkout_additional_information') }}</h6>
                                @foreach($orderCustomFields as $field)
                                    <div class="mb-3">
                                        <label for="custom_field_{{ $field->id }}" class="form-label">
                                            {{ $field->getTranslatedName() }}
                                            @if($field->is_required)<span class="text-danger">*</span>@endif
                                        </label>

                                        @switch($field->type)
                                            @case('text')
                                            @case('input')
                                                <input type="text" class="form-control" id="custom_field_{{ $field->id }}"
                                                       name="custom_field_{{ $field->id }}" {{ $field->is_required ? 'required' : '' }}>
                                                @break

                                            @case('textarea')
                                            @case('textbox')
                                                <textarea class="form-control" id="custom_field_{{ $field->id }}"
                                                          name="custom_field_{{ $field->id }}" rows="3" {{ $field->is_required ? 'required' : '' }}></textarea>
                                                @break

                                            @case('select')
                                            @case('options')
                                                <select class="form-select" id="custom_field_{{ $field->id }}"
                                                        name="custom_field_{{ $field->id }}" {{ $field->is_required ? 'required' : '' }}>
                                                    <option value="">{{ __('store.auth_select_option') }}</option>
                                                    @if($field->values && is_array($field->values))
                                                        @foreach($field->getTranslatedValues() as $key => $value)
                                                            <option value="{{ $key }}">{{ $value }}</option>
                                                        @endforeach
                                                    @endif
                                                </select>
                                                @break

                                            @case('checkbox')
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="custom_field_{{ $field->id }}"
                                                           name="custom_field_{{ $field->id }}" value="1">
                                                    <label class="form-check-label" for="custom_field_{{ $field->id }}">
                                                        {{ $field->getTranslatedDescription() }}
                                                    </label>
                                                </div>
                                                @break
                                        @endswitch

                                        @if($field->getTranslatedDescription() && !in_array($field->type, ['checkbox']))
                                            <small class="form-text text-muted">{{ $field->getTranslatedDescription() }}</small>
                                        @endif
                                        <div class="invalid-feedback"></div>
                                    </div>
                                @endforeach
                            @endif
                        </form>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    {{ __('store.buttons_cancel') }}
                </button>
                <button type="button" class="btn btn-danger d-none" id="deleteAddressBtn">
                    <i class="fas fa-trash me-1"></i>
                    {{ __('store.checkout_delete_address') }}
                </button>
                <button type="submit" class="btn btn-primary" id="saveAddressBtn" form="billingAddressForm">
                    <i class="fas fa-save me-1"></i>
                    {{ __('store.checkout_save_address') }}
                </button>
            </div>
        </div>
    </div>
</div>


<form id="billingEditForm" style="display: none;">
    @csrf
    <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_first_name" class="form-label">{{ __('store.checkout_first_name') }} <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_first_name" name="first_name"
                                       value="{{ $client->first_name }}" required>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_last_name" class="form-label">{{ __('store.checkout_last_name') }} <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_last_name" name="last_name"
                                       value="{{ $client->last_name }}" required>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_company_name" class="form-label">{{ __('store.checkout_company_name') }}</label>
                                <input type="text" class="form-control" id="edit_company_name" name="company_name"
                                       value="{{ $client->company_name }}">
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_tax_id" class="form-label">{{ __('store.checkout_tax_id') }}</label>
                                <input type="text" class="form-control" id="edit_tax_id" name="tax_id"
                                       value="{{ $client->tax_id }}">
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_email" class="form-label">{{ __('store.checkout_email') }} <span class="text-danger">*</span></label>
                                <input type="email" class="form-control" id="edit_email" name="email"
                                       value="{{ $client->email }}" required>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_phone" class="form-label">{{ __('store.checkout_phone') }} <span class="text-danger">*</span></label>
                                <input type="tel" class="form-control" id="edit_phone" name="phone"
                                       value="{{ $client->phone }}" required>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_country_id" class="form-label">{{ __('store.checkout_country') }} <span class="text-danger">*</span></label>
                                <select class="form-select" id="edit_country_id" name="country_id" required>
                                    <option value="">{{ __('store.checkout_select_country') }}</option>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_city" class="form-label">{{ __('store.checkout_city') }} <span class="text-danger">*</span></label>
                                <!-- City Select Dropdown (shown when cities are available) -->
                                <select class="form-select d-none" id="edit_city_select" name="" disabled>
                                    <option value="">{{ __('store.auth_select_city') }}</option>
                                </select>
                                <!-- City Text Input (shown when no cities or fallback) -->
                                <input type="text" class="form-control" id="edit_city" name="city"
                                       value="{{ $client->city }}" required>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_address1" class="form-label">{{ __('store.checkout_address1') }} <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_address1" name="address1"
                                       value="{{ $client->address1 }}" required>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_address2" class="form-label">{{ __('store.checkout_address2') }}</label>
                                <input type="text" class="form-control" id="edit_address2" name="address2"
                                       value="{{ $client->address2 }}">
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_state" class="form-label">{{ __('store.checkout_state') }}</label>
                                <input type="text" class="form-control" id="edit_state" name="state"
                                       value="{{ $client->state }}">
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_postcode" class="form-label">{{ __('store.checkout_postcode') }} <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_postcode" name="postcode"
                                       value="{{ $client->postcode }}" required>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        {{ __('store.buttons_cancel') }}
                    </button>
                    <button type="submit" class="btn btn-primary" id="updateBillingBtn">
                        <i class="fas fa-save me-1"></i>
                        {{ __('store.checkout_update_billing') }}
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Form submission handling
    const checkoutForm = document.getElementById('checkoutForm');

    if (checkoutForm) {
        checkoutForm.addEventListener('submit', function(e) {
            const submitBtn = checkoutForm.querySelector('button[type="submit"]');

            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>{{ __('store.checkout_processing') }}...';
            }
        });
    }

    // Payment method change handling
    const paymentRadios = document.querySelectorAll('input[name="payment_gateway_id"]');
    const paymentFeesDiv = document.getElementById('payment-method-fees');
    const paymentFeeAmount = document.getElementById('payment-fee-amount');
    const totalWithFees = document.getElementById('total-with-fees');
    const originalTotal = {{ $summary['total'] }};

    // Payment gateway fee data
    const paymentGateways = {
        @foreach($paymentGateways as $gateway)
        '{{ $gateway['name'] }}': {
            name: '{{ $gateway['display_name'] }}',
            feePercentage: {{ $gateway['fee_percentage'] }},
            feeFixed: {{ $gateway['fee_fixed'] }}
        },
        @endforeach
    };

    paymentRadios.forEach(radio => {
        radio.addEventListener('change', function() {
            calculatePaymentFees(this.value);
        });
    });

    function calculatePaymentFees(gatewayId) {
        const gateway = paymentGateways[gatewayId];

        if (!gateway) {
            hidePaymentFees();
            return;
        }

        const percentageFee = originalTotal * (gateway.feePercentage / 100);
        const totalFees = percentageFee + gateway.feeFixed;
        const newTotal = originalTotal + totalFees;

        if (totalFees > 0) {
            showPaymentFees(gateway.name, totalFees, newTotal);
        } else {
            hidePaymentFees();
        }
    }

    function showPaymentFees(gatewayName, fees, newTotal) {
        if (paymentFeeAmount && totalWithFees && paymentFeesDiv) {
            paymentFeeAmount.textContent = '{{ $currency->symbol }}' + fees.toFixed(2);
            totalWithFees.textContent = '{{ $currency->symbol }}' + newTotal.toFixed(2);
            paymentFeesDiv.style.display = 'block';
        }
    }

    function hidePaymentFees() {
        if (paymentFeesDiv) {
            paymentFeesDiv.style.display = 'none';
        }
    }

    // Initialize with first payment method if any
    const checkedRadio = document.querySelector('input[name="payment_gateway_id"]:checked');
    if (checkedRadio) {
        calculatePaymentFees(checkedRadio.value);
    }

    // Billing edit modal functionality
    const billingModal = document.getElementById('editBillingModal');
    const billingForm = document.getElementById('billingEditForm');
    const countrySelect = document.getElementById('edit_country_id');
    const cityInput = document.getElementById('edit_city');
    const citySelect = document.getElementById('edit_city_select');

    // Load countries when modal is shown
    billingModal.addEventListener('show.bs.modal', function() {
        loadCountries();
    });

    // Handle country change
    countrySelect.addEventListener('change', function() {
        handleCountryChange(this.value);
    });

    // Load countries function
    async function loadCountries() {
        try {
            const response = await fetch('/storeapi/store/countries');
            const data = await response.json();

            if (data.success) {
                countrySelect.innerHTML = '<option value="">{{ __('store.checkout_select_country') }}</option>';

                data.countries.forEach(country => {
                    const option = document.createElement('option');
                    option.value = country.id;
                    option.textContent = country.name;

                    // Select current country
                    @if($client->country_id)
                        if (country.id == {{ $client->country_id }}) {
                            option.selected = true;
                        }
                    @endif

                    countrySelect.appendChild(option);
                });

                // If country is already selected, load cities
                @if($client->country_id)
                    handleCountryChange({{ $client->country_id }});
                @endif
            }
        } catch (error) {
            console.error('Error loading countries:', error);
        }
    }

    // Handle country change and load cities
    async function handleCountryChange(countryId) {
        if (!countryId) {
            resetCityField();
            return;
        }

        try {
            // Show loading state
            showCityLoading();

            // Fetch cities for the selected country
            const response = await fetch(`/storeapi/store/cities/${countryId}`);
            const data = await response.json();

            if (data.success && data.cities && data.cities.length > 0) {
                showCitySelect(data.cities);
            } else {
                showCityInput();
            }

        } catch (error) {
            console.error('Error fetching cities:', error);
            showCityInput();
        }
    }

    // Show loading state for city field
    function showCityLoading() {
        if (cityInput) {
            cityInput.placeholder = '{{ __('store.auth_cities_loading') }}';
            cityInput.disabled = true;
        }
    }

    // Show city select dropdown with cities
    function showCitySelect(cities) {
        // Hide text input
        if (cityInput) {
            cityInput.classList.add('d-none');
            cityInput.disabled = true;
            cityInput.name = '';
        }

        // Show and populate select
        if (citySelect) {
            citySelect.classList.remove('d-none');
            citySelect.disabled = false;
            citySelect.name = 'city';

            // Clear existing options
            citySelect.innerHTML = `<option value="">{{ __('store.auth_select_city') }}</option>`;

            // Add new options
            cities.forEach(city => {
                const option = document.createElement('option');
                option.value = city.name;
                option.textContent = city.name;

                // Select current city if it matches
                @if($client->city)
                    if (city.name === '{{ $client->city }}') {
                        option.selected = true;
                    }
                @endif

                citySelect.appendChild(option);
            });
        }
    }

    // Show city text input
    function showCityInput() {
        // Show text input
        if (cityInput) {
            cityInput.classList.remove('d-none');
            cityInput.disabled = false;
            cityInput.name = 'city';
            cityInput.placeholder = '';
        }

        // Hide select
        if (citySelect) {
            citySelect.classList.add('d-none');
            citySelect.disabled = true;
            citySelect.name = '';
        }
    }

    // Reset city field to input mode
    function resetCityField() {
        showCityInput();
        if (cityInput) {
            cityInput.value = '';
        }
    }

    // Billing form submission
    billingForm.addEventListener('submit', async function(e) {
        e.preventDefault();

        const submitBtn = document.getElementById('updateBillingBtn');
        const originalText = submitBtn.innerHTML;

        // Clear previous errors
        clearFormErrors();

        // Disable button and show loading
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>{{ __('store.checkout_updating') }}';

        try {
            const formData = new FormData(billingForm);

            const response = await fetch('{{ route('store.checkout.update-billing') }}', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                }
            });

            const data = await response.json();

            if (data.success) {
                // Update the display on the page
                updateBillingDisplay(data.data);

                // Close modal
                const modalInstance = bootstrap.Modal.getInstance(billingModal);
                modalInstance.hide();

                // Show success message
                showAlert('success', data.message);

            } else {
                // Show validation errors
                if (data.errors) {
                    showFormErrors(data.errors);
                } else {
                    showAlert('error', data.message);
                }
            }
        } catch (error) {
            console.error('Error updating billing info:', error);
            showAlert('error', '{{ __('store.messages_error_occurred') }}');
        } finally {
            // Re-enable button
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    });

    // Clear form errors
    function clearFormErrors() {
        const errorElements = billingForm.querySelectorAll('.is-invalid');
        errorElements.forEach(el => el.classList.remove('is-invalid'));

        const feedbackElements = billingForm.querySelectorAll('.invalid-feedback');
        feedbackElements.forEach(el => el.textContent = '');
    }

    // Show form errors
    function showFormErrors(errors) {
        Object.keys(errors).forEach(field => {
            const input = billingForm.querySelector(`[name="${field}"]`);
            const feedback = input?.parentElement.querySelector('.invalid-feedback');

            if (input && feedback) {
                input.classList.add('is-invalid');
                feedback.textContent = errors[field][0];
            }
        });
    }

    // Update billing display on the page
    function updateBillingDisplay(data) {
        // This would update the billing information display in the checkout page
        // For now, we'll just reload the page to show updated data
        location.reload();
    }

    // Show alert function
    function showAlert(type, message) {
        // Simple alert for now - could be replaced with a toast notification
        if (type === 'success') {
            alert(message);
        } else {
            alert('{{ __('store.messages_error_occurred') }}: ' + message);
        }
    }
});
</script>
@endpush
@endsection
