@extends('frontend.layout.master')
@section('title', $pageTitle)
@section('content')

<section>
	<div class="product_details_div_1">
		<div class="container">

			@if($products->isEmpty())
			<div class="empty_alart_div_1 text-center">
			    <img src="{{ url('/') }}/frontend/img/shopping-cart.gif" class="empty_alart_img_1">
			    <p class="empty_alart_p_1">No products found. Try searching for something else.</p>
			</div>
    			
			@else
			<div class="product_details_div_2">
				<div class="row">
					@foreach($products as $product) {{-- Loop through all products --}}
					<div class="col-lg-6 col-md-6 col-12" style="padding: 0px;">
						<div class="product_details_div_3" data-product-id="{{ $product->id }}">
							<div class="product_details_div_5">
								{{-- Main product image --}}
								<div class="tabcontent_product_show" id="city_001_{{ $product->id }}" style="display: block;">
									<div>
										<img src="{{ url('/') }}/{{$product->product_image}}" class="product_details_img_1">
									</div>
								</div>

								{{-- Gallery images tab contents --}}
								@foreach($galleryimg->where('product_id', $product->id) as $index => $image)
								<div class="tabcontent_product_show" id="city_00{{ $index + 2 }}_{{ $product->id }}" style="display: none;">
									<img src="{{ url('/') }}/{{$image->image}}" class="product_details_img_1">
								</div>
								@endforeach
							</div>

							<div class="product_details_div_6 tab_product_show">
								{{-- Main image thumbnail --}}
								<div class="tablinks_product_show" onclick="openCity001(event, 'city_001_{{ $product->id }}', '{{ $product->id }}')">
									<img src="{{ url('/') }}/{{$product->product_image}}" class="product_details_img_2">
								</div>

								{{-- Gallery images thumbnails --}}
								@foreach($galleryimg->where('product_id', $product->id) as $index => $image)
								<div class="tablinks_product_show" onclick="openCity001(event, 'city_00{{ $index + 2 }}_{{ $product->id }}', '{{ $product->id }}')">
									<img src="{{ url('/') }}/{{$image->image}}" class="product_details_img_2">
								</div>
								@endforeach
							</div>
						</div>
					</div>
					<div class="col-lg-6 col-md-6 col-12" style="padding: 0px;">
						<div class="product_details_div_4">
							<h3 class="product_details_h_1">{{$product->product_name}}</h3>
							<p class="product_details_p_1"><b>Product code :</b> {{$product->product_code}}</p>
							<p class="product_details_p_1"><b>Availability :</b> {{$product->product_quantity}}</p>
							<hr>
							<p class="product_details_p_2">Price</p>
							<div class="product_details_div_7">
								<p class="product_details_p_3">₹ {{$product->product_saleprice}}</p>
								<p class="product_details_p_4">₹ {{$product->product_orgprice}}</p>
							</div>
							<hr>
							<div class="product_details_div_8">
								<form class="add-to-cart-form" action="{{ route('add.to.cart', $product->id) }}" method="POST">
									@csrf
									<div class="form-group" style="display: flex;">
										<label class="control-label">Quantity</label>
										<div class="holder">
											<a class="quantity_button minus arrow_icon nk_quantity_btn">-</a>
											<input type="number" name="quantity" value="1" size="2" id="input-quantity" class="quantity nk_quantity_result">
											<a class="quantity_button plus arrow_icon nk_quantity_btn" style="margin-left: -5px;">+</a>
										</div>
									</div>
									<button type="submit" class="product_details_btn_11 btn-submit">
										Add to Cart
									</button>
								</form>
							</div>
							<hr>
						</div>
					</div>
					@endforeach
				</div>

				<br>
				<div class="product_details_div_10">
					<h4 class="product_details_h_2">Description</h4>
					@foreach($products as $product)
					<p class="product_details_p_5">{!! $product->product_dec !!}</p>
					@endforeach
				</div>
			</div>
			@endif
		</div>
	</div>
</section>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
// <script>
// 	$(document).ready(function() {
// 		$('.product_details_btn_1').on('click', function(event) {
// 			event.preventDefault();
// 			var url = $(this).data('url');
// 			var quantity = $('#input-quantity').val();

// 			$.ajax({
// 				url: url,
// 				type: 'GET',
// 				data: {
// 					quantity: quantity
// 				},
// 				success: function(response) {
// 					// Handle the success response here
// 					console.log(response);
// 					// Redirect to the cart page
// 					window.location.href = "{{ route('cart') }}"; // Adjust the path to your actual cart route
// 				},
// 				error: function(xhr, status, error) {
// 					// Handle the error response here
// 					console.error(error);
// 					// Show an error message or perform other error handling
// 				}
// 			});
// 		});
// 	});
// </script>

// <script>
// 	document.addEventListener("DOMContentLoaded", function() {
// 		const minusBtn = document.querySelector(".minus");
// 		const plusBtn = document.querySelector(".plus");
// 		const quantityInput = document.querySelector("#input-quantity");

// 		// Prevent users from entering 0 or negative values manually
// 		quantityInput.addEventListener("input", function() {
// 			if (this.value < 1) {
// 				this.value = 1;
// 			}
// 		});

// 		// Decrease quantity but not below 1
// 		minusBtn.addEventListener("click", function() {
// 			let currentValue = parseInt(quantityInput.value);
// 			if (currentValue > 1) {
// 				quantityInput.value = currentValue - 1;
// 			}
// 		});

