<?php
// This script functions as the hidden connection to the postgresql db
// Clients never directly contact this script, it is only contacted by the inventorytrack index page
// The index page will call functions from here to get data, and then return it to clients that requested it
// All requests from the index page will need to be authenticated by a session number (except logins, which will then add session keys to then authenticate further requests)


class Database {

    public $db;

    public function __construct() {
        print '<!-- CONSTRUCTING DATABASE -->';
        $this->$db = null;
        $this->connect();
        print '<!-- DONE CONSTRUCTING DATABASE -->';
    }

    // public function __destructor() {
    //     if ($this->$db) {
    //         pg_close($this->$db);
    //     }
    // }

    // Establish connection to the db
    private function connect() {
        print '<!-- CONNECTING DATABASE -->';
        // Get credentials
        print '<!-- getting creds -->';
        require('command.php');
        print '<!-- got creds -->';
        // Credentials String
        $creds = "host=localhost port=5432 user=" . $dbadminusername . " password=" . $dbadminpassword . " dbname=inventorytrackdb";

        print '<!-- running connect -->';
        if (!$this->$db) {
            //$this->$db = new PDO('pgsql:host=localhost;port=5432;dbname=inventorytrackdb', $dbadminusername, $dbadminpassword);
            $this->$db = pg_connect($creds);
        }
        if (!$this->$db) {
            echo '<p> NOT ACTUALLY CONNECTED TO DB WTHHH </p>';
        }
        
        print '<!-- DONE CONNECTING DATABASE -->';
    }

    public function test_con() {
        print '<!-- TESTING CONNECTION -->';
        $result = pg_query($this->$db, "SELECT * FROM users_table;");
        // $result = $this->$db->prepare("SELECT * FROM users_table;");
        // $result->execute();
        // $recordset = $result->fetchAll();
        // $result->closeCursor();
        print '<!-- DONE TESTING CONNECTION -->';
        return pg_fetch_all($result);
    }

}



?>