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

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

/* ================= SAFE LOGIN CHECK ================= */
$user_id = 0;

if(isset($_SESSION['user_id'])){
    $user_id = $_SESSION['user_id'];
}
elseif(isset($_SESSION['distributor_id'])){
    $user_id = $_SESSION['distributor_id'];
}
elseif(isset($_SESSION['id'])){
    $user_id = $_SESSION['id'];
}

/* ================= CART QUERY ================= */
$query = "
SELECT 
    c.id,
    c.brand,
    c.quantity,
    c.variety_id,
    lc.label_name,
    c.batch_id,
    COALESCE(im.price, 0) AS price
FROM cart c
LEFT JOIN lifeline_configuration lc 
    ON c.variety_id = lc.id
LEFT JOIN inventory_management im 
    ON im.variety_id = c.variety_id
    AND im.brand = c.brand
WHERE c.user_id = '$user_id'
GROUP BY c.id
ORDER BY c.id DESC
";

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

<style>

.main-content-wrap{
    padding:20px;
}

/* HEADER */
.cart-header{
    display:flex;
    justify-content:space-between;
    align-items:center;
    padding:18px;
    background:#fff;
    border-radius:14px;
    box-shadow:0 6px 18px rgba(0,0,0,0.08);
    margin-bottom:20px;
}

.cart-header h3{
    margin:0;
    font-size:20px;
}

/* BUTTON WRAP */
.header-actions{
    display:flex;
    gap:10px;
}

/* CONTINUE BUTTON */
.continue-btn{
    padding:10px 14px;
    background:#fff;
    border:2px solid #ff7a18;
    color:#ff7a18;
    border-radius:10px;
    text-decoration:none;
    font-weight:600;
    font-size:13px;
    transition:0.2s;
}

.continue-btn:hover{
    background:#ff7a18;
    color:#fff;
}

/* CHECKOUT BUTTON */
.checkout-btn{
    padding:10px 14px;
    background:linear-gradient(90deg,#16a34a,#22c55e);
    color:#fff;
    border-radius:10px;
    text-decoration:none;
    font-weight:700;
    font-size:13px;
    transition:0.2s;
}

.checkout-btn:hover{
    transform:scale(1.05);
}

/* CART WRAP */
.cart-wrap{
    display:flex;
    flex-direction:column;
    gap:15px;
}

/* CARD */
.cart-card{
    display:flex;
    align-items:center;
    gap:15px;
    background:#fff;
    padding:16px;
    border-radius:14px;
    box-shadow:0 8px 20px rgba(0,0,0,0.06);
}

/* ICON */
.cart-img{
    width:65px;
    height:65px;
    border-radius:12px;
    background:linear-gradient(135deg,#ff7a18,#ffb347);
    display:flex;
    justify-content:center;
    align-items:center;
    color:#fff;
    font-size:20px;
}

/* INFO */
.cart-info{
    flex:1;
}

.cart-title{
    font-size:16px;
    font-weight:700;
}

.cart-sub{
    font-size:13px;
    color:#666;
}

/* PRICE */
.cart-price{
    margin-top:5px;
    font-weight:700;
    color:#16a34a;
}

/* QTY */
.qty-box{
    display:flex;
    align-items:center;
    gap:8px;
    margin-top:10px;
    background:#f3f4f6;
    padding:5px 10px;
    border-radius:999px;
    width:max-content;
}

.qty-btn{
    width:26px;
    height:26px;
    border:none;
    border-radius:50%;
    background:#fff;
    cursor:pointer;
    font-weight:700;
}

.qty-value{
    font-weight:700;
    min-width:20px;
    text-align:center;
}

/* REMOVE */
.remove-btn{
    padding:8px 12px;
    border:1px solid red;
    color:red;
    background:#fff;
    border-radius:10px;
    cursor:pointer;
    font-weight:600;
}

.remove-btn:hover{
    background:red;
    color:#fff;
}

/* EMPTY */
.empty{
    text-align:center;
    padding:60px;
    color:#777;
}

</style>

<div class="main-content-inner">
<div class="main-content-wrap">

<!-- HEADER -->
<div class="cart-header">
    <h3>🛒 My Cart</h3>

    <div class="header-actions">

        <a href="products.php" class="continue-btn">
            ← Continue Shopping
        </a>

        <?php if(mysqli_num_rows($result) > 0){ ?>
        <a href="checkout.php" class="checkout-btn">
            Proceed to Checkout →
        </a>
        <?php } ?>

    </div>
</div>

<!-- CART LIST -->
<div class="cart-wrap">

<?php if(mysqli_num_rows($result) > 0){ ?>

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

$total_price = ($row['price'] ?? 0) * ($row['quantity'] ?? 0);

?>

<div class="cart-card" id="cart-<?php echo $row['id']; ?>">

    <div class="cart-img">🌱</div>

    <div class="cart-info">
        <div class="cart-title">
            <?php echo htmlspecialchars($row['brand']); ?>
        </div>

        <div class="cart-sub">
            <?php echo htmlspecialchars($row['label_name']); ?>
        </div>

        <div class="cart-price">
            ₹ <?php echo number_format($total_price, 2); ?>
        </div>

        <div class="qty-box">
            <button class="qty-btn" onclick="updateQty(<?php echo $row['id']; ?>,'decrease')">-</button>

            <span id="qty-<?php echo $row['id']; ?>" class="qty-value">
                <?php echo $row['quantity']; ?>
            </span>

            <button class="qty-btn" onclick="updateQty(<?php echo $row['id']; ?>,'increase')">+</button>
        </div>
    </div>

    <div>
        <button class="remove-btn" onclick="removeItem(<?php echo $row['id']; ?>)">
            Remove
        </button>
    </div>

</div>

<?php } ?>

<?php } else { ?>

<div class="empty">
    🛒 Your cart is empty
</div>

<?php } ?>

</div>

</div>
</div>

<script>
function updateQty(id, action){
    fetch("cart_action.php", {
        method:"POST",
        headers:{ "Content-Type":"application/json" },
        body: JSON.stringify({ id, action })
    })
    .then(res => res.json())
    .then(data => {
        if(data.success){
            document.getElementById("qty-"+id).innerText = data.quantity;
        } else {
            alert(data.message);
        }
    });
}

function removeItem(id){
    fetch("cart_remove.php", {
        method:"POST",
        headers:{ "Content-Type":"application/json" },
        body: JSON.stringify({ id })
    })
    .then(res => res.json())
    .then(data => {
        if(data.success){
            document.getElementById("cart-"+id).remove();
        }
    });
}
</script>

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