// 		// Increase quantity
// 		plusBtn.addEventListener("click", function() {
// 			let currentValue = parseInt(quantityInput.value);
// 			quantityInput.value = currentValue + 1;
// 		});
// 	});
// </script>

<script>
    $(document).ready(function() {
        // Handle AJAX Add to Cart
        $('.btn-submit').on('click', function(event) {
            event.preventDefault();
            
            let form = $(this).closest('form');
            let url = form.attr('action');
            let quantity = $('#input-quantity').val();

            $.ajax({
                url: url,
                type: 'POST',
                data: form.serialize(),
                success: function(response) {
                    console.log(response);
                    // Redirect to the cart page or show a message
                    window.location.href = "{{ route('cart') }}";  // Adjust to your cart route
                },
                error: function(xhr) {
                    console.error(xhr.responseText);
                }
            });
        });

        // Handle Quantity Buttons
        $('.quantity_button').on('click', function() {
            let quantityInput = $('#input-quantity');
            let currentValue = parseInt(quantityInput.val());

            if ($(this).hasClass('plus')) {
                quantityInput.val(currentValue + 1);
            } else if ($(this).hasClass('minus') && currentValue > 1) {
                quantityInput.val(currentValue - 1);
            }
        });

        // Prevent manually entering values below 1
        $('#input-quantity').on('input', function() {
            if (this.value < 1) {
                this.value = 1;
            }
        });
    });
</script>

<script>
	$(document).ready(function() {
		$(document).on("submit", ".add-to-cart-form", function(e) {
			e.preventDefault(); // Prevent default form submission

			var form = $(this);

			$.ajax({
				url: form.attr("action"),
				method: "POST",
				data: form.serialize(),
				dataType: "json",
				success: function(response) {
					if (response.status === "error") {
						Swal.fire({
							icon: "error",
							title: "Oops...",
							text: response.message
						});
					} else if (response.status === "success") {
						Swal.fire({
							icon: "success",
							title: "Success!",
							text: "Product added to cart!",
							showConfirmButton: true
						}).then((result) => {
							if (result.isConfirmed) {
								location.reload(); // Reload the page after clicking OK
							}
						});

						// Update cart count dynamically
						$("#cart-count").text(response.cart_count);
					}
				},
				error: function (xhr) {
    Swal.fire({
        icon: "error",
        title: "Error",
        text: "Something went wrong, Please log in first to continue.",
        showConfirmButton: false,      // Hides the "OK" button
        timer: 2000                    // Automatically closes after 2 seconds
    });

    // Redirect to login page after 2 seconds
    setTimeout(() => {
        window.location.href = "{{ route('login_user') }}";   // Replace with your login route
    }, 200);  // Match the timer duration

    console.log(xhr.responseText);
}
			});
		});
	});
</script>

// <script>
// 	$('.quantity_button.plus').on('click', function() {
// 		var oldVal = $('input.quantity').val();
// 		var newVal = (parseInt($('input.quantity').val(), 10) + 1);
// 		$('input.quantity').val(newVal);
// 	});

// 	$('.quantity_button.minus').on('click', function() {
// 		var oldVal = $('input.quantity').val();
// 		if (oldVal > 1) {
// 			var newVal = (parseInt($('input.quantity').val(), 10) - 1);
// 		} else {
// 			newVal = 1;
// 		}
// 		$('input.quantity').val(newVal);
// 	});
// </script>

<script>
	function openCity001(evt, cityName, productId) {
		var i, tabcontent, tablinks;
		// Get all tab content and tab links within the same product container
		tabcontent = document.querySelectorAll('.product_details_div_3[data-product-id="' + productId + '"] .tabcontent_product_show');
		tablinks = document.querySelectorAll('.product_details_div_3[data-product-id="' + productId + '"] .tablinks_product_show');

		// Hide all tab content
		for (i = 0; i < tabcontent.length; i++) {
			tabcontent[i].style.display = "none";
		}

		// Remove the "active" class from all tab links
		for (i = 0; i < tablinks.length; i++) {
			tablinks[i].className = tablinks[i].className.replace(" active", "");
		}

		// Show the current tab content and add the "active" class to the clicked tab link
		document.getElementById(cityName).style.display = "block";
		evt.currentTarget.className += " active";
	}
</script>

<script>
	$('.product-img--main')
		// tile mouse actions
		.on('mouseover', function() {
			$(this).children('.product-img--main__image').css({
				'transform': 'scale(' + $(this).attr('data-scale') + ')'
			});
		})
		.on('mouseout', function() {
			$(this).children('.product-img--main__image').css({
				'transform': 'scale(1)'
			});
		})
		.on('mousemove', function(e) {
			$(this).children('.product-img--main__image').css({
				'transform-origin': ((e.pageX - $(this).offset().left) / $(this).width()) * 100 + '% ' + ((e.pageY - $(this).offset().top) / $(this).height()) * 100 + '%'
			});
		})
		// tiles set up
		.each(function() {
			$(this)
				// add a image container
				.append('<div class="product-img--main__image"></div>')
				// set up a background image for each tile based on data-image attribute
				.children('.product-img--main__image').css({
					'background-image': 'url(' + $(this).attr('data-image') + ')'
				});
		});
</script>

@endsection