@extends('admin.layouts.app')

@section('title', __('admin/quotes.edit_title') . ' - ' . $quote->quote_number)

@section('content')
<div class="container-fluid px-4">
    <!-- Page Header -->
    <x-admin.page-header
        :title="__('admin/quotes.edit_title') . ' - ' . $quote->quote_number"
        icon="fas fa-file-invoice"
    >
        <span class="badge bg-{{ match($quote->status) {
            'draft' => 'secondary',
            'sent' => 'info',
            'accepted' => 'success',
            'rejected' => 'danger',
            'expired' => 'warning',
            'converted' => 'primary',
            default => 'secondary'
        } }} mt-1 me-2">{{ __('admin/quotes.status_' . $quote->status) }}</span>

        <!-- Action Buttons -->
        @if($quote->canBeSent())
            <form method="POST" action="{{ route('admin.quotes.send', $quote->id) }}" class="d-inline" id="sendForm">
                @csrf
                <button type="button" class="btn btn-outline-success btn-sm" id="sendQuoteBtn">
                    <i class="fas fa-paper-plane me-1"></i>{{ __('admin/quotes.btn_send') }}
                </button>
            </form>
        @endif

        @if($quote->canBeAccepted())
            <form method="POST" action="{{ route('admin.quotes.accept', $quote->id) }}" class="d-inline" id="acceptForm">
                @csrf
                <button type="button" class="btn btn-outline-primary btn-sm" id="acceptQuoteBtn">
                    <i class="fas fa-check-circle me-1"></i>{{ __('admin/quotes.btn_accept') }}
                </button>
            </form>
        @endif

        <form method="POST" action="{{ route('admin.quotes.duplicate', $quote->id) }}" class="d-inline" id="duplicateForm">
            @csrf
            <button type="button" class="btn btn-outline-info btn-sm" id="duplicateQuoteBtn">
                <i class="fas fa-copy me-1"></i>{{ __('admin/quotes.btn_duplicate') }}
            </button>
        </form>

        <a href="{{ route('admin.quotes.download-pdf', $quote->id) }}" class="btn btn-outline-secondary btn-sm" target="_blank">
            <i class="fas fa-file-pdf me-1"></i>{{ __('admin/quotes.btn_download_pdf') }}
        </a>

        @if($quote->canBeDeleted())
            <button type="button" class="btn btn-outline-danger btn-sm" id="deleteQuoteBtn">
                <i class="fas fa-trash me-1"></i>{{ __('admin/quotes.btn_delete') }}
            </button>
        @endif

        <a href="{{ route('admin.quotes.index') }}" class="btn btn-outline-secondary btn-sm">
            <i class="fas fa-arrow-left me-1"></i>{{ __('admin/quotes.btn_back_to_list') }}
        </a>
    </x-admin.page-header>

    @if($quote->canBeEdited())
    {{-- Editable Form --}}
    <form method="POST" action="{{ route('admin.quotes.update', $quote->id) }}" id="quoteForm">
        @csrf
        @method('PUT')

        <!-- Quote Details Card -->
        <x-admin.card :title="__('admin/quotes.edit_title')" class="mb-3">
            <div class="row g-3">
                <!-- Client (read-only in edit) -->
                <div class="col-md-6">
                    <label class="form-label">{{ __('admin/quotes.form_client') }}</label>
                    <input type="text"
                           class="form-control"
                           value="{{ $quote->client->first_name }} {{ $quote->client->last_name }} ({{ $quote->client->email }})"
                           disabled>
                </div>

                <!-- Subject -->
                <div class="col-md-6">
                    <label for="subject" class="form-label">{{ __('admin/quotes.form_subject') }} <span class="text-danger">*</span></label>
                    <input type="text"
                           class="form-control @error('subject') is-invalid @enderror"
                           name="subject"
                           id="subject"
                           value="{{ old('subject', $quote->subject) }}"
                           required>
                    @error('subject')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <!-- Valid Until -->
                <div class="col-md-4">
                    <label for="valid_until" class="form-label">{{ __('admin/quotes.form_valid_until') }} <span class="text-danger">*</span></label>
                    <input type="date"
                           class="form-control @error('valid_until') is-invalid @enderror"
                           name="valid_until"
                           id="valid_until"
                           value="{{ old('valid_until', $quote->valid_until->format('Y-m-d')) }}"
                           required>
                    @error('valid_until')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <!-- Currency (teklifin para birimi, sabit) -->
                <div class="col-md-4">
                    <label class="form-label">{{ __('admin/quotes.form_currency') }}</label>
                    <input type="hidden" name="currency_id" id="currency_id" value="{{ old('currency_id', $quote->currency_id) }}">
                    <p class="form-control-plaintext fw-bold mb-0" id="currencyDisplay">{{ $quote->currency->code ?? '' }}{{ $quote->currency && $quote->currency->symbol ? ' ('.$quote->currency->symbol.')' : '' }}</p>
                    @error('currency_id')
                        <div class="text-danger small">{{ $message }}</div>
                    @enderror
                </div>

                <div class="col-md-4"></div>

                <!-- Proposal -->
                <div class="col-12">
                    <label for="proposal" class="form-label">{{ __('admin/quotes.form_proposal') }}</label>
                    <textarea class="form-control @error('proposal') is-invalid @enderror"
                              name="proposal"
                              id="proposal"
                              rows="3">{{ old('proposal', $quote->proposal) }}</textarea>
                    @error('proposal')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <!-- Admin Notes -->
                <div class="col-md-6">
                    <label for="admin_notes" class="form-label">{{ __('admin/quotes.form_admin_notes') }}</label>
                    <textarea class="form-control @error('admin_notes') is-invalid @enderror"
                              name="admin_notes"
                              id="admin_notes"
                              rows="3">{{ old('admin_notes', $quote->admin_notes) }}</textarea>
                    @error('admin_notes')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <!-- Client Notes -->
                <div class="col-md-6">
                    <label for="client_notes" class="form-label">{{ __('admin/quotes.form_client_notes') }}</label>
                    <textarea class="form-control @error('client_notes') is-invalid @enderror"
                              name="client_notes"
                              id="client_notes"
                              rows="3">{{ old('client_notes', $quote->client_notes) }}</textarea>
                    @error('client_notes')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
        </x-admin.card>

        <!-- Items Section -->
        <x-admin.card class="mb-3">
            <x-slot:header>
                <div class="d-flex justify-content-between align-items-center w-100">
                    <h6 class="mb-0">{{ __('admin/quotes.form_items') }}</h6>
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-sm btn-outline-primary" id="addProductBtn">
                            <i class="fas fa-box me-1"></i>{{ __('admin/quotes.btn_add_product') }}
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-info" id="addDomainBtn">
                            <i class="fas fa-globe me-1"></i>{{ __('admin/quotes.btn_add_domain') }}
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-secondary" id="addCustomItemBtn">
                            <i class="fas fa-plus me-1"></i>{{ __('admin/quotes.btn_add_custom_item') }}
                        </button>
                    </div>
                </div>
            </x-slot:header>

            <div class="table-responsive">
                <table class="table table-bordered align-middle" id="itemsTable">
                    <thead>
                        <tr>
                            <th style="min-width: 250px;">{{ __('admin/quotes.form_item_description') }}</th>
                            <th style="width: 80px;">{{ __('admin/quotes.form_item_quantity') }}</th>
                            <th style="width: 130px;">{{ __('admin/quotes.form_item_unit_price') }}</th>
                            <th style="width: 100px;">{{ __('admin/quotes.form_item_discount') }}</th>
                            <th style="width: 80px;">{{ __('admin/quotes.form_item_taxable') }}</th>
                            <th style="width: 100px;">{{ __('admin/quotes.form_item_tax') }}</th>
                            <th style="width: 130px;">{{ __('admin/quotes.form_item_total') }}</th>
                            <th style="width: 60px;"></th>
                        </tr>
                    </thead>
                    <tbody id="itemsBody">
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="6" class="text-end fw-bold">{{ __('admin/quotes.subtotal') }}:</td>
                            <td id="subtotalDisplay" class="fw-bold">0.00</td>
                            <td></td>
                        </tr>
                        <tr>
                            <td colspan="6" class="text-end fw-bold">{{ __('admin/quotes.tax_total') }}:</td>
                            <td id="taxDisplay" class="fw-bold">0.00</td>
                            <td></td>
                        </tr>
                        <tr>
                            <td colspan="6" class="text-end fw-bold">{{ __('admin/quotes.grand_total') }}:</td>
                            <td id="grandTotalDisplay" class="fw-bold text-primary">0.00</td>
                            <td></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <p class="text-muted small mt-2 mb-0" id="noItemsMsg">{{ __('admin/quotes.form_no_items') }}</p>
        </x-admin.card>

        <input type="hidden" name="items" id="itemsJson" value="[]">

        <!-- Submit -->
        <div class="d-flex justify-content-end gap-2">
            <a href="{{ route('admin.quotes.index') }}" class="btn btn-outline-secondary">
                {{ __('admin/common.cancel') }}
            </a>
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-save me-1"></i>{{ __('admin/quotes.btn_save') }}
            </button>
        </div>
    </form>

    <!-- Product Select Modal -->
    <x-admin.modal id="productModal" :title="__('admin/quotes.product_modal_title')">
        <div class="mb-3">
            <label class="form-label">{{ __('admin/quotes.product_modal_select') }}</label>
            <select class="form-select" id="productSelect">
                <option value="">{{ __('admin/quotes.product_modal_search') }}</option>
            </select>
        </div>
        <div class="mb-3 d-none" id="billingCycleGroup">
            <label class="form-label">{{ __('admin/quotes.product_modal_billing_cycle') }}</label>
            <select class="form-select" id="billingCycleSelect"></select>
        </div>
        <div class="mb-3 d-none" id="productPriceDisplay">
            <label class="form-label">{{ __('admin/quotes.product_modal_price') }}</label>
            <p class="form-control-plaintext fw-bold" id="productPriceText"></p>
        </div>
        <div class="mb-3 d-none" id="productConfigOptions">
            <hr>
            <label class="form-label fw-bold">{{ __('admin/quotes.config_options_title') }}</label>
            <div id="productConfigOptionsBody"></div>
        </div>

        <x-slot:footer>
            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">{{ __('admin/common.cancel') }}</button>
            <button type="button" class="btn btn-primary" id="addProductToQuoteBtn" disabled>
                {{ __('admin/quotes.product_modal_add') }}
            </button>
        </x-slot:footer>
    </x-admin.modal>

    <!-- Domain Select Modal -->
    <x-admin.modal id="domainModal" :title="__('admin/quotes.domain_modal_title')">
        <div class="mb-3">
            <label for="domainNameInput" class="form-label">{{ __('admin/quotes.domain_modal_full_name') }}</label>
            <input type="text"
                   class="form-control"
                   id="domainNameInput"
                   placeholder="{{ __('admin/quotes.domain_modal_full_name_placeholder') }}">
        </div>
        <div class="mb-3 d-none" id="domainResolvedTldGroup">
            <label class="form-label">{{ __('admin/quotes.domain_modal_resolved_tld') }}</label>
            <p class="form-control-plaintext fw-bold mb-0" id="domainResolvedTld"></p>
        </div>
        <div class="mb-3">
            <label for="domainActionSelect" class="form-label">{{ __('admin/quotes.domain_modal_action') }}</label>
            <select class="form-select" id="domainActionSelect">
                <option value="register">{{ __('admin/quotes.domain_modal_action_register') }}</option>
                <option value="transfer">{{ __('admin/quotes.domain_modal_action_transfer') }}</option>
                <option value="renew">{{ __('admin/quotes.domain_modal_action_renew') }}</option>
            </select>
        </div>
        <div class="mb-3 d-none" id="domainPeriodGroup">
            <label for="domainPeriodSelect" class="form-label">{{ __('admin/quotes.domain_modal_period') }}</label>
            <select class="form-select" id="domainPeriodSelect"></select>
        </div>
        <div class="mb-3 d-none" id="domainPriceDisplay">
            <label class="form-label">{{ __('admin/quotes.domain_modal_price') }}</label>
            <p class="form-control-plaintext fw-bold" id="domainPriceText"></p>
        </div>
        <div class="d-none" id="domainNoPricing">
            <p class="text-danger small mb-0">{{ __('admin/quotes.domain_modal_no_pricing_for_tld') }}</p>
        </div>

        <x-slot:footer>
            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">{{ __('admin/common.cancel') }}</button>
            <button type="button" class="btn btn-primary" id="addDomainToQuoteBtn" disabled>
                {{ __('admin/quotes.domain_modal_add') }}
            </button>
        </x-slot:footer>
    </x-admin.modal>

    @else
    {{-- Read-only view for non-editable statuses --}}
    <x-admin.card :title="__('admin/quotes.view_title')" class="mb-3">
        <div class="row g-3">
            <div class="col-md-4">
                <label class="form-label fw-bold">{{ __('admin/quotes.form_client') }}</label>
                <p class="mb-0">{{ $quote->client->first_name }} {{ $quote->client->last_name }} ({{ $quote->client->email }})</p>
            </div>
            <div class="col-md-4">
                <label class="form-label fw-bold">{{ __('admin/quotes.form_subject') }}</label>
                <p class="mb-0">{{ $quote->subject }}</p>
            </div>
            <div class="col-md-4">
                <label class="form-label fw-bold">{{ __('admin/quotes.form_valid_until') }}</label>
                <p class="mb-0">{{ $quote->valid_until->format($dateFormat) }}</p>
            </div>
            <div class="col-md-4">
                <label class="form-label fw-bold">{{ __('admin/quotes.form_currency') }}</label>
                <p class="mb-0">{{ $quote->currency->code ?? '-' }}</p>
            </div>
            <div class="col-md-4">
                <label class="form-label fw-bold">{{ __('admin/quotes.table_admin') }}</label>
                <p class="mb-0">{{ $quote->admin?->name ?? '-' }}</p>
            </div>
            <div class="col-md-4"></div>
            @if($quote->proposal)
            <div class="col-12">
                <label class="form-label fw-bold">{{ __('admin/quotes.form_proposal') }}</label>
                <p class="mb-0">{!! nl2br(e($quote->proposal)) !!}</p>
            </div>
            @endif
            @if($quote->admin_notes)
            <div class="col-md-6">
                <label class="form-label fw-bold">{{ __('admin/quotes.form_admin_notes') }}</label>
                <p class="mb-0">{!! nl2br(e($quote->admin_notes)) !!}</p>
            </div>
            @endif
            @if($quote->client_notes)
            <div class="col-md-6">
                <label class="form-label fw-bold">{{ __('admin/quotes.form_client_notes') }}</label>
                <p class="mb-0">{!! nl2br(e($quote->client_notes)) !!}</p>
            </div>
            @endif
        </div>
    </x-admin.card>

    <!-- Read-only Items -->
    <x-admin.card :title="__('admin/quotes.form_items')" class="mb-3">
        <div class="table-responsive">
            <table class="table table-bordered align-middle">
                <thead>
                    <tr>
                        <th>{{ __('admin/quotes.form_item_description') }}</th>
                        <th>{{ __('admin/quotes.form_item_quantity') }}</th>
                        <th>{{ __('admin/quotes.form_item_unit_price') }}</th>
                        <th>{{ __('admin/quotes.form_item_discount') }}</th>
                        <th>{{ __('admin/quotes.form_item_taxable') }}</th>
                        <th>{{ __('admin/quotes.form_item_tax') }}</th>
                        <th>{{ __('admin/quotes.form_item_total') }}</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($quote->items as $item)
                    <tr>
                        <td>{{ $item->description }}</td>
                        <td>{{ $item->quantity }}</td>
                        <td>{{ number_format($item->unit_price, 2) }}</td>
                        <td>{{ number_format($item->discount, 2) }}%</td>
                        <td>
                            @if($item->taxable)
                                <i class="fas fa-check text-success"></i>
                            @else
                                <i class="fas fa-times text-muted"></i>
                            @endif
                        </td>
                        <td>{{ number_format($item->tax_amount, 2) }}</td>
                        <td>{{ number_format($item->total, 2) }}</td>
                    </tr>
                    @endforeach
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="6" class="text-end fw-bold">{{ __('admin/quotes.subtotal') }}:</td>
                        <td class="fw-bold">{{ number_format($quote->sub_total, 2) }}</td>
                    </tr>
                    <tr>
                        <td colspan="6" class="text-end fw-bold">{{ __('admin/quotes.tax_total') }}:</td>
                        <td class="fw-bold">{{ number_format($quote->tax_amount, 2) }}</td>
                    </tr>
                    <tr>
                        <td colspan="6" class="text-end fw-bold">{{ __('admin/quotes.grand_total') }}:</td>
                        <td class="fw-bold text-primary">{{ number_format($quote->total, 2) }} {{ $quote->currency->code ?? '' }}</td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </x-admin.card>
    @endif

    @if($quote->converted_invoice_id)
    <!-- Converted Invoice Info -->
    <x-admin.card class="mb-3">
        <div class="d-flex align-items-center">
            <i class="fas fa-file-invoice-dollar text-success me-2"></i>
            <span>{{ __('admin/quotes.status_converted') }}:</span>
            <a href="{{ route('admin.billing.edit', $quote->converted_invoice_id) }}" class="ms-2 fw-bold">
                #{{ $quote->converted_invoice_id }}
            </a>
        </div>
    </x-admin.card>
    @endif
