<?php

declare(strict_types=1);

namespace netico\Bones;

/**
 * SQLite wrapper.
 *
 * This is just another SQLite database access wrapper class.
 * It can establish connections to the SQLite database, execute SQL queries, and return results.
 * Native drivers are great if you are only using one database in your application,
 * so this class uses the native SQLite driver.
 *
 *      $db = new \netico\Bones\SQLite();
 *      $db->sql("SELECT * FROM pages ORDER BY [rowid] ASC;");
 *      $db->close();
 *
 *      var_dump($db->data);
 *
 * @package bones
 * @link https://git.lattuga.net/netico/code-library/src/master/Framework
 * @copyright Copyright (c) 2016, 2022 netico <netico@riseup.net>
 * @license https://www.gnu.org/licenses/gpl-3.0.en.html GNU General Public License
 * @author netico <netico@riseup.net>
 *
 */
class SQLite
{
    /**
     * This array contains the results of the query.
     *
     * @var array[] $data
     */
    public $data;
    private $schema;
    private $conn;

    /**
     * This method retrieves the SQLite database path from the configuration file
     * and then opens a connection in read mode.
     */
    public function __construct()
    {
        $c = new \netico\Bones\Configuration(CONFIG);
        $this->schema = $c->getValue("database", "sqlite");
        // FIXME: Exception
        $this->conn = $this->SQLiteOpen($this->schema);
    }

    /**
     * This method closes the connection to the database.
     *
     * @return void
     */
    public function close()
    {
        $this->SQLiteClose($this->conn);
    }

    /**
     * It runs a SQL query on a given database and builds an array of the results.
     *
     * @param string $query
     * @return void
     */
    public function SQL($query)
    {
        $r = $this->SQLiteQuery($this->conn, $query);
        if (is_array($this->data) === true) {
            unset($this->data);
        }
        // FIXME: Exception
        if (is_bool($r) === false) {
            while ($row = $this->SQLiteFetchArray($r)) {
                $this->data[] = $row;
            }
        }
        return $this->data;
    }

    private function SQLiteOpen($path)
    {
        $handle = new \SQLite3($path, SQLITE3_OPEN_READONLY);
        return $handle;
    }

    private function SQLiteClose($handle)
    {
        $handle->close();
    }

    private function SQLiteQuery($dbhandle, $query)
    {
        $res = $dbhandle->query($query);
        return $res;
    }

    private function SQLiteFetchArray(&$r)
    {
        # Get Columns
        $i = 0;
        while ($r->columnName($i)) {
            $columns[] = $r->columnName($i);
            $i++;
        }
        $res = $r->fetchArray(SQLITE3_ASSOC);
        return $res;
    }
}
