<?php
namespace app\models;

use app\app;

class cart_items
{
    public static function init()
    {
        app::$db->exec("CREATE TABLE IF NOT EXISTS cart_items (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            cart_id INTEGER NOT NULL REFERENCES carts(id) ON DELETE CASCADE,
            product_id INTEGER NOT NULL REFERENCES products(id),
            quantity INTEGER NOT NULL CHECK(quantity > 0),
            added_at DATETIME DEFAULT CURRENT_TIMESTAMP
        );");
    }

    public static function addItem(int $cartId, int $productId, int $quantity)
    {
        $stmt = app::$db->prepare("INSERT INTO cart_items (cart_id, product_id, quantity)
                                   VALUES (:cart_id, :product_id, :quantity)");
        $stmt->execute([
            'cart_id'    => $cartId,
            'product_id' => $productId,
            'quantity'   => $quantity,
        ]);
    }

    public static function updateItem(int $cartItemId, int $quantity)
    {
        $stmt = app::$db->prepare("UPDATE cart_items SET quantity = :quantity WHERE cart_item_id = :cart_item_id");
        $stmt->execute([
            'cart_item_id' => $cartItemId,
            'quantity'     => $quantity,
        ]);
    }

    public static function removeItem(int $cartItemId)
    {
        $stmt = app::$db->prepare("DELETE FROM cart_items WHERE cart_item_id = :cart_item_id");
        $stmt->execute(['cart_item_id' => $cartItemId]);
    }

    public static function getCartItems(int $cartId): array
    {
        $stmt = app::$db->prepare("SELECT * FROM cart_items WHERE cart_id = :cart_id");
        $stmt->execute(['cart_id' => $cartId]);
        return $stmt->fetchAll();
    }
}