</div>
@endsection

@push('scripts')
<script>
    window.quoteFormConfig = {
        routes: {
            update: '{{ route("admin.quotes.update", $quote->id) }}',
            productPricing: '{{ route("api.admin.quotes.product-pricing") }}',
            clientSearch: '{{ route("api.admin.clients.search") }}',
            productRecords: '{{ route("api.admin.products.records") }}',
            calculateTax: '{{ route("api.admin.quotes.calculate-tax") }}',
            tldSearch: '{{ route("api.admin.quotes.tld-search") }}',
            domainPricing: '{{ route("api.admin.quotes.domain-pricing") }}',
            productConfigOptions: '{{ route("api.admin.quotes.product-config-options") }}'
        },
        translations: {
            description: '{{ __("admin/quotes.form_item_description") }}',
            quantity: '{{ __("admin/quotes.form_item_quantity") }}',
            unit_price: '{{ __("admin/quotes.form_item_unit_price") }}',
            discount: '{{ __("admin/quotes.form_item_discount") }}',
            taxable: '{{ __("admin/quotes.form_item_taxable") }}',
            tax: '{{ __("admin/quotes.form_item_tax") }}',
            total: '{{ __("admin/quotes.form_item_total") }}',
            items_required: '{{ __("admin/quotes.messages_update_error") }}',
            no_items: '{{ __("admin/quotes.form_no_items") }}',
            billing_cycle: '{{ __("admin/quotes.form_item_billing_cycle") }}',
            product: '{{ __("admin/quotes.form_item_product") }}',
            config_option_required: '{{ __("admin/quotes.config_option_required") }}',
            config_option_select_placeholder: '{{ __("admin/quotes.config_option_select_placeholder") }}',
            domain_required_for_product: {!! json_encode(__('admin/quotes.domain_required_for_product')) !!},
            domain_no_pricing_tld: '{{ __("admin/quotes.domain_modal_no_pricing_for_tld") }}'
        },
        currencies: {!! json_encode($currencies->map(fn($c) => ['id' => $c->id, 'code' => $c->code, 'symbol' => $c->symbol])) !!},
        items: {!! json_encode($quote->items->map(fn($item) => [
            'type' => $item->type,
            'product_id' => $item->product_id,
            'billing_cycle' => $item->billing_cycle,
            'domain_name' => $item->domain_name,
            'tld_id' => $item->tld_id,
            'domain_action' => $item->domain_action,
            'registration_period' => $item->registration_period,
            'description' => $item->description,
            'quantity' => (int) $item->quantity,
            'unit_price' => (float) $item->unit_price,
            'discount' => (float) $item->discount,
            'taxable' => (bool) $item->taxable,
            'tax_rate' => (float) $item->tax_rate,
            'tax_amount' => (float) $item->tax_amount,
            'total' => (float) $item->total,
        ])) !!},
        quoteStatus: '{{ $quote->status }}',
        clientId: null,
        apiToken: window.getApiToken()
    };

    window.quoteEditConfig = {
        routes: {
            send: '{{ route("admin.quotes.send", $quote->id) }}',
            accept: '{{ route("admin.quotes.accept", $quote->id) }}',
            duplicate: '{{ route("admin.quotes.duplicate", $quote->id) }}',
            downloadPdf: '{{ route("admin.quotes.download-pdf", $quote->id) }}',
            destroy: '{{ route("api.admin.quotes.destroy", $quote->id) }}',
            index: '{{ route("admin.quotes.index") }}'
        },
        translations: {
            confirm_send: '{{ __("admin/quotes.confirm_send") }}',
            confirm_accept: '{{ __("admin/quotes.confirm_accept") }}',
            confirm_delete: '{{ __("admin/quotes.confirm_delete") }}',
            confirm_duplicate: '{{ __("admin/quotes.confirm_duplicate") }}'
        },
        apiToken: window.getApiToken()
    };
