<?php
// landing-checkout.php
include "../../config.php"; // update path as needed
?>
<!DOCTYPE html>
<html class="no-js" lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Checkout | Dr Siddha diabetes combo</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="shortcut icon" type="image/x-icon" href="assets/img/favicon.png">
    <!-- CSS here -->
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/animate.min.css">
    <link rel="stylesheet" href="assets/css/magnific-popup.css">
    <link rel="stylesheet" href="assets/css/fontawesome-all.min.css">
    <link rel="stylesheet" href="assets/css/mCustomScrollbar.min.css">
    <link rel="stylesheet" href="assets/css/jquery-ui.css">
    <link rel="stylesheet" href="assets/css/flaticon.css">
    <link rel="stylesheet" href="assets/css/slick.css">
    <link rel="stylesheet" href="assets/css/default.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="assets/css/responsive.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css"
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style>
        /* Responsive tweaks for checkout page */
        @media (max-width: 991.98px) {
            .checkout-area {
                padding-top: 60px !important;
                padding-bottom: 60px !important;
            }
            .checkout-form .col-lg-7,
            .checkout-form .col-lg-5 {
                flex: 0 0 100%;
                max-width: 100%;
            }
            .cart-summary {
                margin-top: 30px;
            }
        }
        @media (max-width: 767.98px) {
            .checkout-area {
                padding-top: 30px !important;
                padding-bottom: 30px !important;
            }
            .section-title .title {
                font-size: 24px !important;
            }
            .cart-summary,
            .checkout-billing {
                padding: 16px !important;
            }
            .cart-summary h4,
            .checkout-billing h4 {
                font-size: 18px !important;
            }
            .btn.special-btn, .btn.solid-btn {
                font-size: 15px !important;
                padding: 8px 12px !important;
            }
        }
        @media (max-width: 575.98px) {
            .section-title .title {
                font-size: 18px !important;
            }
            .cart-summary,
            .checkout-billing {
                padding: 8px !important;
            }
            .cart-summary h4,
            .checkout-billing h4 {
                font-size: 15px !important;
            }
            .form-label {
                font-size: 13px !important;
            }
            .form-control,
            textarea.form-control {
                font-size: 13px !important;
                padding: 6px 8px !important;
            }
            .btn.special-btn, .btn.solid-btn {
                font-size: 13px !important;
                padding: 7px 10px !important;
            }
            .list-group-item {
                font-size: 13px !important;
            }
        }
    </style>
	<style>
