<?php

namespace App\Http\Controllers;

use App\Services\EncryptionService; // Make sure you have this service created
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class EncryptionController extends Controller
{
    protected $encryptionService;

    public function __construct(EncryptionService $encryptionService)
    {
        $this->encryptionService = $encryptionService;
    }

    /**
     * Encrypt a string.
     */
    public function encrypt(Request $request)
    {
        // Validate input
        $request->validate([
            'data' => 'required|string',
        ]);

        // Encrypt the provided data
        try {
            $key = env('JWT_SECRET'); // Use your JWT_SECRET for encryption
            $encryptedData = $this->encryptionService->encryptData($request->input('data'), $key);
            return response()->json(['encrypted' => $encryptedData], Response::HTTP_OK);
        } catch (\Exception $e) {
            Log::error('Encryption error: ' . $e->getMessage());
            return response()->json(['error' => 'Encryption failed'], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * Decrypt a string.
     */
    public function decrypt(Request $request)
    {
        // Validate request data
        $request->validate([
            'encrypted' => 'required|string',
        ]);

        // Get the encrypted data from the request
        $encryptedData = $request->input('encrypted');

        // Decrypt the data
        try {
            $key = env('JWT_SECRET'); // Use the same key for decryption
            $decryptedData = $this->encryptionService->decryptData($encryptedData, $key);
            return response()->json(['decrypted' => $decryptedData], Response::HTTP_OK);
        } catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
            Log::error('Decryption error: ' . $e->getMessage());
            return response()->json(['error' => 'Decryption failed, invalid data'], Response::HTTP_BAD_REQUEST);
        } catch (\Exception $e) {
            Log::error('Decryption error: ' . $e->getMessage());
            return response()->json(['error' => 'Decryption failed'], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
}
