<?php

namespace App\Services;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;

class DecryptionService
{
    /**
     * Decrypt data using AES-256-CBC encryption
     *
     * @param string $encryptedData Base64 encoded encrypted data
     * @return string|null Decrypted data or null on failure
     */
    public function decryptData($encryptedData)
    {
        try {
            $sharedSecretKey = base64_decode(Config::get('app.shared_secret_key'));
            $encryptedData = base64_decode($encryptedData);

            if ($encryptedData === false) {
                Log::error('Error decoding base64 data');
                return null;
            }

            $ivLength = openssl_cipher_iv_length('AES-256-CBC');
            if (strlen($encryptedData) < $ivLength) {
                Log::error('Invalid encrypted data length');
                return null;
            }

            $iv = substr($encryptedData, 0, $ivLength);
            $encryptedData = substr($encryptedData, $ivLength);

            $decryptedData = openssl_decrypt($encryptedData, 'AES-256-CBC', $sharedSecretKey, 0, $iv);

            if ($decryptedData === false) {
                Log::error('Error decrypting data');
                return null;
            }

            return $decryptedData;
        } catch (\Exception $e) {
            Log::error('Decryption service error: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * Decrypt email and password from URL parameters
     *
     * @param \Illuminate\Http\Request $request
     * @return array Array with 'email' and 'password' keys or empty array
     */
    public function decryptLoginCredentials($request)
    {
        if (!$request->has('l') || !$request->has('h')) {
            return [];
        }

        try {
            $encryptedEmail = rawurldecode($request->get('l'));
            $encryptedPassword = rawurldecode($request->get('h'));

            $email = $this->decryptData($encryptedEmail);
            $password = $this->decryptData($encryptedPassword);

            if ($email && $password) {
                return [
                    'email' => $email,
                    'password' => $password
                ];
            }
        } catch (\Exception $e) {
            Log::error('Error decrypting login credentials: ' . $e->getMessage());
        }

        return [];
    }
}
