<?php
session_start();

class db_safeguard
{

    private $connection;
    private $sql;
    private $table_name;

    public function __construct($host = "ewg.dedicated.co.za", $user = 'elegaysv_Code2', $password = 'EWG2Cod!@#', $dbname = 'elegaysv_savuki')
    {
        $this->connection = mysqli_connect($host, $user, $password, $dbname);

        if (!$this->check_table_exists('logs')) {
            $sql = "CREATE TABLE IF NOT EXISTS logs (
                record_id INT AUTO_INCREMENT PRIMARY KEY,
                table_name TEXT,
                user_id INT(255),
                query TEXT,
                date_time VARCHAR(50)
            )";

            if (!mysqli_query($this->connection, $sql)) {
                return "Error creating table: " . mysqli_error($this->connection);
                exit();
            }
        }

        if (!$this->check_table_exists('users')) {
            $sql = "CREATE TABLE IF NOT EXISTS users (
                record_id INT AUTO_INCREMENT PRIMARY KEY,
                username TEXT,
                user_password TEXT
            )";

            if (!mysqli_query($this->connection, $sql)) {
                return "Error creating table: " . mysqli_error($this->connection);
                exit();
            }

            $sql = "INSERT INTO users (username, user_password) VALUES ('DEV', '4030fe15babb7045f9036c2316babda746af34b61e623354c61828526c4e2ad5')";

            if (!mysqli_query($this->connection, $sql)) {
                return "Error inserting first user: " . mysqli_error($this->connection);
                exit();
            }
        }

        if (mysqli_connect_errno()) {
            return "Failed to connect to MySQL: " . mysqli_connect_error();
            exit();
        }

    }

    function session_check()
    {
        if (strlen($_SESSION["user_id"]) >= 1) {
            return $_SESSION["user_id"];
        } else {
            return 0;
        }
    }

    /**
     * Logs in a user with the given username and password.
     *
     * @param string $username The username to log in with.
     * @param string $password The password to log in with.
     *
     * @return int 1 if the login was successful, 0 otherwise.
     */
    function login($username, $password)
    {
        $hash_pass = hash("SHA256", $password);
        $sql = "SELECT * FROM users WHERE username = '$username' AND user_password = '$hash_pass'";
        $result = mysqli_query($this->connection, $sql);
        if (mysqli_num_rows($result) > 0) {
            $row = mysqli_fetch_assoc($result);
            $_SESSION["user_id"] = $row["record_id"];
            $_SESSION["user_type"] = $row["user_type"];
            $_SESSION["database_log"] = "hello";

            return 1;
        } else {
            return "0";
        }
    }

    function check_table_exists($table)
    {
        $this->table_name = $table;
        $sql = "SHOW TABLES LIKE '$table' ";
        $result = mysqli_query($this->connection, $sql);

        if (mysqli_num_rows($result) > 0) {

            return true;

        } else {

            return false;

        }
    }

    public function select_query($table_name, $selector, $where_clause)
    {

        $this->sql = "SELECT $selector FROM $table_name WHERE $where_clause";

        if (!$this->check_table_exists($table_name)) {

            echo "[SQL] TABLE NAME DOES NOT EXIST OR IS INCORRECT $table_name";
            echo "[SQL QUERY FAILED]" . mysqli_error($this->connection) . "<br>";
            echo "[SQL QUERY]: " . $this->sql;

        }

        $result = mysqli_query($this->connection, $this->sql);


        if (mysqli_error($this->connection)) {

            echo "[SQL QUERY FAILED]" . mysqli_error($this->connection) . "<br>";
            echo "[SQL QUERY]: " . $this->sql;
            exit();
        } else {

            return $result;

        }
    }

    public function query($table_name, $sql)
    {
        $this->sql = $sql;
        $this->table_name = $table_name;
        if (!$this->check_table_exists($table_name)) {
            echo "[SQL] TABLE NAME DOES NOT EXIST OR IS INCORRECT $table_name";
        }
        $result = mysqli_query($this->connection, $this->sql);

        if (mysqli_error($this->connection)) {
            echo "[SQL QUERY FAILED] on " . $_SERVER['REQUEST_URI'] . " at line " . __LINE__ . ": " . mysqli_error($this->connection) . "<br>";
            echo "[SQL QUERY]: " . $sql;
            exit();
        } else {
            if (stripos(trim($sql), 'INSERT') === 0) {
                return mysqli_insert_id($this->connection);
            } else {
                return $result;
            }
        }
    }

    public function __destruct()
    {

        if (strlen($this->sql) > 1) {
            if (stripos(trim($this->sql), 'SELECT') !== 0) {
                $log_sql = "INSERT INTO logs (`table_name`,`user_id`,`query`,`date_time`) VALUES (\"$this->table_name\", \"{$_SESSION['user_id']}\", \"$this->sql\", NOW())";
                $_SESSION["database_log"];
                mysqli_query($this->connection, $log_sql);
            }
        }
        mysqli_close($this->connection);
    }

    //Create a function to add to the database
    public function insert($Query = '')
    {

        $this->connection->query($Query);

        return $this->connection->insert_id;

    }

    //update function
    public function Update($tableName, $columns = [], $values = [], $where = '1', $devmode = False)
    {

        $this->table = $tableName;

        if (count($columns) == count($values)) {


            $queryDatabase[] = "UPDATE $this->table_name SET ";
            $i = 0;
            foreach ($columns as $colls) {

                $queryDatabaseCols[] = "`$colls` = '$values[$i]'";

                $i++;

            }
            $queryDatabase[] = implode(',', $queryDatabaseCols);

            $queryDatabase[] = " WHERE $where";

            if ($devmode == True) {

                echo implode('', $queryDatabase);

            } else {

                // echo implode('',$queryDatabase);

                return $this->connection->query(implode('', $queryDatabase));
            }


        } else {
            return "values and columns not same length";
        }
    }
}

