<?php
namespace app\models;

use app\app;

class products
{
    public static function init()
    {
        app::$db->exec("CREATE TABLE IF NOT EXISTS products (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            desc TEXT,
            stock_qty INTEGER NOT NULL DEFAULT 0 CHECK(stock_qty >= 0),
            specs_json TEXT,
            sats_price INTEGER NOT NULL DEFAULT 0 CHECK(sats_price >= 0),
            cents_price INTEGER NOT NULL DEFAULT 0 CHECK(cents_price >= 0),
            digital BOOLEAN NOT NULL DEFAULT 0,
            subscription BOOLEAN NOT NULL DEFAULT 0,
            image_url_0 TEXT,
            image_url_1 TEXT,
            image_url_2 TEXT,
            image_url_3 TEXT,
            image_url_4 TEXT,
            image_url_5 TEXT,
            image_url_6 TEXT,
            image_url_7 TEXT,
            image_url_8 TEXT,
            image_url_9 TEXT,
            image_url_10 TEXT,
            image_url_11 TEXT
        )");
    }

    public static function add($title, $desc, $stock_qty, $specs_json, $sats_price, $cents_price, $digital, $subscription, $images)
    {
        $stmt = app::$db->prepare("INSERT INTO products (
            title, desc, stock_qty, specs_json, sats_price, cents_price, digital, subscription,
            image_url_0, image_url_1, image_url_2, image_url_3, image_url_4, image_url_5,
            image_url_6, image_url_7, image_url_8, image_url_9, image_url_10, image_url_11
        ) VALUES (
            :title, :desc, :stock_qty, :specs_json, :sats_price, :cents_price, :digital, :subscription,
            :image_url_0, :image_url_1, :image_url_2, :image_url_3, :image_url_4, :image_url_5,
            :image_url_6, :image_url_7, :image_url_8, :image_url_9, :image_url_10, :image_url_11
        )");

        $stmt->execute([
            ':title'        => $title,
            ':desc'         => $desc,
            ':stock_qty'    => $stock_qty,
            ':specs_json'   => $specs_json,
            ':sats_price'   => $sats_price,
            ':cents_price'  => $cents_price,
            ':digital'      => (int) $digital,
            ':subscription' => (int) $subscription,
            ':image_url_0'  => $images[0] ?? null,
            ':image_url_1'  => $images[1] ?? null,
            ':image_url_2'  => $images[2] ?? null,
            ':image_url_3'  => $images[3] ?? null,
            ':image_url_4'  => $images[4] ?? null,
            ':image_url_5'  => $images[5] ?? null,
            ':image_url_6'  => $images[6] ?? null,
            ':image_url_7'  => $images[7] ?? null,
            ':image_url_8'  => $images[8] ?? null,
            ':image_url_9'  => $images[9] ?? null,
            ':image_url_10' => $images[10] ?? null,
            ':image_url_11' => $images[11] ?? null,
        ]);
    }
}
