<?php
session_start();
include('db.php');

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];

// ✅ Handle Update Quantities
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_cart'])) {
    foreach ($_POST['quantities'] as $cart_id => $qty) {
        $qty = max(1, intval($qty)); // ensure at least 1
        $stmt = $conn->prepare("UPDATE carts SET quantity = ? WHERE id = ? AND user_id = ?");
        $stmt->bind_param("iii", $qty, $cart_id, $user_id);
        $stmt->execute();
    }
    header("Location: cart.php"); // refresh cart after update
    exit;
}

// ✅ Handle Remove Item
if (isset($_GET['remove'])) {
    $cart_id = intval($_GET['remove']);
    $stmt = $conn->prepare("DELETE FROM carts WHERE id = ? AND user_id = ?");
    $stmt->bind_param("ii", $cart_id, $user_id);
    $stmt->execute();

    header("Location: cart.php"); // refresh after remove
    exit;
}

// ✅ Fetch Cart Items
$stmt = $conn->prepare("
    SELECT 
        c.id as cart_id, 
        p.product_name as name, 
        p.price, 
        p.product_image as image, 
        c.quantity
    FROM carts c
    JOIN products p ON c.product_id = p.id
    WHERE c.user_id = ?
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$total = 0;

include('includes/header.php');
?>

<section class="py-5">
  <div class="container">
    <h2 class="text-success mb-4">Shopping Cart</h2>

    <?php if ($result->num_rows > 0): ?>
    <form method="post" action="cart.php">
      <table class="table table-bordered align-middle">
        <thead>
          <tr class="table-success">
            <th>Product</th>
            <th>Image</th>
            <th>Quantity</th>
            <th>Price (₹)</th>
            <th>Total (₹)</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
        <?php while ($item = $result->fetch_assoc()):
          $price = floatval($item['price']);
          $quantity = intval($item['quantity']);
          $item_total = $price * $quantity;
          $total += $item_total;
        ?>
          <tr>
            <td><?= htmlspecialchars($item['name']) ?></td>
            <td><img src="<?= htmlspecialchars($item['image']) ?>" width="60" height="60" style="object-fit:cover;"></td>
            <td>
              <input type="number" name="quantities[<?= $item['cart_id'] ?>]" value="<?= $quantity ?>" class="form-control" min="1">
            </td>
            <td>₹<?= number_format($price, 2) ?></td>
            <td>₹<?= number_format($item_total, 2) ?></td>
            <td>
              <a href="cart.php?remove=<?= $item['cart_id'] ?>" class="btn btn-sm btn-danger">Remove</a>
            </td>
          </tr>
        <?php endwhile; ?>
          <tr>
            <td colspan="4" class="text-end"><strong>Grand Total:</strong></td>
            <td colspan="2"><strong>₹<?= number_format($total, 2) ?></strong></td>
          </tr>
        </tbody>
      </table>

      <div class="text-end mt-3">
        <button type="submit" name="update_cart" class="btn btn-warning">Update Quantities</button>
        <a href="checkout.php" class="btn btn-success ms-2">Proceed to Checkout</a>
      </div>
    </form>

    <?php else: ?>
      <div class="alert alert-info">🛒 Your cart is currently empty.</div>
    <?php endif; ?>
  </div>
</section>

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