@extends('layouts.landing', ['title' => 'Checkout v.1 - Delivery Info Step 1'])

@section('content')
    <x-layout.header-grocery />

    <!-- Page content -->
    <main class="content-wrapper">
        <div class="container py-5">
            <div class="row pt-1 pt-sm-3 pt-lg-4 pb-2 pb-md-3 pb-lg-4 pb-xl-5">

                <!-- Delivery info (Step 1) -->
                <div class="col-lg-8 col-xl-7 mb-5 mb-lg-0">
                    <div class="d-flex flex-column gap-5 pe-lg-4 pe-xl-0">
                        <div class="d-flex align-items-start">
                            <div class="d-flex align-items-center justify-content-center bg-body-secondary text-body-secondary rounded-circle fs-sm fw-semibold lh-1 flex-shrink-0"
                                style="width: 2rem; height: 2rem; margin-top: -.125rem">1</div>
                            <div class="w-100 ps-3 ps-md-4">
                                <h2 class="h5 text-body-secondary mb-md-4">{{ __('checkout.delivery_method') }}</h2>

                                @if ($delivery_method == 'shipping')
                                    <p>{{ __('checkout.delivery') }}</p>
                                    @if ($address)
                                        <p>{{ $address->location }}</p>
                                    @endif
                                @else
                                    <p>{{ __('checkout.pickup') }}</p>
                                @endif
                            </div>
                        </div>
                        <div class="d-flex align-items-start" id="shippingAddressStep">
                            <div class="d-flex align-items-center justify-content-center bg-primary text-white rounded-circle fs-sm fw-semibold lh-1 flex-shrink-0"
                                style="width: 2rem; height: 2rem; margin-top: -.125rem">2</div>


                            <div class="w-100 ps-3 ps-md-4">
                                <h1 class="h5 mb-12">{{ __('checkout.choose_shipping') }}
                                </h1>
                                <form action="{{ route('checkout.shipping.process') }}" method="post">
                                    @csrf
                          
                                    @if ($delivery_method == 'shipping')
                                        @foreach ($shipping_list as $shipping)
                                            <div class="form-check mb-3">
                                                <input class="form-check-input" type="radio" name="shipping_option"
                                                    id="shipping_{{ $loop->index }}"
                                                    value="{{ $shipping['courier'] }}|{{ $shipping['service'] }}|{{ $shipping['cost'] }}"
                                                    {{ $loop->first ? 'checked' : '' }}>
                                                <label
                                                    class="form-check-label d-flex justify-content-between align-items-center"
                                                    for="shipping_{{ $loop->index }}">
                                                    <div>
                                                        <strong>{{ $shipping['title'] }}</strong>
                                                        <div class="text-muted small">{{ $shipping['description'] }}</div>
                                                    </div>
                                                    <div class="text-primary fw-bold">
                                                        Rp {{ number_format($shipping['cost'], 0, ',', '.') }}
                                                    </div>
                                                </label>
                                            </div>
                                        @endforeach
                                    @else
                                        <div class="alert alert-info">
                                            <i class="ci-store me-2"></i>
                                            {{ __('checkout.pickup_ready') }}
                                        </div>
                                    @endif

                                    <button type="submit" class="btn btn-lg btn-primary w-100 mt-4">
                                        <span>{{ __('checkout.continue_to_payment') }}</span>
                                        <i class="ci-chevron-right fs-lg ms-1 me-n1"></i>
                                    </button>
                                </form>
                            </div>
                        </div>
                        <div class="d-flex align-items-start">
                            <div class="d-flex align-items-center justify-content-center bg-body-secondary text-body-secondary rounded-circle fs-sm fw-semibold lh-1 flex-shrink-0"
                                style="width: 2rem; height: 2rem; margin-top: -.125rem">3</div>
                            <h2 class="h5 text-body-secondary ps-3 ps-md-4 mb-0">{{ __('checkout.payment') }}</h2>
                        </div>
                    </div>
                </div>


                <!-- Order summary (sticky sidebar) -->
                <aside class="col-lg-4 offset-xl-1" style="margin-top: -100px">
                    <div class="position-sticky top-0" style="padding-top: 100px">
                        <x-checkout.order-summary :subtotal="$subtotal" :total="$total" 
                            :showEdit="true" :editUrl="route('cart.index')" />
                    </div>
                </aside>
            </div>
        </div>
    </main>

    @include('layouts.partials/footer')
