<?php
class SecureEmailStorage {
    private $file;
    private $encryptionKey;
    private $cipher = 'AES-256-CBC';

    public function __construct(string $filePath, string $key) {
        $this->file = $filePath;
        if (empty($key) || strlen($key) < 16) {
            throw new InvalidArgumentException('Clave inválida.');
        }
        $this->encryptionKey = substr(hash('sha256', $key, true), 0, 32);
    }

    public function validateEmail(string $email): bool {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }

    private function encrypt(string $data): string {
        $ivLength = openssl_cipher_iv_length($this->cipher);
        $iv = openssl_random_pseudo_bytes($ivLength);
        $encrypted = openssl_encrypt($data, $this->cipher, $this->encryptionKey, OPENSSL_RAW_DATA, $iv);
        return base64_encode($iv . $encrypted);
    }

    private function decrypt(string $data): string {
        $data = base64_decode($data);
        $ivLength = openssl_cipher_iv_length($this->cipher);
        $iv = substr($data, 0, $ivLength);
        $encrypted = substr($data, $ivLength);
        return openssl_decrypt($encrypted, $this->cipher, $this->encryptionKey, OPENSSL_RAW_DATA, $iv);
    }

    public function getAllRegistries(): array {
        if (!file_exists($this->file)) {
            return [];
        }
        $content = file_get_contents($this->file);
        if (empty($content)) return [];
        
        $decrypted = $this->decrypt($content);
        $data = json_decode($decrypted, true);
        return is_array($data) ? $data : [];
    }

    private function saveAllRegistries(array $data): bool {
        $json = json_encode($data, JSON_PRETTY_PRINT);
        $encrypted = $this->encrypt($json);
        return file_put_contents($this->file, $encrypted, LOCK_EX) !== false;
    }

    public function processRegistration(string $name, string $email, string $ip, string $userAgent): bool {
        if (!$this->validateEmail($email)) return false;

        $registries = $this->getAllRegistries();
        $found = false;

        foreach ($registries as &$entry) {
            if (strtolower($entry['email']) === strtolower(trim($email))) {
                $entry['countdownload']++;
                $entry['last_access_date'] = date('Y-m-d H:i:s');
                $entry['last_ip'] = $ip;
                $found = true;
                break;
            }
        }

        if (!$found) {
            $registries[] = [
                'id' => uniqid('NYX_', true),
                'nombre' => trim($name),
                'email' => trim($email),
                'ip' => $ip,
                'navegador' => $userAgent,
                'fecha' => date('Y-m-d H:i:s'),
                'last_access_date' => date('Y-m-d H:i:s'),
                'countdownload' => 1,
                'metadata' => [
                    'os' => $this->getOS($userAgent),
                    'secure_token' => hash('sha256', $email . time())
                ]
            ];
        }

        return $this->saveAllRegistries($registries);
    }

    private function getOS($userAgent) {
        $os_array = [
            '/windows nt 10/i'      =>  'Windows 10',
            '/windows nt 6.3/i'     =>  'Windows 8.1',
            '/windows nt 6.2/i'     =>  'Windows 8',
            '/windows nt 6.1/i'     =>  'Windows 7',
            '/macintosh|mac os x/i' =>  'Mac OS X',
            '/android/i'            =>  'Android',
            '/iphone/i'             =>  'iPhone'
        ];
        foreach ($os_array as $regex => $value) {
            if (preg_match($regex, $userAgent)) return $value;
        }
        return 'Unknown OS';
    }
}
?>
