    @extends('frontend.layouts.master')

    @section('title','Checkout')

    @section('main-content')
    <div class="container my-4">
        <form method="POST" id="checkoutForm" action="{{ route('cart.order') }}">
            @csrf
            @php
            $subtotal = Helper::totalCartPrice();
            $coupon = session('coupon')['value'] ?? 0;
            @endphp
            <div class="row">


                {{-- ================= LEFT COLUMN ================= --}}
                <div class="col-lg-8">

                    {{-- ===== DELIVERY ADDRESS ===== --}}
                    <div class="card mb-4 shadow-sm">
                        <div class="card-body">
                            <h5 class="mb-3">Delivery Address</h5>

                            @if(auth()->check() && isset($addresses) && $addresses->count())
                            <div class="row" id="address_cards">
                                @foreach($addresses as $addr)
                                <div class="col-md-6 mb-3">
                                    <div class="address-card border rounded p-3 h-100"
                                        data-id="{{ $addr->id }}"
                                        data-created="{{ $addr->created_at }}"
                                        data-pincode="{{ $addr->post_code }}"
                                        data-default="{{ $addr->is_default ? '1' : '0' }}"
                                        style="cursor:pointer">

                                        <div class="d-flex justify-content-between">
                                            <strong>{{ $addr->first_name }} {{ $addr->last_name }}</strong>
                                            @if($addr->is_default)
                                            <span class="badge badge-primary">Default</span>
                                            @endif
                                        </div>

                                        <div class="text-muted small mt-2">
                                            {{ $addr->address1 }}<br>
                                            {{ $addr->address2 }}<br>
                                            {{ $addr->post_code }}<br>
                                            {{ $addr->phone }}
                                        </div>
                                    </div>
                                </div>
                                @endforeach
                            </div>

                            <button type="button" id="add_new_address_btn" class="btn btn-outline-primary btn-sm mt-2">
                                + Add New Address
                            </button>

                            <input type="hidden" name="address_id" id="address_id">

                            <hr>

                            <div id="new_address_form" style="display:none">
                                @else
                                <div id="new_address_form">
                                    @endif

                                    {{-- New Address Form --}}
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <h6 class="mb-0">Enter New Address</h6>
                                        <button type="button" class="btn btn-sm btn-outline-secondary" id="close_address_form">✕</button>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label>First Name</label>
                                            <input type="text" class="form-control" name="first_name" required>
                                        </div>

                                        <div class="col-md-6 mb-3">
                                            <label>Last Name</label>
                                            <input type="text" class="form-control" name="last_name" required>
                                        </div>

                                        <div class="col-md-6 mb-3">
                                            <label>Email</label>
                                            <input type="email" class="form-control" name="email" required>
                                        </div>

                                        <div class="col-md-6 mb-3">
                                            <label>Phone</label>
                                            <input type="tel" class="form-control" name="phone" required>
                                        </div>

                                        <div class="col-md-6 mb-3">
                                            <label>Postal Code</label>
                                            <input type="text" class="form-control" id="post_code" name="post_code" maxlength="6" required>
                                        </div>

                                        <div class="col-12 mb-3">
                                            <label>Address Line 1</label>
                                            <input type="text" class="form-control" name="address1" required>
                                        </div>

                                        <div class="col-12 mb-3">
                                            <label>Address Line 2</label>
                                            <input type="text" class="form-control" name="address2">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label>City</label>
                                            <input type="text" class="form-control" name="city" required>
                                        </div>

                                        <div class="col-md-6 mb-3">
                                            <label>State</label>
                                            <input type="text" class="form-control" name="state" required>
                                        </div>

                                        <div class="col-12">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="save_address" value="1">
                                                <label class="form-check-label">Save this address</label>
                                            </div>
                                        </div>
                                    </div>

                                </div> {{-- new_address_form --}}
                            </div>
                        </div>

                        {{-- ===== ORDER DETAILS ===== --}}
                        <div class="card shadow-sm">
                            <div class="card-body">
                                <h5 class="mb-3">Order Details</h5>

                                @foreach(Helper::getAllProductFromCart() as $i => $cart)
                                <div class="d-flex justify-content-between align-items-center border-bottom py-2">
                                    <div class="d-flex align-items-center">
                                        <div class="badge badge-light mr-2">{{ $i+1 }}</div>
                                        <img src="{{ $cart->product->photo ?? '' }}" width="50" class="mr-3 rounded">
                                        <div>
                                            <div>{{ $cart->product->title ?? '' }}</div>
                                            <small class="text-muted">Qty: {{ $cart->quantity }}</small>
                                        </div>
                                    </div>
                                    <strong>Rs. {{ number_format($cart->amount,2) }}</strong>
                                </div>
                                @endforeach

                            </div>
                        </div>

                    </div> {{-- END LEFT COLUMN --}}


                    {{-- ================= RIGHT COLUMN ================= --}}
                    <div class="col-lg-4 mb-4">

                        <div class="sticky-wrap">

                            <div class="card shadow-sm mb-3">
                                <div class="card-body">
                                    <h5>Cart Summary</h5>

                                    @php
                                    $subtotal = Helper::totalCartPrice();
                                    $coupon = session('coupon')['value'] ?? 0;
                                    $total = $subtotal - $coupon;
                                    @endphp

                                    <div class="d-flex justify-content-between">
                                        <span>Subtotal</span>
                                        <span>Rs. {{ number_format($subtotal,2) }}</span>
                                    </div>

                                    <div class="mt-3">
                                        <small class="text-muted">Shipping</small>
                                        <div id="shipping_box" class="small text-muted">
                                            Enter postal code to see options
                                        </div>
                                    </div>

                                    <div id="shipping_row" class="d-flex justify-content-between mt-2" style="display:none">
                                        <span id="shipping_label">Shipping</span>
                                        <span id="shipping_amount">Rs. 0.00</span>
                                    </div>
                                    @if($coupon)
                                    <div class="d-flex justify-content-between text-success">
                                        <span>You Save</span>
                                        <span>- Rs. {{ number_format($coupon,2) }}</span>
                                    </div>
                                    @endif

                                    <hr>

                                    <div class="d-flex justify-content-between font-weight-bold">
                                        <span>Total</span>
                                        <span id="order_total">Rs. {{ number_format($total,2) }}</span>
                                    </div>

                                    <input type="hidden" id="total_amount" value="{{ $total }}">
                                    <input type="hidden" name="shipping_cost" id="shipping_cost" value="0">
                                    <input type="hidden" name="courier_name" id="courier_name">
                                    <input type="hidden" name="courier_id" id="courier_id">
                                </div>
                            </div>

                            <div class="card shadow-sm mb-3">
                                <div class="card-body">
                                    <h5>Payment Method</h5>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="payment_method" value="cod">
                                        <label class="form-check-label">Cash On Delivery</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="payment_method" value="razorpay">
                                        <label class="form-check-label">Razorpay (UPI / Card / NetBanking)</label>
                                    </div>
                                </div>
                            </div>

                            <button type="button" id="checkoutBtn" class="btn btn-dark btn-lg btn-block">
                                Proceed to Checkout
                            </button>

                        </div>
                    </div>

                </div>
        </form>
    </div>
    @endsection


    @push('styles')
    <style>
        .address-card {
            transition: .2s
        }

        .address-card:hover {
            border-color: #007bff
        }

        .address-card.active {
            border: 2px solid #007bff;
            background: #f8fbff
        }

        .sticky-wrap {
            position: sticky;
            top: 20px
        }

        @media(max-width:991px) {
            .sticky-wrap {
                position: relative
            }
        }

        .address-card {
            min-height: 160px;
        }
    </style>
    @endpush


    @push('scripts')
    <script>
        let subtotal = @json($subtotal);
        let coupon = @json($coupon);
    </script>

    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {

            // ===== DOM =====
            const addressCards = document.querySelectorAll('.address-card');
            const addressIdInput = document.getElementById('address_id');
            const postCodeInput = document.getElementById('post_code');

            function setPincode(pin) {
                const input = document.getElementById('post_code');

                if (input) {
                    input.value = pin;
                }

                // Always call shipping directly
                fetchShippingRates(pin);
            }

            const shippingBox = document.getElementById('shipping_box');
            const shippingRow = document.getElementById('shipping_row');
            const shippingAmt = document.getElementById('shipping_amount');
            const orderTotalEl = document.getElementById('order_total');
            const totalAmountEl = document.getElementById('total_amount');
            const shippingCost = document.getElementById('shipping_cost');
            const courierName = document.getElementById('courier_name');
            const courierId = document.getElementById('courier_id');
            const checkoutBtn = document.getElementById('checkoutBtn');
            const addBtn = document.getElementById('add_new_address_btn');
            const closeBtn = document.getElementById('close_address_form');
            const newForm = document.getElementById('new_address_form');
            const shippingLabel = document.getElementById('shipping_label');

            // ===== Address Select =====
            async function selectAddressCard(card) {
                addressCards.forEach(c => c.classList.remove('active'));
                card.classList.add('active');
                addressIdInput.value = card.dataset.id;

                //  load address into form
                const res = await fetch(`{{ url('/user/address') }}/${card.dataset.id}`);
                const addr = await res.json();

                document.querySelector('[name="first_name"]').value = addr.first_name || '';
                document.querySelector('[name="last_name"]').value = addr.last_name || '';
                document.querySelector('[name="email"]').value = addr.email || '';
                document.querySelector('[name="phone"]').value = addr.phone || '';
                document.querySelector('[name="post_code"]').value = addr.post_code || '';
                document.querySelector('[name="address1"]').value = addr.address1 || '';
                document.querySelector('[name="address2"]').value = addr.address2 || '';
                document.querySelector('[name="city"]').value = addr.city || '';
                document.querySelector('[name="state"]').value = addr.state || '';

                fetchShippingRates(addr.post_code);
            }

            addressCards.forEach(card => {
                card.addEventListener('click', () => selectAddressCard(card));
            });

            // ===== Auto Select Address on Page Ready =====
            if (addressCards.length) {
                console.log("AUTO SELECT BLOCK RUNNING");
                let def = [...addressCards].find(c => c.dataset.default === '1');
                if (def) {
                    selectAddressCard(def);
                } else if (addressCards.length === 1) {
                    selectAddressCard(addressCards[0]);
                } else {
                    let last = [...addressCards].sort((a, b) =>
                        new Date(b.dataset.created) - new Date(a.dataset.created)
                    )[0];

                    selectAddressCard(last);
                }
            }

            // ===== Toggle Form =====
            addBtn?.addEventListener('click', () => {
                newForm.style.display = 'block';
                addBtn.style.display = 'none';
            });
            closeBtn?.addEventListener('click', () => {
                newForm.style.display = 'none';
                addBtn.style.display = 'inline-block';
            });

            // ===== Totals =====
            function updateTotal(ship) {
                let total = subtotal + ship - coupon;
                orderTotalEl.innerText = 'Rs. ' + total.toFixed(2);
                totalAmountEl.value = total;
                if (ship > 0) {
                    shippingRow.style.display = 'flex';
                    shippingAmt.innerText = 'Rs. ' + ship.toFixed(2);
                }
            }

            // ===== Shipping =====
            if (postCodeInput) {

                postCodeInput.addEventListener('input', function() {
                    const pin = this.value.trim();
                    if (pin.length === 6) {
                        fetchShippingRates(pin);
                    }
                });
            }

async function fetchShippingRates(pincode) {

    console.log("STEP 1: fetchShippingRates called");
    console.log("PINCODE:", pincode);

    if (!pincode || pincode.trim().length !== 6) {
        console.log("STEP 2: Invalid pincode");
        shippingBox.innerHTML = 'Enter postal code to see options';
        return;
    }

    shippingBox.innerHTML = 'Checking delivery options...';

    try {

        let method = document.querySelector('input[name="payment_method"]:checked');

        console.log("STEP 3: Sending request to backend");

        const res = await fetch('{{ url("checkout/shipping-rates") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                pincode: pincode.trim(),
                cod: method && method.value === 'cod' ? 1 : 0
            })
        });

        console.log("STEP 4: Response status", res.status);

        const text = await res.text();
        console.log("STEP 5: Raw response", text);

        const data = JSON.parse(text);

        console.log("STEP 6: Parsed JSON", data);

        if (!data.status || !Array.isArray(data.options)) {
            console.log("STEP 7: Invalid response format");
            shippingBox.innerHTML = '<span class="text-danger">No delivery available</span>';
            return;
        }

        if (data.options.length === 0) {
            console.log("STEP 8: No couriers returned");
            shippingBox.innerHTML = '<span class="text-danger">No delivery available</span>';
            return;
        }

        console.log("STEP 9: Courier options", data.options);

        data.options.sort((a,b)=>parseFloat(a.rate)-parseFloat(b.rate));

        const cheapest = data.options[0];

        console.log("STEP 10: Cheapest courier", cheapest);

        const cost = parseFloat(cheapest.rate) || 0;
        const name = cheapest.courier || '';

        shippingBox.innerHTML = `
            <div class="border rounded p-2 bg-light">
                <strong>${name}</strong><br>
                ₹${cost.toFixed(2)}
            </div>
        `;

        shippingCost.value = cost;
        courierName.value = name;
        courierId.value = cheapest.courier_company_id;

        updateTotal(cost);

    } catch (err) {

        console.error("STEP ERROR:", err);
        shippingBox.innerHTML = '<span class="text-danger">Shipping unavailable</span>';

    }
}


                               // ===== Checkout btn =====
                    checkoutBtn.onclick = async function() {

    let method = document.querySelector('input[name="payment_method"]:checked');

    if (!method) {
        alert('Select payment method');
        return;
    }

    // Save checkout session
    await fetch("{{ route('checkout.session') }}", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRF-TOKEN": "{{ csrf_token() }}"
        },
        body: JSON.stringify(Object.fromEntries(new FormData(checkoutForm)))
    });

    // ===== COD =====
    if (method.value === 'cod') {

        checkoutForm.action = "{{ route('cart.order') }}";
        checkoutForm.submit();
        return;

    }

    // ===== Razorpay =====
    let orderRes = await fetch("{{ url('/create-order') }}", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRF-TOKEN": "{{ csrf_token() }}"
        },
        body: JSON.stringify({
            amount: parseInt(totalAmountEl.value)
        })
    });

    let order = await orderRes.json();

    new Razorpay({
        key: "{{ env('RAZORPAY_KEY') }}",
        amount: order.amount,
        currency: "INR",
        order_id: order.order_id,
        handler: async function(resp) {

            let verify = await fetch("{{ url('/verify-payment') }}", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRF-TOKEN": "{{ csrf_token() }}"
                },
                body: JSON.stringify(resp)
            });

            let r = await verify.json();

            if (r.status === 'success' && r.redirect_url) {
                window.location.href = r.redirect_url;
            }

        }
    }).open();
};

        });
    </script>


    @endpush