<?php
/*
 * 파일명 : yy_db_conn.php
 * 작성 : jay yun
 * PHP 5.6, PHP 8.x 호환 버전
 */

// strict_types 선언은 PHP 7.0+에서만 지원되므로 제거
// declare(strict_types=1);


error_reporting(E_ALL);
if (defined('YELLOW_API_MODE') && YELLOW_API_MODE) {
    ini_set('display_errors', '0');
} else {
    ini_set('display_errors', '1');
}

$yyyy = date("Y");

date_default_timezone_set("Asia/Seoul");

/* =========================================================
 * Micro Time
 * ========================================================= */
function mtime() {
    return microtime(true);
}

$start_time = mtime();

/* =========================================================
 * 기본 설정
 * ========================================================= */
if (!defined('_GNUBOARD_')) define('_GNUBOARD_', '1');
if (!defined('G5_MYSQLI_USE')) define('G5_MYSQLI_USE', true);
if (!defined('G5_DISPLAY_SQL_ERROR')) define('G5_DISPLAY_SQL_ERROR', true);

/* DB 설정 로드 (기존 경로 유지) */
require_once 'db_config.php';
  
     
/* =========================================================
 * DB 연결
 * ========================================================= */
function sql_connect($host, $user, $pass, $db = null) {
    // PHP 8.x 호환성을 위해 null 체크
    if ($db === null) {
        $db = '';
    }
    
    $link = mysqli_connect($host, $user, $pass, $db);

    if (!$link) {
        // PHP 5.6 호환성을 위해 예외처리와 일반 에러처리 병행
        if (class_exists('RuntimeException')) {
            throw new RuntimeException('DB Connect Error: ' . mysqli_connect_error());
        } else {
            die('DB Connect Error:  $host, $user, $pass, $db ' . mysqli_connect_error());
        }
    }

    mysqli_set_charset($link, 'utf8');

    return $link;
}

/* =========================================================
 * Charset
 * ========================================================= */
function sql_set_charset($charset, $link) {
    return mysqli_set_charset($link, $charset);
}

/* =========================================================
 * Query
 * ========================================================= */
function sql_query($sql, $error = G5_DISPLAY_SQL_ERROR, $link = null) {
    global $g5, $debug;

    if (!$link && isset($g5['connect_db'])) {
        $link = $g5['connect_db'];
    }

    $sql = trim($sql);

    // SQL Injection 최소 방어 (기존 로직 유지)
    $sql = preg_replace("#^select.*from.*[\s\(]+union[\s\)]+.*#i", "select 1", $sql);
    $sql = preg_replace("#^select.*from.*where.*`?information_schema`?.*#i", "select 1", $sql);

    if (!(defined('YELLOW_API_MODE') && YELLOW_API_MODE) && isset($debug) && $debug == 2) {
        echo "<pre><code>$sql</code></pre>";
    }

    $result = mysqli_query($link, $sql);

    if (!$result && $error) {
        $error_msg = "SQL ERROR : " . mysqli_error($link) . "\nSQL : $sql";
        
        // PHP 5.6 호환성을 위해 예외처리와 일반 에러처리 병행
        if (class_exists('RuntimeException')) {
            throw new RuntimeException($error_msg);
        } else {
            die($error_msg);
        }
    }

    return $result;
}

/* =========================================================
 * Fetch
 * ========================================================= */
function sql_fetch_array($result) {
    $row = mysqli_fetch_assoc($result);
    return $row ? $row : null;
}

function Fetch($result) {
    $row = mysqli_fetch_array($result, MYSQLI_BOTH);
    return $row ? $row : null;
}

function sql_fetch($sql, $error = G5_DISPLAY_SQL_ERROR, $link = null) {
    $rs = sql_query($sql, $error, $link);
    
    // PHP 5.6에서는 mysqli_result 클래스 체크 방식이 다를 수 있음
    if (is_object($rs) && method_exists($rs, 'fetch_assoc')) {
        return sql_fetch_array($rs);
    }
    
    return null;
}

/* =========================================================
 * Free
 * ========================================================= */
function sql_free_result($result) {
    if (is_object($result) && method_exists($result, 'free')) {
        mysqli_free_result($result);
    }
}

/* =========================================================
 * Util
 * ========================================================= */
function sql_insert_id($link) {
    return mysqli_insert_id($link);
}

function sql_affected_rows($link) {
    return mysqli_affected_rows($link);
}

/* =========================================================
 * DB / Table / Field 체크
 * ========================================================= */
function isDB($db, $link) {
    $rs = sql_query("SHOW DATABASES", true, $link);
    $db_lower = strtolower($db);

    while ($r = Fetch($rs)) {
        if (strtolower($r[0]) === $db_lower) {
            sql_free_result($rs);
            return true;
        }
    }
    
    sql_free_result($rs);
    return false;
}

function isTable($tb, $link) {
    $rs = sql_query("SHOW TABLES LIKE '{$tb}'", true, $link);
    $count = mysqli_num_rows($rs);
    sql_free_result($rs);
    return $count > 0;
}

function isTbFd($tb, $fd, $link) {
    $rs = sql_query("SHOW FULL FIELDS FROM {$tb}", true, $link);

    while ($r = sql_fetch_array($rs)) {
        if ($r['Field'] === $fd) {
            sql_free_result($rs);
            return true;
        }
    }
    
    sql_free_result($rs);
    return false;
}

/* =========================================================
 * Field 정보
 * ========================================================= */
function GetFDS($table, $link) {
    $rt = array();
    $rs = sql_query("SHOW FULL FIELDS FROM {$table}", true, $link);

    while ($r = sql_fetch_array($rs)) {
        $rt[] = $r['Field'];
    }
    
    sql_free_result($rs);
    return $rt;
}

function getFdCmt($tb, $link) {
    $rt = array('Fd' => array(), 'Cmt' => array());
    $rs = sql_query("SHOW FULL FIELDS FROM {$tb}", true, $link);

    while ($r = sql_fetch_array($rs)) {
        $rt['Fd'][]  = "`{$r['Field']}`";
        $rt['Cmt'][] = $r['Comment'];
    }
    
    sql_free_result($rs);
    return $rt;
}

/* =========================================================
 * UTF-8
 * ========================================================= */
function utf8($str) {
    // PHP 5.6 호환성을 위해 함수 존재 여부 체크
    if (function_exists('mb_detect_encoding')) {
        if (mb_detect_encoding($str, 'UTF-8', true)) {
            return $str;
        }
    }
    
    if (function_exists('iconv')) {
        return iconv('EUC-KR', 'UTF-8', $str);
    }
    
    return $str;
}

// PHP 5.6에서는 mysqli_result가 객체인지 확인하기 위한 헬퍼 함수
if (!function_exists('is_mysqli_result')) {
    function is_mysqli_result($result) {
        return is_object($result) && get_class($result) === 'mysqli_result';
    }
}