<?php
namespace app\models;

use app\app;

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

    public static function addItem(int $quoteId, int $productId, int $quantity, float $price)
    {
        if ($quantity <= 0) {
            throw new \InvalidArgumentException('Quantity must be greater than zero.');
        }
        if ($price < 0) {
            throw new \InvalidArgumentException('Price must be non-negative.');
        }

        $stmt = app::$db->prepare("INSERT INTO quote_items (quote_id, product_id, quantity, price)
                                   VALUES (:quote_id, :product_id, :quantity, :price)");
        $stmt->execute([
            'quote_id'   => $quoteId,
            'product_id' => $productId,
            'quantity'   => $quantity,
            'price'      => $price,
        ]);
    }

    public static function updateItem(int $quoteItemId, int $quantity, float $price)
    {
        if ($quantity <= 0) {
            throw new \InvalidArgumentException('Quantity must be greater than zero.');
        }
        if ($price < 0) {
            throw new \InvalidArgumentException('Price must be non-negative.');
        }

        $stmt = app::$db->prepare("UPDATE quote_items SET quantity = :quantity, price = :price WHERE quote_item_id = :quote_item_id");
        $stmt->execute([
            'quote_item_id' => $quoteItemId,
            'quantity'      => $quantity,
            'price'         => $price,
        ]);
    }

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

    public static function getQuoteItems(int $quoteId): array
    {
        $stmt = app::$db->prepare("SELECT * FROM quote_items WHERE quote_id = :quote_id");
        $stmt->execute(['quote_id' => $quoteId]);
        return $stmt->fetchAll();
    }
}
