<?php
/**
 * license-php/lib/ClientDatabase.php
 * Centralized Database Connection Manager for Presensi Client MySQL (presensi_client_db).
 * Strictly adheres to PDO prepared statements and robust error handling.
 */

class ClientDatabase {
    private static ?PDO $pdo = null;

    /**
     * Get or create active PDO connection to presensi_client_db.
     */
    public static function getConnection(): PDO {
        if (self::$pdo !== null) {
            return self::$pdo;
        }

        $config = require dirname(__DIR__) . '/config/config.php';
        $dbConfig = $config['client_db'] ?? [
            'host'     => getenv('CLIENT_DB_HOST') ?: (getenv('DB_HOST') ?: '127.0.0.1'),
            'port'     => getenv('CLIENT_DB_PORT') ?: (getenv('DB_PORT') ?: '3306'),
            'name'     => getenv('CLIENT_DB_NAME') ?: 'presensi_client_db',
            'user'     => getenv('CLIENT_DB_USER') ?: (getenv('DB_USER') ?: 'root'),
            'password' => getenv('CLIENT_DB_PASSWORD') !== false ? getenv('CLIENT_DB_PASSWORD') : (getenv('DB_PASSWORD') !== false ? getenv('DB_PASSWORD') : ''),
            'charset'  => 'utf8mb4',
        ];

        $host     = $dbConfig['host'] ?? '127.0.0.1';
        $port     = $dbConfig['port'] ?? '3306';
        $dbname   = $dbConfig['name'] ?? 'presensi_client_db';
        $charset  = $dbConfig['charset'] ?? 'utf8mb4';
        $user     = $dbConfig['user'] ?? 'root';
        $password = $dbConfig['password'] ?? '';

        $dsn = "mysql:host={$host};port={$port};dbname={$dbname};charset={$charset}";

        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false
        ];

        try {
            self::$pdo = new PDO($dsn, $user, $password, $options);
            return self::$pdo;
        } catch (PDOException $e) {
            error_log('[CLIENT_DB ERROR] Connection failed: ' . $e->getMessage());
            throw new RuntimeException('Koneksi database presensi client gagal: ' . $e->getMessage(), (int)$e->getCode(), $e);
        }
    }

    /**
     * Override PDO connection (for testing / mocking).
     */
    public static function setConnection(?PDO $pdo): void {
        self::$pdo = $pdo;
    }
}
