db->query( "SELECT * FROM {$this->table} WHERE company_id = ? LIMIT 1", [$companyId] )->fetch(); if ($session) { $session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null; $session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null; } return $session; } /** * Get a session by session_key (used by webhooks) */ public function findBySessionKey(string $sessionKey) { $session = $this->db->query( "SELECT * FROM {$this->table} WHERE session_key = ? LIMIT 1", [$sessionKey] )->fetch(); if ($session) { $session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null; $session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null; } return $session; } /** * Create or retrieve a new session for a company */ public function findOrCreate(int $companyId, string $name = 'Main WhatsApp') { $session = $this->findByCompany($companyId); if ($session) { return $session; } $sessionKey = 'cmp_' . $companyId . '_' . bin2hex(random_bytes(4)); $id = $this->create([ 'company_id' => $companyId, 'name' => $name, 'session_key' => $sessionKey, 'status' => 'disconnected' ]); return $this->findByCompany($companyId); } /** * Update session state securely */ public function updateState(int $id, array $data) { if (isset($data['phone'])) { $data['phone_hash'] = Security::blindIndex($data['phone']); $data['phone'] = Security::encrypt($data['phone']); } if (isset($data['qr_code'])) { $data['qr_code'] = Security::encrypt($data['qr_code']); } return $this->update($id, $data); } }