<?php

/**
 * Helper functions for WP DB.
 *
 * @package northmill-online-shared
 * @noinspection PhpUnused
 */
declare (strict_types=1);
namespace Northmill_Online_Shared_Sync\Northmill_Online_Shared\Helpers;

/**
 * Various helper functions for DB.
 */
class DB_Helpers
{
    /**
     * Insert data into database.
     *
     * @param string       $table  Table name.
     * @param array        $data   Data to insert.
     * @param array|string $format Format of data.
     *
     * @return int|void
     */
    public static function insert_row(string $table, array $data, array|string $format)
    {
        global $wpdb;
        $result = $wpdb->insert($table, $data, $format);
        if ($result) {
            return $wpdb->insert_id;
        }
    }
    /**
     * Get all rows from a table.
     *
     * @param string $table Table name without prefix. This is NOT sanitized.
     *
     * @return array
     */
    public static function get_all_rows_from_table(string $table): array
    {
        global $wpdb;
        $table = $wpdb->prefix . $table;
        $result = $wpdb->get_results("SELECT * FROM {$table}", \ARRAY_A);
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        return is_array($result) ? $result : array();
    }
    /**
     * Truncate a table.
     *
     * @param string $table_name Table name without prefix. This is NOT sanitized.
     *
     * @return bool True if successful, false otherwise.
     */
    public static function truncate_table(string $table_name): bool
    {
        global $wpdb;
        $table_name = $wpdb->prefix . $table_name;
        return $wpdb->query("TRUNCATE TABLE {$table_name}");
    }
}
