<?php
/**
 * SISPENRA - Konfigurasi Database
 */

define('DB_HOST', 'localhost');
define('DB_USER', 'appce697_nilai');
define('DB_PASS', 'Snesaka123456*');
define('DB_NAME', 'appce697_nilai');
define('DB_CHARSET', 'utf8mb4');

// Koneksi database menggunakan PDO
try {
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
    $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];
    $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
} catch (PDOException $e) {
    error_log("Database Connection Error: " . $e->getMessage());
    die(json_encode(['error' => 'Koneksi database gagal. Silakan hubungi administrator.']));
}

/**
 * FIX 1: db_query — handle NULL eksplisit via bindValue
 * Tanpa ini, nilai NULL (kolom sumatif kosong) gagal di-bind
 * karena PDO::ATTR_EMULATE_PREPARES => false bersifat strict.
 */
function db_query($sql, $params = []) {
    global $pdo;
    $stmt = $pdo->prepare($sql);
    foreach ($params as $key => $val) {
        if (is_int($key)) {
            // Positional placeholder (?)
            $type = ($val === null) ? PDO::PARAM_NULL : (is_int($val) ? PDO::PARAM_INT : PDO::PARAM_STR);
            $stmt->bindValue($key + 1, $val, $type);
        } else {
            // Named placeholder (:key)
            $k    = (strpos($key, ':') === 0) ? $key : ':' . $key;
            $type = ($val === null) ? PDO::PARAM_NULL : (is_int($val) ? PDO::PARAM_INT : PDO::PARAM_STR);
            $stmt->bindValue($k, $val, $type);
        }
    }
    $stmt->execute();
    return $stmt;
}

function db_fetch($sql, $params = []) {
    return db_query($sql, $params)->fetch();
}

function db_fetchAll($sql, $params = []) {
    return db_query($sql, $params)->fetchAll();
}

function db_insert($table, $data) {
    global $pdo;
    $columns      = implode(', ', array_keys($data));
    $placeholders = ':' . implode(', :', array_keys($data));
    $sql = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})";
    db_query($sql, $data);
    return $pdo->lastInsertId();
}

/**
 * FIX 2: db_update — prefix kolom SET dengan 'set__'
 * Tanpa ini, jika $data punya key yang sama dengan WHERE param,
 * array_merge akan menimpa nilainya → UPDATE bisa salah baris.
 */
function db_update($table, $data, $where, $whereParams = []) {
    $setParts    = [];
    $setPrefixed = [];
    foreach ($data as $key => $val) {
        $setParts[]                 = "{$key} = :set__{$key}";
        $setPrefixed["set__{$key}"] = $val;
    }
    $setString = implode(', ', $setParts);
    $sql = "UPDATE {$table} SET {$setString} WHERE {$where}";
    return db_query($sql, array_merge($setPrefixed, $whereParams));
}

// Ambil pengaturan sekolah
function getPengaturan() {
    return db_fetch("SELECT * FROM pengaturan LIMIT 1");
}