<?php
namespace app\models;

use app\app;

class order_items
{
    public static function init()
    {
        app::$db->exec("CREATE TABLE IF NOT EXISTS order_items (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            order_id INTEGER NOT NULL REFERENCES orders(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 $orderId, int $productId, int $quantity)
    {
        if ($quantity <= 0) {
            throw new \InvalidArgumentException('Quantity must be greater than zero.');
        }

        $stmt = app::$db->prepare("INSERT INTO order_items (order_id, product_id, quantity)
                                   VALUES (:order_id, :product_id, :quantity)");
        $stmt->execute([
            'order_id'   => $orderId,
            'product_id' => $productId,
            'quantity'   => $quantity,
        ]);
    }

    public static function updateItem(int $orderItemId, int $quantity)
    {
        if ($quantity <= 0) {
            throw new \InvalidArgumentException('Quantity must be greater than zero.');
        }

        $stmt = app::$db->prepare("UPDATE order_items SET quantity = :quantity WHERE order_item_id = :order_item_id");
        $stmt->execute([
            'order_item_id' => $orderItemId,
            'quantity'      => $quantity,
        ]);
    }

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

    public static function getOrderItems(int $orderId): array
    {
        $stmt = app::$db->prepare("SELECT * FROM order_items WHERE order_id = :order_id");
        $stmt->execute(['order_id' => $orderId]);
        return $stmt->fetchAll();
    }
}