@endsection

@section('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Shipping option selection handler
            const shippingRadios = document.querySelectorAll('input[name="shipping_option"]');
            console.log('Found shipping radios:', shippingRadios.length);

            shippingRadios.forEach((radio, index) => {
                console.log(`Radio ${index}:`, radio.value, radio.checked);
                radio.addEventListener('change', function() {
                    console.log('Shipping option changed:', this.value, this.checked);
                    if (this.checked) {
                        updateOrderSummaryWithShippingCost(this.value);
                    }
                });
            });

            function updateOrderSummaryWithShippingCost(shippingValue) {
                const saving = {{ session('use_point') ?? 0 }};
                console.log('updateOrderSummaryWithShippingCost called with:', shippingValue);

                // Parse the shipping value: courier|service|cost
                const parts = shippingValue.split('|');
                console.log('Parsed parts:', parts);
                if (parts.length !== 3) {
                    console.log('Invalid shipping value format');
                    return;
                }

                const courier = parts[0];
                const service = parts[1];
                const cost = parseInt(parts[2]);
                console.log('Extracted cost:', cost);

                // Update order summary
                const subtotalElement = document.getElementById('cart-subtotal');
                console.log('Subtotal element:', subtotalElement);
                if (!subtotalElement) {
                    console.log('Subtotal element not found');
                    return;
                }

                const currentSubtotal = parseFloat(subtotalElement.textContent.replace(/[^\d]/g, ''));
                console.log('Current subtotal:', currentSubtotal);
                const newTotal = currentSubtotal + cost - saving;
                console.log('New total:', newTotal);

                // Store original total
                if (!window.originalTotal) {
                    window.originalTotal = subtotalElement.textContent;
                    console.log('Stored original total:', window.originalTotal);
                }

                // Update total
                const totalElement = document.getElementById('cart-estimated-total');
                console.log('Total element:', totalElement);
                if (totalElement) {
                    totalElement.textContent = `Rp ${number_format(newTotal, 0, ',', '.')}`;
                    console.log('Updated total to:', totalElement.textContent);
                }

                // Show shipping cost in summary
                showShippingCost(cost);
            }

            function showShippingCost(cost, isFree = false) {
                console.log('showShippingCost called with:', cost, isFree);

                // Use existing shipping row in order summary
                const shippingRow = document.getElementById('shipping-row');
                console.log('Shipping row element:', shippingRow);
                if (!shippingRow) {
                    console.log('Shipping row not found');
                    return;
                }

                const costElement = shippingRow.querySelector('span:last-child');
                console.log('Cost element:', costElement);
                if (!costElement) {
                    console.log('Cost element not found');
                    return;
                }

                if (isFree) {
                    costElement.textContent = '{{ __('checkout.free') }}';
                    costElement.className = 'text-success fw-medium';
                    console.log('Set to free shipping');
                } else {
                    costElement.textContent = `Rp ${number_format(cost, 0, ',', '.')}`;
                    costElement.className = 'text-dark-emphasis fw-medium';
                    console.log('Set shipping cost to:', costElement.textContent);
                }

                // Ensure the shipping row is visible
                shippingRow.style.display = 'flex';
                console.log('Made shipping row visible');
            }

            // Initialize shipping cost on page load for checked option
            const checkedShippingRadio = document.querySelector('input[name="shipping_option"]:checked');
            console.log('Checked shipping radio on load:', checkedShippingRadio);
            if (checkedShippingRadio) {
                console.log('Initializing with value:', checkedShippingRadio.value);
                updateOrderSummaryWithShippingCost(checkedShippingRadio.value);
            }

        // Number formatting helper
        function number_format(number, decimals, dec_point, thousands_sep) {
            number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
            var n = !isFinite(+number) ? 0 : +number;
            var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
            var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
            var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

            var s = '';
            var toFixedFix = function(n, prec) {
                var k = Math.pow(10, prec);
                return '' + Math.round(n * k) / k;
            };

            s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
            if (thousands_sep) {
                var re = /(-?\d+)(\d{3})/;
                while (re.test(s[0])) {
                    s[0] = s[0].replace(re, '$1' + sep + '$2');
                }
            }

            if ((s[1] || '').length < prec) {
                s[1] = s[1] || '';
                s[1] += new Array(prec - s[1].length + 1).join('0');
            }

            return s.join(dec);
        }
        });
    </script>
@endsection
