<?php
// ============================================================
// config/database.php – Koneksi Database (PDO Singleton)
// ============================================================

class Database {
    private static ?PDO $instance = null;

    private static string $host   = 'localhost';
    private static string $db     = 'gent3792_pendamping_sekolah';
    private static string $user   = 'gent3792_guru';
    private static string $pass   = 'Dikmapsmlg!#';
    private static string $charset= 'utf8mb4';
    public static function getInstance(): PDO {
        if (self::$instance === null) {
            $dsn = "mysql:host=" . self::$host
                 . ";dbname=" . self::$db
                 . ";charset=" . self::$charset;
            $opts = [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ];
            try {
                self::$instance = new PDO($dsn, self::$user, self::$pass, $opts);
            } catch (PDOException $e) {
                error_log("DB Error: " . $e->getMessage());
                die(json_encode(['error' => 'Koneksi database gagal.']));
            }
        }
        return self::$instance;
    }

    // Shorthand query
    public static function query(string $sql, array $params = []): PDOStatement {
        $stmt = self::getInstance()->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }

    public static function fetchAll(string $sql, array $params = []): array {
        return self::query($sql, $params)->fetchAll();
    }

    public static function fetchOne(string $sql, array $params = []): array|false {
        return self::query($sql, $params)->fetch();
    }

    public static function execute(string $sql, array $params = []): bool {
        return self::query($sql, $params)->rowCount() > 0;
    }

    public static function lastInsertId(): string {
        return self::getInstance()->lastInsertId();
    }

    public static function count(string $sql, array $params = []): int {
        return (int) self::query($sql, $params)->fetchColumn();
    }
}