body { background: #f9f9f9; }
.special-btn {
    background-color: #2a8f54;
    color: #fff;
    border: none;
    padding: 12px;
    font-weight: 600;
    border-radius: 6px;
    transition: all 0.3s;
}
.special-btn:hover {
    background-color: #246e45;
    color: #fff;
}
.solid-btn {
    background-color: #fff;
    border: 1px solid #ccc;
    padding: 10px 16px;
    border-radius: 6px;
    transition: 0.3s;
}
.solid-btn:hover {
    background: #eee;
}
.empty-cart {
    display: none;
    text-align: center;
    padding: 80px 0;
}
</style>
</head>

<body>
    <?php include "header.php";?>

    <!-- main-area -->
    <main>
		<section class="checkout-area pt-120 pb-120" style="background:#f9f9f9;">
		  <div class="container">
			<div class="row justify-content-center">
			  <div class="col-xl-10">
				<div class="section-title special-title mb-40 text-center">
				  <h2 class="title">Buy Now</h2>
				  <p>Enter your details to complete your purchase</p>
				</div>

				<div class="checkout-content row g-4">
				  <!-- Billing Details -->
				  <div class="col-lg-7">
					<div class="checkout-billing p-4 rounded" style="background:#fff;box-shadow:0 2px 10px #eee;">
					  <h4 class="mb-3">Shipping Details</h4>
					  <form id="shippingForm" action="javascript:;">
						<div class="row g-3">
						  <div class="col-md-6">
							<label class="form-label">First Name*</label>
							<input type="text" class="form-control" id="fname" required>
						  </div>
						  <div class="col-md-6">
							<label class="form-label">Last Name</label>
							<input type="text" class="form-control" id="lname">
						  </div>
						  <div class="col-md-6">
							<label class="form-label">Email*</label>
							<input type="email" class="form-control" id="email" required>
						  </div>
						  <div class="col-md-6">
							<label class="form-label">Mobile Number*</label>
							<input type="text" class="form-control" id="mobilenumber" required>
						  </div>
						  <div class="col-md-6">
							<label class="form-label">Door No*</label>
							<input type="text" class="form-control" id="dno" required>
						  </div>
						  <div class="col-md-6">
							<label class="form-label">Street*</label>
							<input type="text" class="form-control" id="street" required>
						  </div>
						  <div class="col-md-6">
							<label class="form-label">City*</label>
							<input type="text" class="form-control" id="city" required>
						  </div>
						  <div class="col-md-6">
							<label class="form-label">State*</label>
							<select class="form-select" id="state" required>
							  <option value="">Select State</option>
							</select>
						  </div>
						  <div class="col-md-6">
							<label class="form-label">Pincode*</label>
							<input type="text" class="form-control" id="pincode" required>
						  </div>
						</div>
					  </form>
					</div>
				  </div>

				  <!-- Order Summary -->
				  <div class="col-lg-5">
					<div class="cart-summary p-4 rounded mb-4" style="background:#fff;box-shadow:0 2px 10px #eee;">
					  <h4 class="mb-3">Order Summary</h4>
					  <ul id="orderItems" class="list-group mb-3"></ul>

					  <div class="mb-3">
						<label class="form-label mb-2">Payment Method</label>
						<div class="form-check">
						  <input class="form-check-input" type="radio" name="payment" id="cod" value="COD" checked>
						  <label class="form-check-label" for="cod">Cash on Delivery</label>
						</div>
						<div class="form-check">
						  <input class="form-check-input" type="radio" name="payment" id="online" value="OnlinePayment">
						  <label class="form-check-label" for="online">Online Payment</label>
						</div>
					  </div>

					  <button class="btn special-btn w-100" id="placeOrderBtn">Place Order <i class="fa-solid fa-check"></i></button>
					</div>
				  </div>
				</div>

			  </div>
			</div>
		  </div>
		</section>
		</main>
    <!-- main-area-end -->

    <!-- footer-area (reuse from index.html) -->
    <?php include "footer.php";?>
    <!-- footer-area-end -->

    <!-- JS here -->
    <script src="assets/js/vendor/jquery-3.6.0.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="assets/js/isotope.pkgd.min.js"></script>
    <script src="assets/js/imagesloaded.pkgd.min.js"></script>
    <script src="assets/js/jquery.magnific-popup.min.js"></script>
    <script src="assets/js/jquery.easypiechart.min.js"></script>
    <script src="assets/js/jquery.mCustomScrollbar.min.js"></script>
    <script src="assets/js/jquery.inview.min.js"></script>
    <script src="assets/js/jquery.parallaxScroll.js"></script>
    <script src="assets/js/jquery.easing.js"></script>
    <script src="assets/js/jquery-ui.min.js"></script>
    <script src="assets/js/validator.js"></script>
    <script src="assets/js/nav-tool.js"></script>
    <script src="assets/js/slick.min.js"></script>
    <script src="assets/js/ajax-form.js"></script>
    <script src="assets/js/wow.min.js"></script>
    <script src="assets/js/main.js"></script>
	<!-- ✅ Razorpay SDK (must be before your checkout script) -->
	<script src="https://checkout.razorpay.com/v1/checkout.js"></script>

	<script>
	const API_URL = "<?php echo API_URL; ?>";

	// Read landingProduct from localStorage
	let landingProduct = JSON.parse(localStorage.getItem("landingProduct") || "{}");
	if (!landingProduct.id) {
	  alert("Product not found");
	}

	let qty = landingProduct.qty || 1;

	// ✅ Populate State Dropdown
	const stateSelect = document.getElementById("state");
	const states = [
	  "Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chhattisgarh",
	  "Goa", "Gujarat", "Haryana", "Himachal Pradesh", "Jharkhand", "Karnataka",
	  "Kerala", "Madhya Pradesh", "Maharashtra", "Manipur", "Meghalaya", "Mizoram",
	  "Nagaland", "Odisha", "Punjab", "Rajasthan", "Sikkim", "Tamil Nadu", "Telangana",
	  "Tripura", "Uttar Pradesh", "Uttarakhand", "West Bengal", "Delhi", "Puducherry",
	  "Other"
	];

	if (stateSelect && stateSelect.options.length <= 1) {
	  states.forEach(st => {
		const o = document.createElement("option");
		o.value = st;
		o.text = st;
		stateSelect.add(o);
	  });
	}

	// ✅ Shipping logic
	function calculateShipping(state) {
	  return state === "Tamil Nadu" ? 50 : 100;
	}

	// ✅ Render order summary
	function renderSummary() {
	  if (!landingProduct.id) return;

	  const price = parseFloat(landingProduct.price) || 0;
	  const subtotal = price * qty;
	  const stateVal = stateSelect ? stateSelect.value : "";
	  const shipping = calculateShipping(stateVal);
	  const total = subtotal + shipping;

	  const itemsEl = document.getElementById("orderItems");
	  if (!itemsEl) return;

	  itemsEl.innerHTML = `
		<li class="list-group-item d-flex justify-content-between align-items-center border-0">
		  <div>
			<strong>${landingProduct.name}</strong><br>
			<small>₹${price.toFixed(2)} × </small>
			<button type="button" id="minusBtn" class="btn btn-sm btn-outline-secondary">-</button>
			<span id="qty">${qty}</span>
			<button type="button" id="plusBtn" class="btn btn-sm btn-outline-secondary">+</button>
		  </div>
		  <span>₹${subtotal.toFixed(2)}</span>
		</li>
		<li class="list-group-item d-flex justify-content-between border-0">
		  <span>Shipping</span><span>₹${shipping.toFixed(2)}</span>
		</li>
		<li class="list-group-item d-flex justify-content-between border-0">
		  <strong>Total</strong><strong id="finalTotal">₹${total.toFixed(2)}</strong>
		</li>
	  `;

	  // Quantity buttons
	  const plusBtn = document.getElementById("plusBtn");
	  const minusBtn = document.getElementById("minusBtn");
	  if (plusBtn) plusBtn.onclick = () => { qty++; renderSummary(); };
	  if (minusBtn) minusBtn.onclick = () => { if (qty > 1) { qty--; renderSummary(); } };
	}

	if (stateSelect) stateSelect.addEventListener("change", renderSummary);
	renderSummary();


	// ✅ Place Order button click
	document.getElementById("placeOrderBtn").addEventListener("click", async () => {
	  try {
		const fname = document.getElementById("fname").value.trim();
		const email = document.getElementById("email").value.trim();
		const mobile = document.getElementById("mobilenumber").value.trim();
		const door = document.getElementById("dno").value.trim();
		const street = document.getElementById("street").value.trim();
		const city = document.getElementById("city").value.trim();
		const state = document.getElementById("state").value.trim();
		const pincode = document.getElementById("pincode").value.trim();

		// ✅ Validation alerts
		if (!fname) return alert("Please enter your first name.");
		if (!email) return alert("Please enter your email.");
		if (!mobile || mobile.length < 10) return alert("Please enter a valid mobile number.");
		if (!door) return alert("Please enter your door number.");
		if (!street) return alert("Please enter your street.");
		if (!city) return alert("Please enter your city.");
		if (!state) return alert("Please select your state.");
		if (!pincode || pincode.length < 6) return alert("Please enter a valid pincode.");

		const paymentRadio = document.querySelector('input[name="payment"]:checked');
		if (!paymentRadio) return alert("Please select a payment method.");
		const paymentSelected = paymentRadio.value;

		const customerData = {
		  first_name: fname,
		  last_name: (document.getElementById("lname")?.value || "").trim(),
		  email,
		  mobilenumber: mobile
		};

		const addressData = { doorno: door, street, city, state, pincode };

		const shipping = calculateShipping(state);
		const price = parseFloat(landingProduct.price) || 0;
		const subtotal = price * qty;
		const total = subtotal + shipping;

		// --- Create customer ---
		const custRes = await fetch(`${API_URL}?gofor=landingcustomersadd`, {
		  method: "POST",
		  headers: { "Content-Type": "application/json" },
		  body: JSON.stringify(customerData)
		});
		const cust = await custRes.json();
		const customerId = cust.customer_id;
		if (!customerId) throw new Error("Customer ID missing");

		// --- Create address ---
		const addrRes = await fetch(`${API_URL}?gofor=landingaddaddress`, {
		  method: "POST",
		  headers: { "Content-Type": "application/json" },
		  body: JSON.stringify({ ...addressData, customer_id: customerId })
		});
		const addr = await addrRes.json();
		const addressId = addr.address_id || "";

		// --- Create order ---
		const orderPayload = {
		  customer_id: customerId,
		  product_details: [{
			product_id: landingProduct.id,
			product_name: landingProduct.name,
			prod_attri_id: landingProduct.unit || "",
			amount: parseFloat(landingProduct.price),
			quantity: qty
		  }],
		  fullquantity: qty,
		  invoice_amount: subtotal,
		  delivery_charge: shipping,
		  discount_amount: 0,
		  total_amount: total,
		  payment_mode: paymentSelected,
		  address_id: addressId
		};

		const orderRes = await fetch(`${API_URL}?gofor=landingcreateorders`, {
		  method: "POST",
		  headers: { "Content-Type": "application/json" },
		  body: JSON.stringify(orderPayload)
		});
		const order = await orderRes.json();
		const orderId = order?.order_id || order?.orderid || order?.id;
		if (!orderId) throw new Error("Order ID missing");

		// --- Razorpay (Online Payment) ---
		if (paymentSelected === "OnlinePayment") {
		  const razorRes = await fetch(`${API_URL}?gofor=razorpay_test_handler`, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({ customer_id: customerId, order_id: orderId })
		  });

		  const razorData = await razorRes.json();
		  if (!razorData?.order_id || !razorData?.razorpay_key)
			throw new Error("Razorpay order creation failed");

		  const options = {
			key: razorData.razorpay_key,
			amount: Math.round(total * 100),
			currency: "INR",
			name: "Drs Siddha",
			image: "https://drsiddha.com/assets/images/logo.png",
			description: `Order #${orderId}`,
			order_id: razorData.order_id,
			prefill: {
			  name: fname,
			  email: email,
			  contact: mobile
			},
			handler: async function (response) {
			  try {
				await fetch(`${API_URL}?gofor=razorpay_test_handler`, {
				  method: "POST",
				  headers: { "Content-Type": "application/json" },
				  body: JSON.stringify({
					razorpay_payment_id: response.razorpay_payment_id,
					razorpay_order_id: response.razorpay_order_id,
					razorpay_signature: response.razorpay_signature,
					order_id: orderId
				  })
				});
			  } catch (err) {
				console.error("Error sending payment confirmation", err);
			  }
			  localStorage.clear();
			  window.location.href = `thank-you.php?order_id=${orderId}`;
			}
		  };

		  const rzp = new Razorpay(options);
		  rzp.open();
		  return;
		}

		// --- COD flow ---
		localStorage.clear();
		window.location.href = `thank-you.php?order_id=${orderId}`;

	  } catch (err) {
		console.error("DEBUG ERROR TRACE:", err);
		alert("Error placing order. Please try again.");
	  }
	});
	</script>


</body>
</html>
