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

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

$user_id = $_SESSION['user_id'];

// Handle remove item
if(isset($_GET['remove_id'])){
    $remove_id = $_GET['remove_id'];
    foreach($_SESSION['cart'] as $key => $item){
        if($item['id'] == $remove_id){
            unset($_SESSION['cart'][$key]);
            $_SESSION['cart'] = array_values($_SESSION['cart']); // reindex
            break;
        }
    }
    header("Location: checkout.php");
    exit;
}

// Handle update quantity
if(isset($_POST['update_cart'])){
    foreach($_POST['quantities'] as $id => $qty){
        foreach($_SESSION['cart'] as &$item){
            if($item['id'] == $id){
                $item['quantity'] = max(1, intval($qty));
                break;
            }
        }
        unset($item);
    }
    header("Location: checkout.php");
    exit;
}

// Handle place order
if(isset($_POST['place_order'])){
    $name    = $_POST['name'];
    $phone   = $_POST['phone'];
    $address = $_POST['address'];
    $city    = $_POST['city'];
    $pincode = $_POST['pincode'];
    $payment = $_POST['payment_method']; // COD

    $cart_items = $_SESSION['cart'] ?? [];
    if(!empty($cart_items)){
        // calculate total
        $total = 0;
        foreach($cart_items as $item){
            $total += $item['price'] * $item['quantity'];
        }

        // insert into orders
        $stmt = $conn->prepare("INSERT INTO orders 
            (user_id, delivery_name, delivery_phone, delivery_address, delivery_city, delivery_pincode, total_amount, payment_method) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("isssssds", $user_id, $name, $phone, $address, $city, $pincode, $total, $payment);
        $stmt->execute();

        $order_id = $stmt->insert_id; // get new order id

        // insert into order_items
        foreach($cart_items as $item){
            $product_id = $item['id'];
            $quantity   = $item['quantity'];
            $price      = $item['price'];
            $subtotal   = $price * $quantity;

            $stmt2 = $conn->prepare("INSERT INTO order_items 
                (order_id, product_id, quantity, price, subtotal) 
                VALUES (?, ?, ?, ?, ?)");
            $stmt2->bind_param("iiidd", $order_id, $product_id, $quantity, $price, $subtotal);
            $stmt2->execute();
        }

        unset($_SESSION['cart']); // clear cart
        $_SESSION['order_confirmed'] = true;
        header("Location: checkout.php");
        exit;
    }
}

// Cart items and total
$cart_items = $_SESSION['cart'] ?? [];
$total = 0;
foreach($cart_items as $item){
    $total += $item['price'] * $item['quantity'];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Checkout - Art Shop</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body { padding-top: 70px; background-color: #ffe6f0; }
.cart-img { width: 80px; height: 80px; object-fit: cover; }
</style>
</head>
<body>

<?php
// Show order confirmed popup
if(isset($_SESSION['order_confirmed']) && $_SESSION['order_confirmed']){
    echo "<script>alert('✅ Order Confirmed with Cash on Delivery!');</script>";
    unset($_SESSION['order_confirmed']);
}
?>

<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
  <div class="container">
    <a class="navbar-brand" href="dashboard.php">🎨 Art Shop</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav ms-auto">
        <li class="nav-item"><a class="nav-link" href="dashboard.php">Home</a></li>
        <li class="nav-item"><a class="nav-link" href="logout.php">Logout</a></li>
      </ul>
    </div>
  </div>
</nav>

<div class="container py-5">
<h2 class="mb-4 text-center">🛒 Your Cart</h2>

<?php if(count($cart_items) > 0): ?>
<form method="POST">
<table class="table table-bordered">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach($cart_items as $item): ?>
<tr>
<td><img src="data:image/jpeg;base64,<?= $item['image'] ?>" class="cart-img"></td>
<td><?= htmlspecialchars($item['name']) ?></td>
<td>₹<?= number_format($item['price'],2) ?></td>
<td>
<input type="number" name="quantities[<?= $item['id'] ?>]" value="<?= $item['quantity'] ?>" min="1" class="form-control" style="width:70px;">
</td>
<td>₹<?= number_format($item['price'] * $item['quantity'],2) ?></td>
<td>
<a href="checkout.php?remove_id=<?= $item['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Remove this item?')">Remove</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<div class="d-flex justify-content-between align-items-center">
<h4>Total: ₹<?= number_format($total,2) ?></h4>
<div>
<button type="submit" name="update_cart" class="btn btn-warning">Update Cart</button>
</div>
</div>
</form>

<!-- Delivery Details Form -->
<hr>
<h3>📦 Delivery Details</h3>
<form method="POST" class="mt-3">
  <div class="mb-3">
    <label class="form-label">Full Name</label>
    <input type="text" name="name" class="form-control" required>
  </div>
  <div class="mb-3">
    <label class="form-label">Phone</label>
    <input type="text" name="phone" class="form-control" required>
  </div>
  <div class="mb-3">
    <label class="form-label">Address</label>
    <textarea name="address" class="form-control" required></textarea>
  </div>
  <div class="mb-3">
    <label class="form-label">City</label>
    <input type="text" name="city" class="form-control" required>
  </div>
  <div class="mb-3">
    <label class="form-label">Pincode</label>
    <input type="text" name="pincode" class="form-control" required>
  </div>

  <div class="mb-3">
    <label class="form-label">Payment Method</label>
    <select name="payment_method" class="form-control" required>
      <option value="COD">Cash on Delivery (COD)</option>
    </select>
  </div>

  <button type="submit" name="place_order" class="btn btn-success btn-lg">Place Order</button>
</form>

<?php else: ?>
<p class="text-center">Your cart is empty. <a href="dashboard.php">Go shopping</a></p>
<?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
