<?php
/**
 * Noahvelle POS - Data Connection Configuration Helper
 */

// Include base configuration
require_once __DIR__ . '/config.php';

// --- SHARED API HELPER ---
// Using dynamic URLs to support hosting in any directory
function get_api_base_url() {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
    $host = $_SERVER['HTTP_HOST'];
    $script_dir = dirname(dirname($_SERVER['SCRIPT_NAME']));
    $base_dir = str_replace('\\', '/', $script_dir);
    if ($base_dir === '/') $base_dir = '';
    return $protocol . '://' . $host . $base_dir . '/api/';
}

function get_frontend_url() {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
    $host = $_SERVER['HTTP_HOST'];
    $script_dir = dirname(dirname($_SERVER['SCRIPT_NAME']));
    $base_dir = str_replace('\\', '/', $script_dir);
    if ($base_dir === '/') $base_dir = '';
    return $protocol . '://' . $host . $base_dir . '/../';
}

define('API_BASE_URL', get_api_base_url());
define('FRONTEND_URL', get_frontend_url());

class Database {
    private $conn;

    /**
     * Get the database connection
     */
    public function getConnection() {
        $this->conn = null;

        try {
            $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
            
            if ($this->conn->connect_error) {
                error_log("Connection error: " . $this->conn->connect_error);
                return null;
            }
            
            $this->conn->set_charset("utf8");
        } catch (Exception $e) {
            error_log("Connection error: " . $e->getMessage());
        }

        return $this->conn;
    }

    /**
     * Escape string for SQL
     */
    public function escape($string) {
        if (!$this->conn) {
            $this->getConnection();
        }
        return $this->conn->real_escape_string($string);
    }

    /**
     * Close connection
     */
    public function close() {
        if ($this->conn) {
            $this->conn->close();
            $this->conn = null;
        }
    }
}
?>