</script>
@if($quote->canBeEdited())
    @vite('resources/js/admin/quotes/form.js')
@endif
@vite('resources/js/admin/quotes/edit.js')
@endpush

@push('styles')
<style>
/* Select2 Dark Mode Support */
[data-bs-theme="dark"] .select2-container--default .select2-selection--single {
    background-color: var(--bs-body-bg);
    border-color: var(--bs-border-color);
    color: var(--bs-body-color);
}

[data-bs-theme="dark"] .select2-container--default .select2-selection--single .select2-selection__rendered {
    color: var(--bs-body-color);
}

[data-bs-theme="dark"] .select2-container--default .select2-selection--single .select2-selection__placeholder {
    color: var(--bs-secondary-color);
}

[data-bs-theme="dark"] .select2-dropdown {
    background-color: var(--bs-body-bg);
    border-color: var(--bs-border-color);
}

[data-bs-theme="dark"] .select2-container--default .select2-results__option {
    color: var(--bs-body-color);
}

[data-bs-theme="dark"] .select2-container--default .select2-results__option--highlighted[aria-selected] {
    background-color: var(--bs-primary);
    color: white;
}

[data-bs-theme="dark"] .select2-container--default .select2-search--dropdown .select2-search__field {
    background-color: var(--bs-body-bg);
    border-color: var(--bs-border-color);
    color: var(--bs-body-color);
}

[data-bs-theme="dark"] .select2-container--default.select2-container--focus .select2-selection--single {
    border-color: var(--bs-primary);
}
</style>
@endpush
