<?php
// File: cart_handler.php
session_start();
require_once 'db.php';

// Initialize the cart if it doesn't exist
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

// --- ACTION: ADD ITEM TO CART ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $painting_id = filter_var($_POST['painting_id'], FILTER_SANITIZE_NUMBER_INT);
    $quantity = 1; // For now, we add one at a time. Can be expanded later.

    // Check if the painting already exists in the cart
    if (isset($_SESSION['cart'][$painting_id])) {
        // Optional: you could increase quantity here if you allow multiple
        // For now, we'll just confirm it's added
    } else {
        // Add the new item
        $_SESSION['cart'][$painting_id] = ['quantity' => $quantity];
    }
    
    // Redirect back to the paintings page with a success message
    header('Location: paintings.php?status=added_to_cart');
    exit();
}

// --- ACTION: UPDATE ITEM QUANTITY ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update') {
    $painting_id = filter_var($_POST['painting_id'], FILTER_SANITIZE_NUMBER_INT);
    $quantity = filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT);

    if (isset($_SESSION['cart'][$painting_id]) && $quantity > 0) {
        $_SESSION['cart'][$painting_id]['quantity'] = $quantity;
    } elseif ($quantity <= 0) {
        // If quantity is 0 or less, remove the item
        unset($_SESSION['cart'][$painting_id]);
    }
    
    header('Location: cart.php');
    exit();
}


// --- ACTION: REMOVE ITEM FROM CART ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'remove') {
    $painting_id = filter_var($_POST['painting_id'], FILTER_SANITIZE_NUMBER_INT);

    if (isset($_SESSION['cart'][$painting_id])) {
        unset($_SESSION['cart'][$painting_id]);
    }
    
    header('Location: cart.php?status=item_removed');
    exit();
}

// If no action is specified, redirect home
header('Location: index.php');
exit();

