<?php

session_start();
require 'connect.php';

    // Get member_id from session
    $userId = $_SESSION['userid'] ?? null;
    if (!$userId) {
        header('Location: ./Sign&Log.php');
    }

    function getCartItems($conn, $memberId) {
        $query = "
            SELECT 
                book.bookid,
                book.title,
                book.publishedyear,
                book.coverimage,
                book.description,
                string_agg(CONCAT(author.firstname, ' ', author.lastname), ', ') as author_names
            FROM cart 
			JOIN book ON book.bookid = cart.bookid
            JOIN book_author ON book.bookid = book_author.bookid
            JOIN author ON book_author.authorid = author.authorid
            WHERE cart.memberid = :memberid
            GROUP BY book.bookid, book.title, book.publishedyear, book.coverimage, book.description;
        ";
        
        $stmt = $conn->prepare($query);
        $stmt->execute(['memberid' => $memberId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

// Assuming you store user_id in session and need to get member_id
    $userId = $_SESSION['userid'] ?? null;
    if ($userId) {
        $memberQuery = "SELECT memberid FROM member WHERE userid = :userid";
        $stmt = $conn->prepare($memberQuery);
        $stmt->execute(['userid' => $userId]);
        $member = $stmt->fetch(PDO::FETCH_ASSOC);
        $memberId = $member['memberid'] ?? null;
    } else {
        // Redirect to login if no user is logged in
        header('Location: ./Sign&Log.php');
        exit();
    }

// Fetch cart items
$cartItems = $memberId ? getCartItems($conn, $memberId) : [];

    if (isset($_GET['submit']) == 'remove-from-cart') {
        try {
            // Delete from cart
            $deleteQuery = "DELETE FROM cart WHERE memberid = :memberid AND bookid = :bookid";
            $deleteStmt = $conn->prepare($deleteQuery);
            $deleteStmt->execute([
                'memberid' => $member['memberid'],
                'bookid' => $_GET['bookid']
            ]);

            header("Location: ./Cart.php");
            exit();

        } catch (PDOException $e) {
            error_log("Database error: " . $e->getMessage());
            echo "An error occurred while removing the book from your cart.";
            exit();
        }
    }

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shopping Cart</title>
    <link rel="stylesheet" href="CSS/Cart.css">
</head>
<body>

<?php include 'Components/Header.html'; ?>


<div class="container">
        <div class="breadcrumb">
            <a href="#">Books</a> / <a href="#">Cart</a>
        </div>

        <div class="cart-page">
            <h1>Your Cart</h1>

            <div class="cart-items">
            <?php if (empty($cartItems)): ?>
                <p>Your cart is empty.</p>
            <?php else: ?>
                <?php foreach ($cartItems as $item): ?>
                    <div class="cart-item">
                        <div class="cart-item-image">
                            <?php if ($item['coverimage']): ?>
                                <img src="BookImages/<?php echo htmlspecialchars($item['coverimage']); ?>" alt="Book Cover">
                            <?php else: ?>
                                <img src="images/placeholder-book.png" alt="Book Cover">
                            <?php endif; ?>
                        </div>
                        <div class="cart-item-info">
                            <h2><?php echo htmlspecialchars($item['title']); ?></h2>
                            <p>By <?php echo htmlspecialchars($item['author_names']); ?></p>
                            <p>Publication Year: <?php echo htmlspecialchars($item['publishedyear']); ?></p>
                        </div>
                        <div class="cart-item-actions">
                            <form method="GET" action="Cart.php">
                                <input type="hidden" name="bookid" value="<?php echo $item['bookid']; ?>">
                                <button type="submit" name="submit" value="remove-from-cart" class="btn btn-secondary">Remove</button>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <div class="cart-summary">
            <h2>Summary</h2>
            <div class="summary-item">
                <span>Total Books: <?php echo count($cartItems); ?> </span>
            </div>
            <form action="./BorrowBook.php" method="POST">
                <input type="hidden" name="memberid" value="<?php echo $_SESSION['userid'] ?>">
                <button class="btn btn-primary" <?php if (count($cartItems) == 0) { echo 'disabled'; } ?>>Borrow</button>
            </form>
        </div>
    </div>
</div>

<?php include 'Components/Footer.html'; ?>
</body>
</html>