@extends('layouts.land')

@section('title', 'Cart')

@section('content')

<link href="{{ asset('tingle-master/dist/tingle.min.css') }}" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/tingle/0.16.0/tingle.min.js" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js" crossorigin="anonymous"></script>

@include('sweetalert::alert')

@if(!Auth::check())
    <button class="trigger-button btn btn-primary">Have an account? Login</button>
    <div class="tingle-demo container p-5">
        <form action="{{ route('loginInCart') }}" method="POST" id="login-form" style="display: none;">
            @csrf
            <div class="form-group">
                <label>Email Address</label>
                <input type="email" name="email" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" class="form-control" required>
            </div>
            <button type="submit" class="btn btn-primary">Login</button>
        </form>
    </div>
@endif

<div class="container my-5">
    <table id="cart" class="table table-hover shadow-sm rounded">
        <thead class="table-light">
            <tr>
                <th style="width:50%">Product</th>
                <th style="width:15%">Price</th>
                <th style="width:8%">Quantity</th>
                <th style="width:15%" class="text-center">Subtotal</th>
                <th style="width:12%"></th>
            </tr>
        </thead>
        <tbody>
            @php $total = 0; @endphp
            @forelse(session('cart', []) as $id => $details)
                @php
                    $price = $details['price'] ?? 0;
                    $quantity = $details['quantity'] ?? 1;
                    $subtotal = $price * $quantity;
                    $total += $subtotal;
                @endphp
                <tr>
                    <td data-th="Product">
                        <div class="d-flex">
                            <img src="{{ $details['image'] ?? asset('default.jpg') }}" width="100" height="100" class="img-responsive me-3 rounded"/>
                            <div>
                                <h5>{{ $details['name'] ?? 'No name' }}</h5>
                                <small>{{ $details['desc'] ?? 'No description available' }}</small>
                            </div>
                        </div>
                    </td>
                    <td data-th="Price">₦{{ number_format($price, 2) }}</td>
                    <td data-th="Quantity">
                        <div class="input-group">
                            <button class="btn btn-outline-secondary decrease-quantity" data-id="{{ $id }}">-</button>
                            <input type="number" value="{{ $quantity }}" class="form-control quantity-input" min="1" data-id="{{ $id }}">
                            <button class="btn btn-outline-secondary increase-quantity" data-id="{{ $id }}">+</button>
                        </div>
                    </td>
                    <td data-th="Subtotal" class="text-center">₦{{ number_format($subtotal, 2) }}</td>
                    <td class="actions" data-th="">
                        <button class="btn btn-danger btn-sm remove-from-cart" data-id="{{ $id }}"><i class="fa fa-trash"></i></button>
                    </td>
                </tr>
            @empty
                <tr>
                    <td colspan="5" class="text-center text-muted">Your cart is empty</td>
                </tr>
            @endforelse
        </tbody>
        @if ($total > 0)
            <tfoot>
                <tr>
                    <td><a href="{{ url('/') }}" class="btn btn-warning"><i class="fa fa-angle-left"></i> Continue Shopping</a></td>
                    <td colspan="2" class="text-end"><strong>Total</strong></td>
                    <td class="text-center"><strong>₦{{ number_format($total, 2) }}</strong></td>
                    <td>
                        <button class="btn btn-danger" id="clear-cart">Clear Cart</button>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#checkoutModal">Checkout</button>
                    </td>
                </tr>
            </tfoot>
        @endif
    </table>
</div>

<!-- [Checkout Modal code remains unchanged] -->

<script>
    // Clear entire cart
    const clearCartButton = document.getElementById('clear-cart');
    if (clearCartButton) {
        clearCartButton.addEventListener('click', function() {
            $.ajax({
                url: '{{ url('clear-cart') }}',
                method: 'DELETE',
                data: { _token: '{{ csrf_token() }}' },
                success: function(response) {
                    if (response.success) {
                        window.location.reload();
                    }
                }
            });
        });
    }

    // Quantity increase button
    $('.increase-quantity').on('click', function () {
        const id = $(this).data('id');
        const quantityInput = $(`input[data-id="${id}"]`);
        const newQuantity = parseInt(quantityInput.val()) + 1;
        updateCartQuantity(id, newQuantity);
    });

    // Quantity decrease button
    $('.decrease-quantity').on('click', function () {
        const id = $(this).data('id');
        const quantityInput = $(`input[data-id="${id}"]`);
        const newQuantity = Math.max(1, parseInt(quantityInput.val()) - 1); // Prevents below 1
        updateCartQuantity(id, newQuantity);
    });

    // Update cart quantity function
    function updateCartQuantity(id, quantity) {
        $.ajax({
            url: `{{ url('update-cart') }}/${id}`,
            method: 'PATCH',
            data: { _token: '{{ csrf_token() }}', quantity },
            success: function(response) {
                if (response.success) {
                    window.location.reload();
                }
            }
        });
    }

    // Remove item from cart
    $('.remove-from-cart').on('click', function () {
        const id = $(this).data('id');
        $.ajax({
            url: `{{ url('cart.remove') }}/${id}`,
            method: "DELETE",
            data: { _token: '{{ csrf_token() }}' },
            success: function () {
                window.location.reload();
            }
        });
    });
</script>

<style>
    /* Responsive adjustments */
    @media (max-width: 768px) {
        #cart {
            font-size: 0.9rem;
        }
        .quantity-input {
            max-width: 60px;
        }
    }
</style>

@endsection
