@extends('layouts.app')
@section('title', 'Cart')

@section('content')
    <style>
        .badge {
            font-size: 1rem;
            font-style: normal;
            font-weight: 400;
            font-family: "IBM Plex Sans", sans-serif;
            line-height: 1.5;
        }
    </style>
    <link rel="stylesheet" href="{{ asset('assets/css/subscriptions.css') }}">

    <!-- Main content -->
    <section class="content">
        @if($cartItems)
            <div class="row">
                @if(session('success'))
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        {{ session('success') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                @endif

                @if(session('error'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        {{ session('error') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                @endif

                <div class="col-md-12 col-xs-12">
                    <div class="box">
                        <div class="box-body">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Product Subscription</th>
                                        <th>Billing Period</th>
                                        <th>Quantity</th>
                                        <th>Subtotal</th>
                                        <th>Remove</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @php $intTotal = 0; @endphp
                                    @if(isset($cartItems))
                                        @foreach($cartItems as $cartId => $cartItem)
                                            <tr id="cart-row-{{ $cartId }}">
                                                <td>{{ $loop->index + 1 }}</td>
                                                <td>{{ $cartItem->product }}</td>
                                                <td class="billing-period" data-billing="{{ $cartItem->billing }}">
                                                    {{ $cartItem->billing_period }}</td>
                                                <td>
                                                    <div class="number-of-users" data-id="{{ $cartId }}">
                                                        <span class="minus" data-page="cart"><span
                                                                class="glyphicon glyphicon-minus"></span></span>
                                                        <input type="text" value="{{ $cartItem->quantity }}" />
                                                        <span class="plus" data-page="cart"><span
                                                                class="glyphicon glyphicon-plus"></span></span>
                                                    </div>
                                                </td>
                                                <td class="product-price" data-price="{{ $cartItem->base_rate_monthly_billed }}">
                                                    ${{ number_format($cartItem->subtotal, 2) }}</td>
                                                <td>
                                                    <a style="cursor:pointer;" class="delete-cart-item" data-id="{{ $cartId }}"
                                                        data-product="{{ $cartItem->product }}" data-bs-toggle="modal"
                                                        data-bs-target="#deleteModal">
                                                        <i class="fa fa-trash-o fa-lg"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                            @php $intTotal += $cartItem->subtotal; @endphp
                                        @endforeach
                                    @endif
                                </tbody>
                            </table>
                            <!-- Delete modal (only ONCE outside foreach) -->
                            <div class="modal fade none-border" id="deleteModal">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h4 class="modal-title"><strong>Delete</strong> Item</h4>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                        </div>
                                        <div class="modal-body">
                                            <p>You are about to delete <b><i id="deleteItemName"></i></b> from your cart.</p>
                                            <input type="hidden" name="cartId" id="deleteCartId">
                                            <p>Do you want to proceed?</p>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-danger" id="confirmDeleteBtn">Delete</button>
                                            <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 col-xs-12">
                    <div class="box">
                        <div class="box-body">
                            <p class="lead">Payment Methods:</p>
                            <img src="{{ asset('assets/images/visa.png') }}" alt="Visa">
                            <img src="{{ asset('assets/images/mastercard.png') }}" alt="Mastercard">
                            <img src="{{ asset('assets/images/american-express.png') }}" alt="American Express">
                            <img src="{{ asset('assets/images/paypal2.png') }}" alt="Paypal">
                            <p class="text-muted well well-sm no-shadow" style="margin-top: 10px;">
                                We do accept both, credit cards and Paypal.
                            </p>
                        </div>
                    </div>
                </div>
                <div class="col-md-6 col-xs-12">
                    <div class="box">
                        <div class="box-body">
                            <p class="lead">Amount Due</p>
                            <table class="table table-bordered table-hover">
                                <tbody>
                                    <tr>
                                        <th>Subtotal:</th>
                                        <td class="subtotal-price">${{ number_format($intTotal, 2) }}</td>
                                    </tr>
                                    <tr>
                                        <th>Tax (0%):</th>
                                        <td class="tax-price" data-price="0">$0.00</td>
                                    </tr>
                                    <tr>
                                        <th>Shipping:</th>
                                        <td class="shipping-price" data-price="0">$0.00</td>
                                    </tr>
                                    <tr>
                                        <th>Total:</th>
                                        <td class="grand-total">${{ number_format($intTotal, 2) }}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="text-end">
                            <form action="{{ url('/checkout') }}" method="get">
                                @csrf
                                <button type="submit" class="btn btn-primary">Proceed to Checkout</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        @else
            <div class="cart-empty">Your cart is empty <i class="fa fa-shopping-cart"></i></div>
        @endif

        <script src="{{ asset('assets/js/pages/subscriptions.js') }}"></script>

        <script>
            function updateCartCount() {
                fetch('/cart/count')
                    .then(response => response.json())
                    .then(data => {
                        let count = 0;
                        if (Array.isArray(data)) {
                            count = data[0];
                        }
                        document.getElementById('cart-count-badge').textContent = count;
                    })
                    .catch(err => console.error('Error fetching cart count:', err));
            }
            $(document).ready(function () {
                // Step 1: Open modal & set product details
                $(".delete-cart-item").on("click", function (e) {
                    e.preventDefault();
                    let cartId = $(this).data("id");
                    let productName = $(this).data("product");

                    $("#deleteItemName").text(productName);
                    $("#deleteCartId").val(cartId);
                    $("#deleteModal").modal("show");
                });

                // Step 2: Confirm deletion via AJAX
                $("#confirmDeleteBtn").on("click", function () {
                    let cartId = $("#deleteCartId").val();

                    $.ajax({
                        url: "{{ url('/cart/delete') }}/" + cartId,
                        type: "POST",
                        data: {
                            _token: $('meta[name="csrf-token"]').attr("content"),
                            cart_id: cartId
                        },
                        success: function (response) {
                            if (response.success) {
                                toastr.success(response.message);
                                $("#cart-row-" + cartId).fadeOut(300, function () {
                                    $(this).remove();
                                    // Recalculate total
                                    let newTotal = 0;
                                    $('.product-price').each(function () {
                                        let price = parseFloat($(this).data('price')) * parseInt($(this).siblings('.number-of-users').find('input').val());
                                        newTotal += price;
                                    });
                                    $('.subtotal-price').text('$' + newTotal.toFixed(2));
                                    $('.grand-total').text('$' + newTotal.toFixed(2));
                                    if ($('.table-striped tbody tr').length === 0) {
                                        $('.content').html('<div class="cart-empty">Your cart is empty <i class="fa fa-shopping-cart"></i></div>');
                                    }
                                });
                                updateCartCount();
                                $("#deleteModal").modal("hide");
                            } else {
                                toastr.error(response.message || "Something went wrong");
                            }
                        },
                        error: function (xhr) {
                            toastr.error("Server error: " + (xhr.responseJSON?.message || "Please try again."));
                        }
                    });
                });
            });
        </script>
@endsection
