<?php

require_once __DIR__ . '/koneksi.php';
require_once __DIR__ . '/auth.php';

/**
 * 🔥 QUERY AUTO COMPANY
 */
function dbQuery($sql) {
    global $conn;

    $company_id = getCompanyId();

    // 🔥 AUTO TAMBAH WHERE
    if (stripos($sql, 'where') !== false) {
        $sql .= " AND company_id = '$company_id'";
    } else {
        $sql .= " WHERE company_id = '$company_id'";
    }

    return mysqli_query($conn, $sql);
}

/**
 * 🔥 GET ALL DATA
 */
function dbGetAll($sql) {
    $result = dbQuery($sql);

    $data = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }

    return $data;
}

/**
 * 🔥 GET SINGLE
 */
function dbGetOne($sql) {
    $result = dbQuery($sql);
    return mysqli_fetch_assoc($result);
}

/**
 * 🔥 INSERT AUTO COMPANY
 */
function dbInsert($table, $data) {
    global $conn;

    $company_id = getCompanyId();

    // 🔥 inject company_id otomatis
    $data['company_id'] = $company_id;

    $columns = implode(",", array_keys($data));
    $values  = implode("','", array_values($data));

    $sql = "INSERT INTO $table ($columns) VALUES ('$values')";

    return mysqli_query($conn, $sql);
}

/**
 * 🔥 UPDATE AUTO COMPANY
 */
function dbUpdate($table, $data, $where) {
    global $conn;

    $company_id = getCompanyId();

    $set = [];
    foreach ($data as $key => $val) {
        $set[] = "$key='$val'";
    }

    $setString = implode(",", $set);

    $sql = "UPDATE $table SET $setString WHERE $where AND company_id='$company_id'";

    return mysqli_query($conn, $sql);
}

/**
 * 🔥 DELETE AUTO COMPANY
 */
function dbDelete($table, $where) {
    global $conn;

    $company_id = getCompanyId();

    $sql = "DELETE FROM $table WHERE $where AND company_id='$company_id'";

    return mysqli_query($conn, $sql);
}