<?php
session_start();
include 'includes/header.php';
include 'includes/sidebar.php';
include 'includes/connect.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

$user_id = $_SESSION['user_id'] ?? $_SESSION['distributor_id'] ?? $_SESSION['id'] ?? 0;

if(empty($user_id)){
    header("Location: login.php");
    exit;
}

$query = "
SELECT 
    c.id,
    c.brand,
    c.quantity,
    c.price,
    c.variety_id,
    c.batch_id,
    lc.label_name
FROM cart c
LEFT JOIN lifeline_configuration lc ON c.variety_id = lc.id
WHERE c.user_id = '$user_id'
";

$result = mysqli_query($conn, $query);

$grand_total = 0;
?>

<style>
body{
    font-family: "Segoe UI", Roboto, Arial, sans-serif;
    background:#f4f6f9;
    font-size:14px;
    color:#1f2937;
}

/* LAYOUT */
.checkout-wrap{
    padding:30px;
}

.checkout-header{
    display:flex;
    justify-content:space-between;
    align-items:center;
    background:#fff;
    padding:20px 25px;
    border-radius:14px;
    box-shadow:0 6px 20px rgba(0,0,0,0.06);
    margin-bottom:25px;
}

.checkout-header h2{
    font-size:24px;
    font-weight:700;
}

/* GRID */
.checkout-grid{
    display:grid;
    grid-template-columns: 2fr 1fr;
    gap:25px;
}

/* CARD */
.card{
    background:#fff;
    border-radius:16px;
    padding:22px;
    box-shadow:0 6px 18px rgba(0,0,0,0.05);
    margin-bottom:20px;
}

.card h3{
    font-size:18px;
    font-weight:700;
    margin-bottom:15px;
}

/* INPUTS */
input, textarea, select{
    width:100%;
    padding:12px 14px;
    border-radius:10px;
    border:1px solid #e5e7eb;
    margin-top:6px;
    margin-bottom:14px;
    font-size:14px;
    transition:0.2s;
}

input:focus, textarea:focus, select:focus{
    outline:none;
    border-color:#ff7a18;
    box-shadow:0 0 0 3px rgba(255,122,24,0.12);
}

/* ITEM */
.item{
    display:flex;
    justify-content:space-between;
    align-items:flex-start;
    padding:14px 0;
    border-bottom:1px dashed #e5e7eb;
}

.item div:first-child{
    font-weight:600;
    font-size:15px;
}

.item small{
    font-size:12px;
    color:#6b7280;
}

/* RIGHT BOX */
.price-box{
    display:flex;
    flex-direction:column;
    align-items:flex-end;
    gap:10px;
}

/* FIELD */
.field{
    display:flex;
    flex-direction:column;
    align-items:flex-end;
}

.field label{
    font-size:12px;
    font-weight:600;
    color:#6b7280;
}

/* INPUT SMALL */
.tray-input,
.price-input{
    width:90px;
    padding:7px;
    border-radius:8px;
    border:1px solid #ddd;
    text-align:right;
    font-weight:600;
}

.tray-input:focus,
.price-input:focus{
    border-color:#ff7a18;
}

/* TOTAL */
.line-total{
    font-size:14px;
    font-weight:700;
    color:#16a34a;
}

/* TOTAL BOX */
.total-box{
    display:flex;
    justify-content:space-between;
    font-size:18px;
    font-weight:700;
    margin-top:12px;
}

/* PAYMENT SUMMARY */
.pay-summary{
    background:#f9fafb;
    padding:16px;
    border-radius:12px;
    margin-top:15px;
}

.pay-summary h4{
    font-size:15px;
    font-weight:700;
    margin-bottom:10px;
}

.pay-row{
    display:flex;
    justify-content:space-between;
    align-items:center;
    margin:10px 0;
    font-size:14px;
}

.pay-row input,
.pay-row select{
    width:120px;
    padding:6px;
    text-align:right;
}

/* NET */
.net{
    font-size:20px;
    font-weight:800;
    color:#16a34a;
}

