<?php

/*
	--- The Database Module
	--- This module is for the general CRUD methods.
	--- This module was crafted by Skylear. : )
	--- Copyright (c) Mad Splash, 2014, all rights reserved.
*/

class Database
{
	/* --- Variables - data the module needs to work with. --- */
	private static PDO $c;

	/* --- Constructor - creates the module's instance. --- */
	public static function init(string $path, array $opts = [])
	{
		$opts = !empty($opts) ? $opts : [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ];

        try {
            self::$c = new PDO("sqlite:$path", null, null, $opts);
        } catch (PDOException $e) {
            throw $e;
        }
	}

	/* --- Module Functions - the meat and purpose of the module. --- */
	/* Create Table - for creating a table when need be.
	* @param string $name - the name of the table to be created.
	* @param string $columns - a long string containing the columns to be made.
	*/
	public static function createTable($name, $columns) {
		// No need for creating tables for the time being.
	}

	/* Select Data - used for getting data from the database.
	* @return array $selectedRos - an array containing the data.
	*/
	public static function select(string $from, string $retrieve, string $condition, string $orderby = '', int $limit = 0, array $data = [])
	{
		$query = "SELECT $retrieve FROM $from $condition";
		if (!empty($orderby)) { $query .= " ORDER BY $orderby"; }
		if ($limit > 0) { $query .= " LIMIT $limit"; }

		$selectQuery = self::$c->prepare($query);
		$selectQuery->execute($data);
		return $selectQuery;
	}

	public function count(string $from, string $condition = ''): mixed
	{
		$query = "SELECT COUNT(*) FROM $from";
		if (!empty($condition)) { $query .= " $condition"; }
		return self::$c->query($query)->fetch();
	}
}
