<?PHP
    class Database {
        private $connection;

        function __construct($db_host, $db_name, $db_user, $db_pass, $db_port, $db_schema) {
          $this->connection = pg_connect("dbname={$db_name} user={$db_user} password={$db_pass} host={$db_host} port={$db_port}");
        }
				
				function __destruct() {
					pg_close($this->connection);
				}

    	function modify($str) {
        		return ucwords(str_replace("_", " ", $str));
    	}

				function getConn() {
					return $this->connection;
				}
        function getAll($table, $where = '', $orderby = '') {
            $orderby = $orderby ? 'ORDER BY '.$orderby : '';
            $where = $where ? 'WHERE '.$where : '';

            $query = "SELECT * FROM {$table} {$where} {$orderby}";
            $result = pg_query($this->connection, $query);

            if (!$result) {
                echo "An error occurred executing the query.\n";
                exit;
            }

            // Fetch all rows
            $rows = array();
            while ($row = pg_fetch_assoc($result)) {
                $rows[] = $row;
            }

            return $rows;
        }


        function get($table, $where = '') {
            if(is_numeric($where)) {
                $where = "id = ".intval($where);
            }
            else if (empty($where)) {
                $where = "1";
            }

            $query = "SELECT * FROM {$table} WHERE $where";
            $result = pg_query($this->connection, $query);

            if (!$result) {
                echo "An error occurred executing the query.\n";
                exit;
            }

            // Fetch one rows
            $row = pg_fetch_assoc($result);

            return $row;
        }


        /* Select Query */
        function select($query) {
            $result = pg_query($this->connection, $query);

            if (!$result) {
                echo "An error occurred executing the query.\n";
                exit;
            }

            // Fetch all rows
            $rows = array();
            while ($row = pg_fetch_assoc($result)) {
                $rows[] = $row;
            }

            return $rows;
        }
				
				function buildGeoJSON($query){
					$qc_id = 0;	# NOTE: counter needed by qgis2web ?
					echo '{"type": "FeatureCollection",
				    	"features": [';

					$feature = array('type' => 'Feature');
					
					$result = pg_query($this->connection, $query);
					if ($result) {
						$sep = '';
						while ($row = pg_fetch_assoc($result)) {
							$feature['geometry'] = json_decode($row['geojson'], true);
							# Remove geojson and geometry fields from properties
							unset($row['geojson']);
							unset($row['geom']);
							$row['qc_id'] = $qc_id; $qc_id = $qc_id + 1;
							$feature['properties'] = $row;
							
							echo $sep."\n".json_encode($feature, JSON_NUMERIC_CHECK);
							$sep = ',';
						}
						pg_free_result($result);
					}
					
					echo ']}';
					
					return 0;
				}
				
				function find_srid($schema, $tbl, $geom){
					/*$query = "SELECT Find_SRID('".$schema."','".$tbl."','".$geom."')";
					$result = pg_query($this->connection, $query);

					if (!$result) {
						echo "An error occurred executing the query.\n";
						exit;
					}
					$row = pg_fetch_assoc($result);
					pg_free_result($result);
					
					return $row['find_srid'];*/
					return 4326;
				}
				
				function getGeoJSON($schema, $tbl, $geom){
					if(!empty($where)){
						$where = 'WHERE '.$where;
					}
					
					$srid = $this->find_srid($schema, $tbl, $geom);
					
					$query = 'SELECT *, public.ST_AsGeoJSON(public.ST_Transform(('.$tbl.'.'.$geom.'),'.$srid.')) AS geojson FROM "'.$schema.'"."'.$tbl.'"';
					return $this->buildGeoJSON($query);
				}
    }
?>