<?php
require_once __DIR__ . '/config.php';

class Database {
    private $host = DB_HOST;
    private $user = DB_USER;
    private $pass = DB_PASS;
    private $dbname = DB_NAME;
    private $conn;
    
    // Singleton instance to prevent multiple connections
    private static $instance = null;
    
    public function __construct() {
        $this->connectDB();
    }
    
    // The Singleton Method
    public static function getInstance() {
        if (self::$instance == null) {
            self::$instance = new Database();
        }
        return self::$instance;
    }
    
    private function connectDB() {
        $this->conn = new mysqli($this->host, $this->user, $this->pass, $this->dbname);
        
        if ($this->conn->connect_error) {
            die("Connection failed: " . $this->conn->connect_error);
        }
        
        $this->conn->set_charset("utf8mb4");
    }
    
    public function getConnection() {
        return $this->conn;
    }
    
    public function select($query, $params = []) {
        $stmt = $this->conn->prepare($query);
        if (!$stmt) return []; // Fail-safe
        
        if (!empty($params)) {
            $types = str_repeat('s', count($params));
            $stmt->bind_param($types, ...$params);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        
        $data = [];
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
        
        $stmt->close();
        return $data;
    }
    
    public function insert($query, $params = []) {
        $stmt = $this->conn->prepare($query);
        if (!$stmt) return false; // Fail-safe
        
        if (!empty($params)) {
            $types = str_repeat('s', count($params));
            $stmt->bind_param($types, ...$params);
        }
        
        if ($stmt->execute()) {
            $insert_id = $stmt->insert_id;
            $stmt->close();
            return $insert_id;
        }
        
        $stmt->close();
        return false;
    }
    
    // MAGIC DESTRUCTOR: Forces the connection closed the moment the script ends!
    public function __destruct() {
        if ($this->conn) {
            $this->conn->close();
        }
    }
}

// Instantiate using the Singleton to ensure absolute connection safety
$db = Database::getInstance();
$conn = $db->getConnection();

/* ---------------------------------------------------------------------------
   Admin activity trail. The helper decides for itself whether the current
   request is worth recording, and every failure is swallowed, so this can
   never break a page.
   ------------------------------------------------------------------------ */
if (@is_file(__DIR__ . '/includes/activity.php')) {
    require_once __DIR__ . '/includes/activity.php';
    try { activity_autolog($db); } catch (\Throwable $e) { /* never break a page */ }
}
?>