<?php
// public_html/printshop/includes/db.php
include_once(__DIR__ . '/../config/config.php'); // Ensure the config is included

// Fetch all results from a query
function fetchAll($query, $params = []) {
    global $conn;
    $stmt = $conn->prepare($query);
    if ($params) {
        $types = str_repeat('s', count($params)); // Assuming all params are strings. Adjust this if needed.
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    return $data;
}

// Fetch a single row from a query
function fetchOne($query, $params = []) {
    global $conn;
    $stmt = $conn->prepare($query);
    if ($params) {
        $types = str_repeat('s', count($params)); // Assuming all params are strings. Adjust this if needed.
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    return $result->fetch_assoc();
}

// Execute a query (INSERT/UPDATE/DELETE)
function execute($query, $params = []) {
    global $conn;
    $stmt = $conn->prepare($query);
    if ($params) {
        $types = str_repeat('s', count($params)); // Assuming all params are strings. Adjust this if needed.
        $stmt->bind_param($types, ...$params);
    }
    return $stmt->execute();
}

// Sanitize a value to prevent SQL injection
function sanitize($value) {
    global $conn;
    return mysqli_real_escape_string($conn, trim($value)); // Use mysqli_real_escape_string for sanitization
}
?>
