<?php
// cart.php - Professional cart page (blue/gray theme, fixed add-to-cart redirect)
session_start();
include_once 'config.php';
include_once 'auth.php';

// Handle cart actions before output
if (isset($_GET['action']) && isset($_GET['product_id'])) {
    $product_id = (int)$_GET['product_id'];
    // Use return_url from GET, fallback to HTTP_REFERER, then products.php
    $return_url = isset($_GET['return_url']) && !empty($_GET['return_url']) 
        ? urldecode($_GET['return_url']) 
        : ($_SERVER['HTTP_REFERER'] ?? 'products.php');
    
    if ($_GET['action'] == 'add') {
        // Verify product exists
        $stmt = $conn->prepare("SELECT id, stock FROM products WHERE id = ?");
        $stmt->bind_param("i", $product_id);
        $stmt->execute();
        $product = $stmt->get_result()->fetch_assoc();
        
        if ($product && $product['stock'] > 0) {
            if (isset($_SESSION['cart'][$product_id])) {
                $_SESSION['cart'][$product_id]++;
            } else {
                $_SESSION['cart'][$product_id] = 1;
            }
            set_flash_message('success', 'Item added to cart.');
        } else {
            set_flash_message('error', 'Item is out of stock or invalid.');
        }
        header("Location: $return_url");
        exit();
    } elseif ($_GET['action'] == 'remove') {
        unset($_SESSION['cart'][$product_id]);
        set_flash_message('success', 'Item removed from cart.');
        header("Location: cart.php");
        exit();
    }
}

// Handle quantity update
if (isset($_POST['update_cart']) && isset($_POST['quantity'])) {
    foreach ($_POST['quantity'] as $product_id => $quantity) {
        $product_id = (int)$product_id;
        $quantity = (int)$quantity;
        if ($quantity <= 0) {
            unset($_SESSION['cart'][$product_id]);
        } else {
            $_SESSION['cart'][$product_id] = $quantity;
        }
    }
    set_flash_message('success', 'Cart updated successfully.');
    header("Location: cart.php");
    exit();
}

// Handle checkout
if (isset($_POST['checkout']) && is_logged_in()) {
    $user_id = $_SESSION['user_id'];
    $total = 0;
    $items = [];
    
    if (!empty($_SESSION['cart'])) {
        $ids = implode(',', array_map('intval', array_keys($_SESSION['cart'])));
        $result = $conn->query("SELECT id, price FROM products WHERE id IN ($ids)");
        while ($row = $result->fetch_assoc()) {
            $total += $row['price'] * $_SESSION['cart'][$row['id']];
            $items[$row['id']] = $_SESSION['cart'][$row['id']];
        }
        
        $stmt = $conn->prepare("INSERT INTO orders (user_id, total, status, items) VALUES (?, ?, 'pending', ?)");
        $items_json = json_encode($items);
        $stmt->bind_param("ids", $user_id, $total, $items_json);
        if ($stmt->execute()) {
            unset($_SESSION['cart']);
            set_flash_message('success', 'Order placed successfully! <a href="orders.php" class="alert-link">View Orders</a>');
        } else {
            set_flash_message('error', 'Error placing order: ' . htmlspecialchars($conn->error));
        }
    } else {
        set_flash_message('error', 'Your cart is empty.');
    }
    header("Location: cart.php");
    exit();
}

include_once 'header.php';
?>

<style>
    .cart-container {
        max-width: 900px;
        margin: 120px auto;
        padding: 30px;
        background-color: white;
        box-shadow: 0 6px 15px rgba(0,0,0,0.1);
        border-radius: 12px;
        transition: box-shadow 0.3s ease;
    }
    .cart-container:hover {
        box-shadow: 0 8px 20px rgba(0,0,0,0.15);
    }
    .btn-primary {
        background-color: #0D6EFD;
        border-color: #0D6EFD;
        transition: background-color 0.3s ease, transform 0.2s ease;
    }
    .btn-primary:hover {
        background-color: #0c5fdb;
        transform: translateY(-2px);
    }
    .btn-danger {
        transition: background-color 0.3s ease, transform 0.2s ease;
    }
    .btn-danger:hover {
        background-color: #c82333;
        transform: translateY(-2px);
    }
    .btn-success {
        background-color: #198754;
        border-color: #198754;
        transition: background-color 0.3s ease, transform 0.2s ease;
    }
    .btn-success:hover {
        background-color: #157347;
        transform: translateY(-2px);
    }
    .table th, .table td {
        vertical-align: middle;
    }
    .form-control-sm {
        width: 80px;
    }
    h2 {
        font-family: 'Inter', sans-serif;
        color: #212529;
    }
    .alert-link {
        color: #0D6EFD;
    }
</style>

<div class="container cart-container">
    <h2 class="text-center mb-4"><i class="fas fa-shopping-cart me-2"></i>Shopping Cart</h2>
    
    <?php if (empty($_SESSION['cart'])): ?>
        <div class="alert alert-info text-center">Your cart is empty. <a href="products.php" class="link-primary">Shop now</a>.</div>
    <?php else: ?>
        <form method="post" action="cart.php">
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>Product</th>
                        <th>Price</th>
                        <th>Quantity</th>
                        <th>Total</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $total = 0;
                    $ids = implode(',', array_map('intval', array_keys($_SESSION['cart'])));
                    $result = $conn->query("SELECT id, name, price, image FROM products WHERE id IN ($ids)");
                    while ($row = $result->fetch_assoc()):
                        $subtotal = $row['price'] * $_SESSION['cart'][$row['id']];
                        $total += $subtotal;
                    ?>
                        <tr>
                            <td>
                                <img src="<?php echo htmlspecialchars($row['image'] ?? 'placeholder.jpg'); ?>" alt="<?php echo htmlspecialchars($row['name']); ?>" width="50" class="img-fluid me-2">
                                <?php echo htmlspecialchars($row['name']); ?>
                            </td>
                            <td>KES<?php echo number_format($row['price'], 2); ?></td>
                            <td>
                                <input type="number" name="quantity[<?php echo $row['id']; ?>]" value="<?php echo $_SESSION['cart'][$row['id']]; ?>" min="1" class="form-control form-control-sm">
                            </td>
                            <td>KES<?php echo number_format($subtotal, 2); ?></td>
                            <td>
                                <a href="cart.php?action=remove&product_id=<?php echo $row['id']; ?>" class="btn btn-danger btn-sm">Remove</a>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="3" class="text-end fw-bold">Total:</td>
                        <td colspan="2" class="fw-bold">KES<?php echo number_format($total, 2); ?></td>
                    </tr>
                </tfoot>
            </table>
            <div class="d-flex justify-content-between">
                <button type="submit" name="update_cart" class="btn btn-primary">Update Cart</button>
                <?php if (is_logged_in()): ?>
                    <a href="checkout.php" class="btn btn-success">Proceed to Checkout</a>
                <?php else: ?>
                    <a href="login.php?redirect=cart" class="btn btn-success">Login to Checkout</a>
                <?php endif; ?>
            </div>
        </form>
    <?php endif; ?>
    <div class="text-center mt-4">
        <a href="products.php" class="btn btn-outline-primary">Continue Shopping</a>
    </div>
</div>

<?php include_once 'footer.php'; ?>