<?php
// db.php - Database Functions
// File location: /bidwheels.net/includes/db.php

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

/**
 * Execute query and return result
 */
function query($sql) {
    global $conn;
    return mysqli_query($conn, $sql);
}

/**
 * Get single row
 */
function fetchOne($sql) {
    $result = query($sql);
    return mysqli_fetch_assoc($result);
}

/**
 * Get all rows
 */
function fetchAll($sql) {
    $result = query($sql);
    $data = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }
    return $data;
}

/**
 * Get total count
 */
function getCount($table, $where = '') {
    $sql = "SELECT COUNT(*) as total FROM $table";
    if ($where) {
        $sql .= " WHERE $where";
    }
    $result = fetchOne($sql);
    return $result['total'];
}

/**
 * Insert data into table
 */
function insert($table, $data) {
    global $conn;
    $fields = array_keys($data);
    $values = array_values($data);
    
    $fields_str = implode(', ', $fields);
    $values_str = "'" . implode("', '", array_map('mysqli_real_escape_string', array_fill(0, count($values), $conn), $values)) . "'";
    
    $sql = "INSERT INTO $table ($fields_str) VALUES ($values_str)";
    query($sql);
    return mysqli_insert_id($conn);
}

/**
 * Update data in table
 */
function update($table, $data, $where) {
    global $conn;
    $set = [];
    foreach ($data as $key => $value) {
        $set[] = "$key = '" . mysqli_real_escape_string($conn, $value) . "'";
    }
    $set_str = implode(', ', $set);
    $sql = "UPDATE $table SET $set_str WHERE $where";
    return query($sql);
}

/**
 * Delete from table
 */
function delete($table, $where) {
    $sql = "DELETE FROM $table WHERE $where";
    return query($sql);
}

/**
 * Get last inserted ID
 */
function lastInsertId() {
    global $conn;
    return mysqli_insert_id($conn);
}

/**
 * Escape string for safe query
 */
function escape($str) {
    global $conn;
    return mysqli_real_escape_string($conn, $str);
}

/**
 * Check if table exists
 */
function tableExists($table) {
    $result = query("SHOW TABLES LIKE '$table'");
    return mysqli_num_rows($result) > 0;
}
?>