<?php
namespace app\models;

use app\app;

class user_settings
{
    public static function init()
    {
        app::$db->exec("CREATE TABLE IF NOT EXISTS user_settings (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL REFERENCES users(id),
            opt_in_promotional BOOLEAN NOT NULL,
            opt_in_subscription BOOLEAN DEFAULT TRUE,
            opt_in_order BOOLEAN DEFAULT TRUE,
            dark_theme BOOLEAN NOT NULL
        );");
    }

    public static function add($user_id, $opt_in_promotional, $dark_theme)
    {
        $query = "INSERT INTO user_settings (user_id, opt_in_promotional, dark_theme)
                  VALUES (:user_id, :opt_in_promotional, :dark_theme)";
        $stmt = app::$db->prepare($query);
        $stmt->bindParam(':user_id', $user_id);
        $stmt->bindParam(':opt_in_promotional', $opt_in_promotional);
        $stmt->bindParam(':dark_theme', $dark_theme);
        $stmt->execute();
    }

    public static function update($user_id, $columnValues)
    {
        $setClause = [];
        foreach ($columnValues as $column => $value) {
            $setClause[] = "$column = :$column";
        }
        $setClause = implode(', ', $setClause);
        $query     = "UPDATE user_settings SET $setClause WHERE user_id = :user_id";
        $stmt      = app::$db->prepare($query);
        foreach ($columnValues as $column => &$value) {
            $stmt->bindParam(":$column", $value);
        }
        $stmt->bindParam(':user_id', $user_id);
        $stmt->execute();
    }

    public static function getByUserId($user_id)
    {
        $query = "SELECT * FROM user_settings WHERE user_id = :user_id";
        $stmt  = app::$db->prepare($query);
        $stmt->bindParam(':user_id', $user_id);
        $stmt->execute();
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }
}
