<?php
declare(strict_types=1);

namespace Bdp\Libs;

class DatabaseHandler {
	public function readFromDb(string $table, array $conditions = []) : array {
		global $wpdb;
		$sql = 'SELECT * FROM ' . $wpdb->prefix . $table . $this->parseConditions($conditions);
		return $this->getResults( $sql );
	}

	public function readSqlFromDb(string $tableName, string $preparedSql) : array
	{
		global $wpdb;
		$sql = str_replace('%tablename%', $wpdb->prefix . $tableName, $preparedSql );
		return $this->getResults($sql);
	}

	public function deleteFromDb(string $table, array $conditions = []) {
		global $wpdb;
		$table = $wpdb->prefix . $table;
		$wpdb->delete($table, $conditions);
	}

	public function insertRows(string $tableName, array $newData) : ?int
	{
		global $wpdb;
		$tableName = $wpdb->prefix . $tableName;


		if (!$wpdb->insert( $tableName, $newData )) {
            return null;
        };
		return $wpdb->insert_id;
	}

	public function updateRows(string $tableName, array $newData, $conditions = [])
	{
		global $wpdb;
		$tableName = $wpdb->prefix . $tableName;
        return $wpdb->update( $tableName, $newData, $conditions );
	}

	public function countSqlRows(string $tableName, array $conditions = []) : int
	{
		global $wpdb;
		$sql = 'SELECT COUNT(*) as count_data FROM ' . $wpdb->prefix . $tableName . $this->parseConditions($conditions);
		$res = $this->getResults( $sql );
		$res = $res[0];
		return (int)$res->count_data;
	}

	private function getResults(string $sql) : array
	{
		global $wpdb;
		return $wpdb->get_results($sql, OBJECT );
	}

	private function parseConditions(array $conditionArray) : string
	{
		global $wpdb;
		$_tmpArr = [];
		foreach ($conditionArray as $key => $value) {
			$_tmpArr[] = '`' . $key .'` = "' . $wpdb->_real_escape($value) . '"';
		}

		$returnString = implode(' AND ', $_tmpArr);
		return $returnString !== '' ? (' WHERE ' . $returnString) : '';
	}
}