<?php

namespace classes;

class TransactionHistory
{
    private const DATE_CREATED_COLUMN = "date_created";
    private const LAST_UPDATED_COLUMN = "last_updated";
    private const MYSQL_NOW_FUNCTION = "NOW()";

    /**
     * Inserts a record into the database.
     *
     * @param array $data An associative array of column-value pairs to insert.
     * @param MysqliVeu $database An instance of the database connection.
     * @return void
     * @throws \Exception
     */
    public static function insertRecord(array $data, MysqliVeu $database): bool
    {
        $sql = self::buildQuery($data);
        $params = array_values($data);
        return $database->execute($sql, $params);
    }


    /**
     * Builds an SQL query string for inserting data into the transaction_history table.
     *
     * @param array $data Associative array of column names and their corresponding values.
     * @return string|null The constructed SQL query string or null.
     */
    private static function buildQuery(array $data): ?string
    {
        $columns = self::createColumnNamesArray($data);
        $placeholders = self::createPlaceholdersArray(count($columns));

        $columnsString = implode(', ', $columns);
        $placeholdersString = implode(', ', $placeholders);

        return "INSERT INTO transaction_history ($columnsString) VALUES ($placeholdersString)";
    }


    /**
     * Creates an array of column names to be used in an SQL insert statement.
     *
     * @param array $data Associative array of column names and their corresponding values.
     * @return array The array of column names including predefined columns for date created and last updated.
     */
    private static function createColumnNamesArray(array $data): array
    {
        $columns = array_keys($data);
        $columns[] = self::DATE_CREATED_COLUMN;
        $columns[] = self::LAST_UPDATED_COLUMN;
        return $columns;
    }


    /**
     * Creates an array of placeholders for SQL query values.
     *
     * @param int $countOfColumns Number of columns for which placeholders are needed.
     * @return array Array of placeholders, with the last two placeholders set to the MySQL NOW() function.
     */
    private static function createPlaceholdersArray(int $countOfColumns): array
    {
        $placeholders = array_fill(0, $countOfColumns - 2, '?');
        $placeholders[] = self::MYSQL_NOW_FUNCTION;
        $placeholders[] = self::MYSQL_NOW_FUNCTION;
        return $placeholders;
    }
}
