<?php
namespace app\models;

use app\app;

class carts
{
    public static function init()
    {
        app::$db->exec("CREATE TABLE IF NOT EXISTS carts (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL REFERENCES users(id),
            short_id TEXT UNIQUE NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        );");
    }

    public static function addCart(int $userId): string
    {
        return self::createCart($userId, 'user_cart_id');
    }

    public static function addSaved(int $userId): string
    {
        return self::createCart($userId, 'user_saved_for_later_id');
    }

    private static function createCart(int $userId, string $column): string
    {
        $characters = '123456789ABCDEFGHJKLMNPQRSTUVWXYZ';
        $shortId    = '';

        for ($i = 0; $i < 6; $i++) {
            $shortId .= $characters[random_int(0, strlen($characters) - 1)];
        }

        app::$db->prepare("INSERT INTO carts (user_id, short_id) VALUES (:user_id, :short_id)")
            ->execute(['user_id' => $userId, 'short_id' => $shortId]);

        return $shortId;
    }
}