/* BUTTON */
.place-btn{
    width:100%;
    margin-top:18px;
    padding:14px;
    border:none;
    border-radius:12px;
    background:linear-gradient(90deg,#ff7a18,#ffb347);
    color:#fff;
    font-size:15px;
    font-weight:700;
    cursor:pointer;
    transition:0.2s;
}

.place-btn:hover{
    transform:translateY(-1px);
    box-shadow:0 6px 15px rgba(255,122,24,0.3);
}

/* STICKY RIGHT */
.checkout-grid > div:last-child{
    position:sticky;
    top:20px;
}

/* MOBILE */
@media(max-width:1000px){
    .checkout-grid{
        grid-template-columns:1fr;
    }
}
</style>

<div class="checkout-wrap">

<div class="checkout-header">
    <h2>🧾 Checkout</h2>
</div>

<div class="checkout-grid">

<!-- LEFT -->
<div>
    <div class="card">
        <h3>🚚 Shipping Details</h3>

        <input id="name" placeholder="Full Name">
        <input id="mobile" placeholder="Mobile Number">
        <textarea id="address" placeholder="Address"></textarea>
        <input id="city" placeholder="City">

        <select id="village">
            <option>Select Village</option>
            <option>Rampur</option>
            <option>Rajpura</option>
            <option>Shivnagar</option>
        </select>

        <input id="pincode" placeholder="Pincode">
    </div>
</div>

<!-- RIGHT -->
<div>

<div class="card">

<h3>🛒 Order Summary</h3>

<?php while($row = mysqli_fetch_assoc($result)) {

    $price = floatval($row['price']);
    $qty = intval($row['quantity']);
    $total = $price * $qty;
    $grand_total += $total;
?>

<div class="item">

<div>
    <div><?php echo $row['brand']; ?></div>
    <small><?php echo $row['label_name']; ?></small>
    <small><?php echo $row['batch_id']; ?></small>
</div>

<div class="price-box">

<div class="field">
<label>No of Trays</label>
<input type="number" class="tray-input" value="<?php echo $qty; ?>" data-id="<?php echo $row['id']; ?>" oninput="updateTotal()">
</div>

<div class="field">
<label>Price</label>
<input type="number" class="price-input" value="<?php echo $price; ?>" data-id="<?php echo $row['id']; ?>" oninput="updateTotal()">
</div>

<span class="line-total" id="total-<?php echo $row['id']; ?>">
₹ <?php echo number_format($total,2); ?>
</span>

</div>
</div>

<?php } ?>

<!-- PAYMENT SUMMARY -->
<div class="pay-summary">

<label>
<input type="checkbox" id="payCarry" onchange="updateTotal()"> Pay & Carry (Full Payment + Delivery)
</label>

<div class="pay-row">
<span>Gross Amount</span>
<span id="gross">₹ <?php echo number_format($grand_total,2); ?></span>
</div>

<div class="pay-row">
<span>Discount</span>
<input type="number" id="discount" value="0" oninput="updateTotal()">
</div>

<div class="pay-row net">
<span>Net Amount</span>
<span id="net">₹ <?php echo number_format($grand_total,2); ?></span>
</div>

</div>

<!-- NEW PAYMENT DETAILS SECTION -->
<div class="pay-summary">

<h4 style="margin-bottom:10px;">💰 Payment Details</h4>

<div class="pay-row">
<span>Payment Amount</span>
<input type="number" id="payAmount" value="0">
</div>

<div class="pay-row">
<span>Payment Type</span>
<select id="payType">
<option>Advance</option>
<option>Complete</option>
<option>Part Payment</option>
</select>
</div>

<div class="pay-row">
<span>Payment Mode</span>
<select id="payMode">
<option>UPI</option>
<option>Cash</option>
<option>Bank Transfer</option>
</select>
</div>

<div class="pay-row">
<span>Total Trays</span>
<span id="totalTrays">0</span>
</div>

<div class="pay-row">
<span>Delivered Trays</span>
<input type="number" id="deliveredTrays" value="0">
</div>

</div>

<button class="place-btn" onclick="placeOrder()">Place Order</button>

</div>
</div>

</div>
</div>

<script>

function updateTotal(){

    let grand = 0;
    let totalTrays = 0;

    document.querySelectorAll(".item").forEach(item => {

        let qty = parseFloat(item.querySelector(".tray-input").value) || 0;
        let price = parseFloat(item.querySelector(".price-input").value) || 0;

        let total = qty * price;

        let id = item.querySelector(".price-input").dataset.id;

        document.getElementById("total-"+id).innerText = "₹ " + total.toFixed(2);

        grand += total;
        totalTrays += qty;
    });

    // Gross
    document.getElementById("gross").innerText = "₹ " + grand.toFixed(2);

    // Discount
    let discount = parseFloat(document.getElementById("discount").value) || 0;

    let net = grand - discount;
    if(net < 0) net = 0;

    document.getElementById("net").innerText = "₹ " + net.toFixed(2);

    // Total Trays
    document.getElementById("totalTrays").innerText = totalTrays;
}


/* ================= PLACE ORDER ================= */
function placeOrder(){

    let items = [];

    document.querySelectorAll(".item").forEach(item => {

        let qty = item.querySelector(".tray-input").value;
        let price = item.querySelector(".price-input").value;
        let id = item.querySelector(".price-input").dataset.id;

        if(qty > 0){
            items.push({id,qty,price});
        }
    });

    let data = {
        name: document.getElementById("name").value,
        mobile: document.getElementById("mobile").value,
        address: document.getElementById("address").value,
        city: document.getElementById("city").value,
        pincode: document.getElementById("pincode").value,

        payment: document.getElementById("payCarry").checked ? "Pay & Carry" : "Normal",
        discount: document.getElementById("discount").value,

        // NEW FIELDS
        payment_amount: document.getElementById("payAmount").value,
        payment_type: document.getElementById("payType").value,
        payment_mode: document.getElementById("payMode").value,
        delivered_trays: document.getElementById("deliveredTrays").value,

        items: items
    };

    fetch("place_order.php",{
        method:"POST",
        headers:{ "Content-Type":"application/json" },
        body: JSON.stringify(data)
    })
    .then(res=>res.json())
    .then(res=>{
        alert(res.message);
        if(res.success){
            window.location.href="order_success.php";
        }
    });
}

window.onload = updateTotal;

</script>

<?php include 'includes/footer.php'; ?>