<?php
class DatabaseSessionHandler implements SessionHandlerInterface {
    private $pdo;
    
    public function __construct() {
        $this->pdo = Database::getInstance()->getConnection();
    }
    
    public function open($savePath, $sessionName): bool {
        return true;
    }
    
    public function close(): bool {
        return true;
    }
    
    public function read($sessionId): string {
        try {
            $stmt = $this->pdo->prepare("SELECT session_data FROM user_sessions WHERE session_id = ? AND expires_at > NOW()");
            $stmt->execute([$sessionId]);
            $data = $stmt->fetchColumn();
            return $data ?: '';
        } catch (Throwable $t) {
            return '';
        }
    }
    
    public function write($sessionId, $sessionData): bool {
        try {
            $stmt = $this->pdo->prepare("REPLACE INTO user_sessions (session_id, session_data, expires_at) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 2 HOUR))");
            return $stmt->execute([$sessionId, $sessionData]);
        } catch (Throwable $t) {
            return false;
        }
    }
    
    public function destroy($sessionId): bool {
        try {
            $stmt = $this->pdo->prepare("DELETE FROM user_sessions WHERE session_id = ?");
            return $stmt->execute([$sessionId]);
        } catch (Throwable $t) {
            return false;
        }
    }
    
    public function gc($maxLifetime): int {
        try {
            $stmt = $this->pdo->prepare("DELETE FROM user_sessions WHERE expires_at < NOW()");
            return $stmt->execute() ? 1 : 0;
        } catch (Throwable $t) {
            return 0;
        }
    }
}