loadConnectionProfiles(); $this->pdo = $this->createConnection(); $this->currentDatabase = $_ENV['DB_NAME'] ?? 'crm'; } /** * Create PDO connection */ private function createConnection(): PDO { try { // Load environment variables \App\Core\EnvironmentLoader::load(); $config = \App\Core\EnvironmentLoader::getDatabaseConfig(); // In local development, use MAMP socket if ($config['host'] === 'localhost' && $config['port'] === '8889') { $dsn = "mysql:unix_socket=" . ($config['socket'] ?: '/Applications/MAMP/tmp/mysql/mysql.sock') . ";dbname=" . $config['database']; } else { $dsn = "mysql:host=" . $config['host'] . ";dbname=" . $config['database'] . ";port=" . $config['port']; // Add socket if defined if (!empty($config['socket'])) { $dsn .= ";unix_socket=" . $config['socket']; } } return new PDO( $dsn, $config['username'], $config['password'], [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES " . $config['charset'] ] ); } catch (PDOException $e) { // ErrorReporter::report($e, ['context' => 'Database connection creation']); throw new Exception("Database connection failed: " . $e->getMessage()); } } public static function getInstance(): self { if (self::$instance === null) { self::$instance = new self(); } return self::$instance; } /** * Get PDO connection (compatibility method) */ public static function getConnection(): PDO { return self::getInstance()->pdo; } /** * Switch to a specific database */ public function useDatabase(string $database): bool { try { // Create new PDO connection with specified database $host = $_ENV['DB_HOST'] ?? 'localhost'; $port = $_ENV['DB_PORT'] ?? '8889'; $user = $_ENV['DB_USER'] ?? 'root'; $pass = $_ENV['DB_PASS'] ?? 'root'; // In local development, use MAMP socket if ($host === '127.0.0.1' && $port === '8889') { $dsn = "mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname={$database}"; } else { $dsn = "mysql:host={$host};dbname={$database};port={$port}"; // Add socket if defined if (isset($_ENV['DB_SOCKET']) && !empty($_ENV['DB_SOCKET'])) { $dsn .= ";unix_socket=" . $_ENV['DB_SOCKET']; } } $this->pdo = new PDO($dsn, $user, $pass, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4" ]); $this->currentDatabase = $database; return true; } catch (PDOException $e) { // ErrorReporter::report($e, ['context' => 'Database switch', 'database' => $database]); return false; } } /** * Get current database name */ public function getCurrentDatabase(): string { return $this->currentDatabase; } /** * Switch back to default database */ public function useDefaultDatabase(): bool { $defaultDb = $_ENV['DB_NAME'] ?? 'crm'; return $this->useDatabase($defaultDb); } /** * Execute query on specific database */ public function queryOnDatabase(string $database, string $query, array $params = []): mixed { $originalDb = $this->currentDatabase; $this->useDatabase($database); try { $result = $this->query($query, $params); return $result; } finally { $this->useDatabase($originalDb); } } /** * Fetch single record from specific database */ public function fetchOnDatabase(string $database, string $query, array $params = [], ?callable $callback = null): ?array { $originalDb = $this->currentDatabase; $this->useDatabase($database); try { $result = $this->fetch($query, $params, $callback); return $result; } finally { $this->useDatabase($originalDb); } } /** * Fetch all records from specific database */ public function fetchAllOnDatabase(string $database, string $query, array $params = [], ?callable $callback = null): array { $originalDb = $this->currentDatabase; $this->useDatabase($database); try { $result = $this->fetchAll($query, $params, $callback); return $result; } finally { $this->useDatabase($originalDb); } } /** * Fetch a single record */ public function fetch(string $query, array $params = [], ?callable $callback = null): ?array { try { $stmt = $this->pdo->prepare($query); $stmt->execute($params); $result = $stmt->fetch(); if ($callback && $result) { $result = $callback($result); } return $result ?: null; } catch (PDOException $e) { $this->logError($e, $query, $params); throw new Exception("Database fetch error: " . $e->getMessage()); } } /** * Fetch all records */ public function fetchAll(string $query, array $params = [], ?callable $callback = null): array { try { $stmt = $this->pdo->prepare($query); $stmt->execute($params); $results = $stmt->fetchAll(); if ($callback) { $results = array_map($callback, $results); } return $results; } catch (PDOException $e) { $this->logError($e, $query, $params); throw new Exception("Database fetchAll error: " . $e->getMessage()); } } /** * Execute INSERT, UPDATE, DELETE query */ public function query(string $query, array $params = []): int { try { $stmt = $this->pdo->prepare($query); $stmt->execute($params); return $stmt->rowCount(); } catch (PDOException $e) { $this->logError($e, $query, $params); throw new Exception("Database query error: " . $e->getMessage()); } } /** * Execute raw SQL (use with caution) */ public function execute(string $sql): bool { try { return $this->pdo->exec($sql) !== false; } catch (PDOException $e) { ErrorReporter::report($e, ['context' => 'Raw SQL execution', 'sql' => $sql]); throw new Exception("Database execute error: " . $e->getMessage()); } } /** * Execute query and return results */ public function queryWithResult(string $sql, array $params = []): array { try { $stmt = $this->pdo->prepare($sql); $stmt->execute($params); return [ 'rowCount' => $stmt->rowCount(), 'lastInsertId' => $this->pdo->lastInsertId(), 'results' => $stmt->fetchAll() ]; } catch (PDOException $e) { $this->logError($e, $sql, $params); throw new Exception("Database queryWithResult error: " . $e->getMessage()); } } /** * Insert or update record based on unique keys */ public function insertOrUpdate(string $table, array $data, array $uniqueKeys = ['id']): int { try { // Check if record exists $whereConditions = []; $whereParams = []; foreach ($uniqueKeys as $key) { if (isset($data[$key])) { $whereConditions[] = "{$key} = ?"; $whereParams[] = $data[$key]; } } if (empty($whereConditions)) { throw new Exception("No unique keys provided for insertOrUpdate"); } $whereClause = implode(' AND ', $whereConditions); $existing = $this->fetch("SELECT COUNT(*) as count FROM {$table} WHERE {$whereClause}", $whereParams); if ($existing && $existing['count'] > 0) { // Update existing record return $this->update($table, $data, array_combine($uniqueKeys, $whereParams)); } else { // Insert new record return $this->insert($table, $data); } } catch (Exception $e) { ErrorReporter::report($e, ['context' => 'InsertOrUpdate', 'table' => $table, 'data' => $data]); throw $e; } } /** * Insert new record */ public function insert(string $table, array $data): int { try { $columns = implode(', ', array_keys($data)); $placeholders = '?' . str_repeat(', ?', count($data) - 1); $sql = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})"; $stmt = $this->pdo->prepare($sql); $stmt->execute(array_values($data)); return (int) $this->pdo->lastInsertId(); } catch (PDOException $e) { $this->logError($e, "INSERT INTO {$table}", $data); throw new Exception("Database insert error: " . $e->getMessage()); } } /** * Update existing record */ public function update(string $table, array $data, array $where): int { try { $setParts = []; $whereParts = []; $params = []; // Build SET clause foreach ($data as $column => $value) { $setParts[] = "{$column} = ?"; $params[] = $value; } // Build WHERE clause foreach ($where as $column => $value) { $whereParts[] = "{$column} = ?"; $params[] = $value; } $setClause = implode(', ', $setParts); $whereClause = implode(' AND ', $whereParts); $sql = "UPDATE {$table} SET {$setClause} WHERE {$whereClause}"; $stmt = $this->pdo->prepare($sql); $stmt->execute($params); return $stmt->rowCount(); } catch (PDOException $e) { $this->logError($e, "UPDATE {$table}", array_merge($data, $where)); throw new Exception("Database update error: " . $e->getMessage()); } } /** * Delete records */ public function delete(string $table, array $where): int { try { $whereParts = []; $params = []; foreach ($where as $column => $value) { $whereParts[] = "{$column} = ?"; $params[] = $value; } $whereClause = implode(' AND ', $whereParts); $sql = "DELETE FROM {$table} WHERE {$whereClause}"; $stmt = $this->pdo->prepare($sql); $stmt->execute($params); return $stmt->rowCount(); } catch (PDOException $e) { $this->logError($e, "DELETE FROM {$table}", $where); throw new Exception("Database delete error: " . $e->getMessage()); } } /** * Count records */ public function count(string $table, array $where = []): int { try { $sql = "SELECT COUNT(*) as count FROM {$table}"; $params = []; if (!empty($where)) { $whereParts = []; foreach ($where as $column => $value) { $whereParts[] = "{$column} = ?"; $params[] = $value; } $sql .= " WHERE " . implode(' AND ', $whereParts); } $result = $this->fetch($sql, $params); return (int) ($result['count'] ?? 0); } catch (PDOException $e) { $this->logError($e, "COUNT {$table}", $where); throw new Exception("Database count error: " . $e->getMessage()); } } /** * Check if record exists */ public function exists(string $table, array $where): bool { return $this->count($table, $where) > 0; } /** * Execute transaction */ public function transaction(callable $callback): mixed { try { $this->pdo->beginTransaction(); $result = $callback($this); $this->pdo->commit(); return $result; } catch (Exception $e) { $this->pdo->rollBack(); throw $e; } } /** * Get last insert ID */ public function lastInsertId(): int { return (int) $this->pdo->lastInsertId(); } /** * Log database errors */ private function logError(PDOException $e, string $query, array $params): void { // ErrorReporter::report($e, [ // 'context' => 'Database operation', // 'query' => $query, // 'params' => $params, // 'database' => $this->currentDatabase // ]); } /** * Get PDO instance (use with caution) */ public function getPDO(): PDO { return $this->pdo; } // Prevent cloning private function __clone() {} /** * Prevent unserialization */ public function __wakeup() { throw new Exception("Cannot unserialize singleton"); } /** * Get connection for specific database */ public static function getConnectionFor(string $database, ?string $host = null, ?string $user = null, ?string $pass = null, ?string $port = null): PDO { $connectionKey = "{$host}:{$port}:{$user}:{$database}"; if (!isset(self::$_connections[$connectionKey])) { $host = $host ?? $_ENV['DB_HOST'] ?? 'localhost'; $port = $port ?? $_ENV['DB_PORT'] ?? '8889'; $user = $user ?? $_ENV['DB_USER'] ?? 'root'; $pass = $pass ?? $_ENV['DB_PASS'] ?? 'root'; // In local development, use MAMP socket if ($host === '127.0.0.1' && $port === '8889') { $dsn = "mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname={$database}"; } else { $dsn = "mysql:host={$host};dbname={$database};port={$port}"; // Add socket if defined if (isset($_ENV['DB_SOCKET']) && !empty($_ENV['DB_SOCKET'])) { $dsn .= ";unix_socket=" . $_ENV['DB_SOCKET']; } } try { self::$_connections[$connectionKey] = new PDO($dsn, $user, $pass, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4" ]); } catch (PDOException $e) { // ErrorReporter::report($e, [ // 'context' => 'Multi-connection creation', // 'database' => $database, // 'host' => $host, // 'port' => $port // ]); throw new Exception("Failed to create connection for database {$database}: " . $e->getMessage()); } } return self::$_connections[$connectionKey]; } /** * Escape value for safe use in queries */ public function escape($value): string { if (is_null($value)) { return 'NULL'; } if (is_bool($value)) { return $value ? '1' : '0'; } if (is_numeric($value)) { return (string) $value; } return $this->pdo->quote($value); } /** * Extract JSON field value */ public function jsonExtract(string $field, string $key): string { return "JSON_EXTRACT({$field}, '$.{$key}')"; } /** * Execute query with retry mechanism */ private function queryWithRetry(string $query, array $params = [], int $maxRetries = 3): int|array { $attempts = 0; $lastException = null; while ($attempts < $maxRetries) { try { $stmt = $this->pdo->prepare($query); $stmt->execute($params); // Determine if it's a SELECT or other query if (stripos(trim($query), 'SELECT') === 0) { return $stmt->fetchAll(); } else { return $stmt->rowCount(); } } catch (PDOException $e) { $lastException = $e; $attempts++; // Only retry on connection-related errors if ($e->getCode() !== 'HY000' || strpos($e->getMessage(), 'server has gone away') === false) { break; } // Wait before retry (exponential backoff) if ($attempts < $maxRetries) { sleep(pow(2, $attempts)); } } } // If we get here, all retries failed $this->logError($lastException, $query, $params); throw new Exception("Database query failed after {$maxRetries} attempts: " . $lastException->getMessage()); } /** * Fetch all records with flexible error handling */ public function fetchAllFlexible(string $query, array $params = [], ?callable $callback = null): array { try { return $this->fetchAll($query, $params, $callback); } catch (Exception $e) { // ErrorReporter::report($e, ['context' => 'Flexible fetchAll', 'query' => $query]); return []; } } /** * Fetch single record with flexible error handling */ public function fetchFlexible(string $query, array $params = [], ?callable $callback = null): ?array { try { return $this->fetch($query, $params, $callback); } catch (Exception $e) { // ErrorReporter::report($e, ['context' => 'Flexible fetch', 'query' => $query]); return null; } } /** * Safe insert or update with error handling */ public function insertOrUpdateSafe(string $table, array $data, array $uniqueKeys = ['id']): int { try { return $this->insertOrUpdate($table, $data, $uniqueKeys); } catch (Exception $e) { ErrorReporter::report($e, ['context' => 'Safe insertOrUpdate', 'table' => $table]); return 0; } } /** * Load connection profiles from environment variables */ private function loadConnectionProfiles(): void { if (!empty(self::$connectionProfiles)) { return; // Already loaded } // Load environment first \App\Core\EnvironmentLoader::load(); // Try to get profiles as string first (new format) $profilesString = \App\Core\EnvironmentLoader::get('DB_PROFILES'); if (!empty($profilesString)) { // Parse comma-separated profiles $profiles = explode(',', $profilesString); foreach ($profiles as $profile) { $profile = trim($profile); if (empty($profile)) continue; // Parse profile format: name:host:port:user:pass:db:charset:socket $parts = explode(':', $profile); if (count($parts) < 5) continue; // Need at least name, host, port, user, pass, db $profileName = trim($parts[0]); $config = []; if (count($parts) >= 2) $config['host'] = trim($parts[1]); if (count($parts) >= 3) $config['port'] = trim($parts[2]); if (count($parts) >= 4) $config['username'] = trim($parts[3]); if (count($parts) >= 5) $config['password'] = trim($parts[4]); if (count($parts) >= 6) $config['database'] = trim($parts[5]); if (count($parts) >= 7) $config['charset'] = trim($parts[6]); if (count($parts) >= 8) $config['socket'] = trim($parts[7]); self::$connectionProfiles[$profileName] = $config; } } else { // New format with prefixes: DB_PROFILE_DEFAULT, DB_PROFILE_IMPORTER, etc. $prefixProfiles = [ 'default' => $_ENV['DB_PROFILE_DEFAULT'] ?? null, 'importer' => $_ENV['DB_PROFILE_IMPORTER'] ?? null, 'legacy' => $_ENV['DB_PROFILE_LEGACY'] ?? null, ]; foreach ($prefixProfiles as $profileName => $profileConfig) { if (empty($profileConfig)) continue; $config = []; $parts = explode(':', $profileConfig); if (count($parts) >= 1) $config['host'] = trim($parts[0]); if (count($parts) >= 2) $config['port'] = trim($parts[1]); if (count($parts) >= 3) $config['username'] = trim($parts[2]); if (count($parts) >= 4) $config['password'] = trim($parts[3]); if (count($parts) >= 5) $config['database'] = trim($parts[4]); if (count($parts) >= 6) $config['charset'] = trim($parts[5]); if (count($parts) >= 7) $config['socket'] = trim($parts[6]); self::$connectionProfiles[$profileName] = $config; } } } /** * Get configuration for a specific connection profile */ public static function getConnectionProfile(string $profileName = 'default'): array { if (!isset(self::$connectionProfiles[$profileName])) { throw new Exception("Connection profile '{$profileName}' not found."); } return self::$connectionProfiles[$profileName]; } /** * Switch to a different connection profile */ public function connectionProfile(string $profileName): self { if ($this->currentProfile === $profileName) { return $this; // Already using this profile } $this->currentProfile = $profileName; $this->pdo = $this->createConnectionForProfile($profileName); return $this; } /** * Create connection for specific profile */ private function createConnectionForProfile(string $profileName): PDO { try { // Load environment variables \App\Core\EnvironmentLoader::load(); $defaultConfig = \App\Core\EnvironmentLoader::getDatabaseConfig(); // Get profile-specific config $profileConfig = self::getConnectionProfile($profileName); // Merge default config with profile config $config = array_merge($defaultConfig, $profileConfig); // Create connection key for caching $connectionKey = "{$profileName}:{$config['host']}:{$config['port']}:{$config['database']}:{$config['username']}"; // Check if connection already exists if (isset(self::$_connections[$connectionKey])) { return self::$_connections[$connectionKey]; } // In local development, use MAMP socket if ($config['host'] === 'localhost' && $config['port'] === '8889') { $dsn = "mysql:unix_socket=" . ($config['socket'] ?: '/Applications/MAMP/tmp/mysql/mysql.sock') . ";dbname=" . $config['database']; } else { $dsn = "mysql:host=" . $config['host'] . ";dbname=" . $config['database'] . ";port=" . $config['port']; // Add socket if defined if (!empty($config['socket'])) { $dsn .= ";unix_socket=" . $config['socket']; } } $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_TIMEOUT => 5, // 5 seconds timeout PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES " . ($config['charset'] ?: 'utf8mb4') ]; $pdo = new PDO($dsn, $config['username'], $config['password'], $options); // Cache the connection self::$_connections[$connectionKey] = $pdo; return $pdo; } catch (PDOException $e) { throw new Exception("Database connection failed for profile '{$profileName}': " . $e->getMessage()); } } /** * Get current connection profile name */ public function getCurrentProfile(): string { return $this->currentProfile; } /** * List all available connection profiles */ public static function getAvailableProfiles(): array { return array_keys(self::$connectionProfiles); } }