<?php
// landing-checkout.php
include "../../config.php"; // update path as needed
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Direct Buy Checkout</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="path/to/fontawesome.css">
<style>
.checkout-area { padding: 20px; font-family: Arial; }
.empty-cart { text-align: center; margin: 30px 0; display: none; }
.order-summary-container { border: 1px solid #ddd; padding: 10px; border-radius: 5px; }
.single-shop-list { display: flex; justify-content: space-between; margin-bottom: 10px; }
.checkout-content { display: flex; gap: 20px; }
.billing-details, .order-summary { flex:1; }
</style>
</head>
<body>

<div class="checkout-area">
    <div class="empty-cart">
        <i class="fa-solid fa-cart-shopping" style="font-size:40px;color:var(--color-primary);"></i>
        <h3>Your Cart is Empty.</h3>
        <a href="products.php" class="btn-primary">Shop Now</a>
    </div>

    <div class="checkout-content">
        <div class="billing-details">
            <h3>Shipping Details</h3>
            <form id="shippingForm" action="javascript:;">
                <label>First Name*</label>
                <input type="text" id="fname" required>
                <label>Last Name</label>
                <input type="text" id="lname">
				<label>Email*</label>
                <input type="email" id="email" required>
                <label>Mobile Number*</label>
                <input type="text" id="mobilenumber" required>
                <label>Door No*</label>
                <input type="text" id="dno" required>
                <label>Street*</label>
                <input type="text" id="street" required>
                <label>City*</label>
                <input type="text" id="city" required>
                <label>State*</label>
                <select id="state" required>
                    <option value="">Select State</option>
                </select>
                <label>Pincode*</label>
                <input type="text" id="pincode" required>
            </form>
        </div>

        <div class="order-summary">
            <h3>Your Order</h3>
            <div class="order-summary-container"></div>

            <div>
                <input type="radio" name="selector" value="cod" checked> Cash On Delivery
                <input type="radio" name="selector" value="OnlinePayment"> Online Payment
            </div>

            <div>
                <input type="checkbox" id="terms"> I agree to terms
            </div>

            <button class="order-place">Place Order</button>
        </div>
    </div>
</div>

<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
let shippingCharge = 0;
let selectedState = "";

// ---- Discount / Coupon / Membership from localStorage ----
let discountAmount = parseFloat(localStorage.getItem("discountAmount")) || 0;
let appliedCoupon = localStorage.getItem("appliedCoupon") || "";
let appliedMembership = localStorage.getItem("appliedMembership") || "";

// Landing product from localStorage
const landingProduct = JSON.parse(localStorage.getItem("landingProduct") || "{}");
if (!landingProduct.id) {
    document.querySelector(".empty-cart").style.display = "block";
    document.querySelector(".checkout-content").style.display = "none";
}

// Render order summary
function renderOrderSummary() {
    const summaryContainer = document.querySelector(".order-summary-container");
    if (!landingProduct.id) return summaryContainer.innerHTML = "";

    const subtotal = parseFloat(landingProduct.price) * parseInt(landingProduct.qty);
    const totalBeforeDiscount = subtotal + shippingCharge;
    const finalTotal = totalBeforeDiscount - discountAmount;

    summaryContainer.innerHTML = `
        <div class="single-shop-list">
            <span>${landingProduct.name} × ${landingProduct.qty}</span>
            <span>₹${subtotal.toFixed(2)}</span>
        </div>
        <div class="single-shop-list">
            <span>Shipping</span>
            <span>₹${shippingCharge.toFixed(2)}</span>
        </div>
        ${discountAmount > 0 ? `
        <div class="single-shop-list">
            <span>Discount ${appliedCoupon ? `(Coupon: ${appliedCoupon})` : appliedMembership ? `(Membership)` : ""}</span>
            <span>-₹${discountAmount.toFixed(2)}</span>
        </div>` : ""}
        <div class="single-shop-list">
            <span><b>Total</b></span>
            <span><b>₹${finalTotal.toFixed(2)}</b></span>
        </div>
    `;
}

// Populate states
const states = ["Maharashtra","Karnataka","Delhi","Tamil Nadu","Gujarat","Other"];
const stateField = document.getElementById("state");
states.forEach(st => {
    const opt = document.createElement("option");
    opt.value = st;
    opt.text = st;
    stateField.add(opt);
});

// Shipping logic
stateField.addEventListener("change", () => {
    selectedState = stateField.value;
    shippingCharge = selectedState === "Maharashtra" ? 50 : (selectedState ? 100 : 0);
    renderOrderSummary();
});

// Place order
document.querySelector(".order-place").addEventListener("click", async function() {
    if (!landingProduct.id) return alert("Product not found.");

    const fname = document.getElementById("fname").value.trim();
    const lname = document.getElementById("lname").value.trim();
    const email = document.getElementById("email").value.trim();
    const mobilenumber = document.getElementById("mobilenumber").value.trim();
    const dno = 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();

    if (!fname || !email || !mobilenumber || !dno || !street || !city || !state || !pincode)
        return alert("Please fill all required fields.");
    if (!document.getElementById("terms").checked) return alert("Please agree to terms.");

    const subtotal = parseFloat(landingProduct.price) * parseInt(landingProduct.qty);
    const totalBeforeDiscount = subtotal + shippingCharge;
    const finalTotal = totalBeforeDiscount - discountAmount;
    const paymentSelected = document.querySelector('input[name="selector"]:checked').value;

    try {
        // --- Step 1: Check / Add Guest Customer ---
        let guestPayload = {
			first_name: fname,
			last_name: lname,
			email: email,
			mobilenumber: mobilenumber
		};
        const custRes = await fetch("<?php echo API_URL; ?>?gofor=landingcustomersadd", {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify(guestPayload)
        });
        const custData = await custRes.json();
        const customerId = custData.customer_id;

        // --- Step 2: Check / Add Address ---
        let addressPayload = {
            customer_id: customerId,
            doorno: dno,
            street: street,
            location: "",
            pincode: pincode,
            city: city,
            state: state,
            primary_use: 1,
            recently_use: 1
        };
        const addrRes = await fetch("<?php echo API_URL; ?>?gofor=landingaddaddress", {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify(addressPayload)
        });
        const addrData = await addrRes.json();
        const addressId = addrData.address_id;

        // --- Step 3: Create Order ---
        const orderPayload = {
            gofor: "landingcreateorders",
            customer_id: customerId,
            product_details: [{
                product_id: landingProduct.id,
                product_name: landingProduct.name,
				prod_attri_id: landingProduct.unit,
                amount: parseFloat(landingProduct.price),
                quantity: parseInt(landingProduct.qty)
            }],
            fullquantity: parseInt(landingProduct.qty),
            invoice_amount: subtotal,
            delivery_charge: shippingCharge,
            discount_amount: discountAmount,
            total_amount: finalTotal,
            payment_mode: paymentSelected,
            address_id: addressId,
            applied_coupon: appliedCoupon,
            applied_membership: appliedMembership
        };

        const orderRes = await fetch("<?php echo API_URL; ?>?gofor=landingcreateorders", {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify(orderPayload)
        });
        const orderData = await orderRes.json();
        if (!orderData.order_id) return alert("Order creation failed.");

        const orderId = orderData.order_id;

        // --- Step 4: Handle Online Payment ---
        if (paymentSelected === "OnlinePayment") {
            const razorRes = await fetch("<?php echo API_URL; ?>?gofor=razorpay_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) return alert("Unable to initiate Razorpay.");

            const options = {
                key: razorData.razorpay_key,
                amount: finalTotal * 100,
                currency: "INR",
                name: "Drs Siddha",
                order_id: razorData.order_id,
                handler: async function(response) {
                    await fetch("<?php echo API_URL; ?>?gofor=razorpay_handler", {
                        method: "POST",
                        headers: {"Content-Type": "application/json"},
                        body: JSON.stringify(response)
                    });
                    localStorage.removeItem("landingProduct");
                    localStorage.removeItem("discountAmount");
                    localStorage.removeItem("appliedCoupon");
                    localStorage.removeItem("appliedMembership");
                    window.location.href = `thank-you.php?order_id=${orderId}`;
                }
            };
            const rzp = new Razorpay(options);
            rzp.open();
            return;
        }

        // COD
        localStorage.removeItem("landingProduct");
        localStorage.removeItem("discountAmount");
        localStorage.removeItem("appliedCoupon");
        localStorage.removeItem("appliedMembership");
        window.location.href = `thank-you.php?order_id=${orderId}`;

    } catch (err) {
        console.error(err);
        alert("Error placing order.");
    }
});

// Initialize
document.addEventListener("DOMContentLoaded", function() {
    renderOrderSummary();
});
</script>

</body>
</html>
