<?php

define('DB_HOST', 'localhost');
define('DB_NAME', 'pip_klasifikasi');
define('DB_USER', 'root');
define('DB_PASS', '');

function ensurePenghasilanOrtuColumn(PDO $pdo): void
{
    static $checked = false;
    if ($checked) {
        return;
    }
    $checked = true;

    $toVarchar = static function (PDO $db, string $table): void {
        $stmt = $db->prepare(
            'SELECT DATA_TYPE FROM information_schema.COLUMNS
             WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?'
        );
        $stmt->execute([DB_NAME, $table, 'penghasilan_ortu']);
        $row = $stmt->fetch();
        if ($row && strtolower((string) $row['DATA_TYPE']) === 'decimal') {
            $db->exec(
                "ALTER TABLE `$table` MODIFY COLUMN penghasilan_ortu VARCHAR(150) NOT NULL DEFAULT ''"
            );
        }
    };

    $toVarchar($pdo, 'siswa');
    $toVarchar($pdo, 'data_latih');
}

function getDB(): PDO
{
    static $pdo = null;
    if ($pdo === null) {
        $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4';
        $pdo = new PDO($dsn, DB_USER, DB_PASS, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
        ensurePenghasilanOrtuColumn($pdo);
    }
    return $pdo;
}
