<?php

class ModelSettingDeveloper extends Model {

	const SHOWTABLESSQL = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '" . DB_DATABASE . "' AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME";
	const COUNTTABLESSQL = "SELECT COUNT(*) AS total_tabelas FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '" . DB_DATABASE . "' AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME";
	const DESCRIBETABLESQL = "SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS
		WHERE TABLE_SCHEMA = '" . DB_DATABASE . "'";

    public function getDescribe($data = array()):array {

		if (!isset($data['table'])) {
			return [];
		}

		$sql = self::DESCRIBETABLESQL . " AND TABLE_NAME = '" . $data['table'] ."'";

		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}

			$list = $sql . " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}

		$queryA = $this->db->query($list);
		$queryB = $this->db->query($sql);

		$describeTable = $queryA->rows;
		$countFields = $queryB->num_rows;

		return [
			"fields"=> $describeTable,
			"count"=> $countFields
		];

    }

	public function getTables($data = array()):array {

		$sql = self::SHOWTABLESSQL;
		$sqlCount = self::COUNTTABLESSQL;

		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}

			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}

		$queryA = $this->db->query($sql);
		$queryB = $this->db->query($sqlCount);
		$tables = $queryA->rows;
		$count = $queryB->rows[0]['total_tabelas'];

		return [
				"tables"=> $tables,
				"count"=> $count
			];
	}

}