<?php
/**
 * Konfigurasi Database SIAKAD
 * ============================================================
 *
 * LOCALHOST:
 *   DB_HOST = 'localhost'
 *   DB_USER = 'root'
 *   DB_PASS = ''
 *   DB_NAME = 'siakad'
 *
 * HOSTING (cPanel):
 *   DB_HOST = 'localhost'
 *   DB_USER = 'namauser_siakad'   dari cPanel > MySQL Databases
 *   DB_PASS = 'password_db'       password yang dibuat di cPanel
 *   DB_NAME = 'namauser_siakad'   nama database di cPanel
 * ============================================================
 */

define('DB_HOST',    'localhost');
define('DB_USER',    'mtsdafam_siakad');
define('DB_PASS',    'admin0520');
define('DB_NAME',    'mtsdafam_siakad');
define('DB_CHARSET', 'utf8mb4');

function getDB() {
    static $conn = null;
    if ($conn === null) {
        $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($conn->connect_error) {
            $msg = (defined('IS_PRODUCTION') && IS_PRODUCTION)
                ? 'Terjadi kesalahan sistem. Hubungi administrator.'
                : 'Koneksi database gagal: ' . $conn->connect_error;
            die('<div style="font-family:sans-serif;padding:30px;max-width:500px;margin:50px auto;
                background:#fee2e2;border:1px solid #fca5a5;border-radius:8px;">
                <h3 style="color:#dc2626;margin:0 0 10px">Database Error</h3>
                <p style="margin:0;color:#7f1d1d">' . htmlspecialchars($msg) . '</p>
                <p style="margin:10px 0 0;font-size:.85rem;color:#991b1b">
                    Periksa konfigurasi di <code>config/database.php</code>
                </p></div>');
        }
        $conn->set_charset(DB_CHARSET);
    }
    return $conn;
}

/**
 * Helper: ambil semua baris dari $db->query()
 */
function query_fetch_all($db, $sql) {
    $result = $db->query($sql);
    if (!$result) return array();
    $rows = array();
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $result->free();
    return $rows;
}

/**
 * Helper: ambil satu baris dari $db->query()
 */
function query_fetch_assoc($db, $sql) {
    $result = $db->query($sql);
    if (!$result) return null;
    $row = $result->fetch_assoc();
    $result->free();
    return $row ? $row : null;
}

/**
 * Kompatibilitas stmt->get_result() untuk hosting tanpa mysqlnd penuh.
 * Mengembalikan objek dengan fetch_assoc() dan fetch_all().
 */
function stmt_get_result($stmt) {
    $stmt->store_result();
    $meta = $stmt->result_metadata();

    if (!$meta) {
        return new StmtResultEmpty();
    }

    $fields = array();
    while ($field = $meta->fetch_field()) {
        $fields[] = $field->name;
    }
    $meta->free();

    $row  = array();
    $refs = array();
    foreach ($fields as $name) {
        $row[$name] = null;
        $refs[]     = &$row[$name];
    }
    call_user_func_array(array($stmt, 'bind_result'), $refs);

    $rows = array();
    while ($stmt->fetch()) {
        $copy = array();
        foreach ($row as $k => $v) {
            $copy[$k] = $v;
        }
        $rows[] = $copy;
    }

    return new StmtResult($rows);
}

/**
 * Hasil kosong untuk query non-SELECT
 */
class StmtResultEmpty {
    public $num_rows = 0;
    public function fetch_assoc() { return null; }
    public function fetch_all($mode = MYSQLI_ASSOC) { return array(); }
}

/**
 * Hasil untuk query SELECT
 */
class StmtResult {
    private $rows;
    private $pos;
    public  $num_rows;

    public function __construct($rows) {
        $this->rows     = $rows;
        $this->pos      = 0;
        $this->num_rows = count($rows);
    }

    public function fetch_assoc() {
        if ($this->pos < count($this->rows)) {
            return $this->rows[$this->pos++];
        }
        return null;
    }

    public function fetch_all($mode = MYSQLI_ASSOC) {
        return $this->rows;
    }
}
