<?php

namespace App\Providers;

use Aws\SecretsManager\SecretsManagerClient;
use Aws\Exception\AwsException;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Config;

class AWSSecretsManagerProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot()
    {   
        if(config('app.env')!='local'){     
             //$this->loadSecretsFromAWS();
        }
    }

    /**
     * Load secrets from AWS Secrets Manager and set them in the environment.
     */
    protected function loadSecretsFromAWS()
    {        
        // Ensure AWS credentials and secret name are in the .env file
        $secretNameArr = array(config('app.AWS_SECRET_DB'), config('app.AWS_SECRET_AWS'));
           
        if (empty($secretNameArr[0])) {
            return;
        }

        // Create a Secrets Manager Client
        $client = new SecretsManagerClient([
            'version' => 'latest',
            'region' => "us-east-1"            
        ]);
        
        try {
            foreach($secretNameArr as $secretName){
            // Fetch the secret from AWS Secrets Manager
            $result = $client->getSecretValue([
                'SecretId' => $secretName,
            ]);
            // echo "Secret manager load22";exit;
            if (isset($result['SecretString']) && !empty($result['SecretString'])) {
                $secret = json_decode($result['SecretString'], true); // Decode JSON format
                if($secretName == "RDSSecret"){
                // Set environment variables dynamically
                foreach ($secret as $key => $value) {
                    // echo "Secret manager loop";exit;
                    // Set the config for Laravel runtime usage
                    // putenv("$key=$value"); // Optionally use putenv() for PHP environment
                    if($key == 'dbInstanceIdentifier'){
                        $_ENV["DB_DATABASE"] = $value;
                        $_SERVER["DB_DATABASE"] = $value;
                    }else{
                        $_ENV["DB_".strtoupper($key)] = $value;
                        $_SERVER["DB_".strtoupper($key)] = $value;
                    }
                }
            }else{                
                foreach ($secret as $key => $value) {                                        
                        $_ENV[$key] = $value;
                        $_SERVER[$key] = $value;                    
                }
            }
            }
        }
        } catch (AwsException $e) {
            // Handle exception if necessary
            logger()->error('Failed to retrieve secrets from AWS Secrets Manager: ' . $e->getMessage());
        }
    }

    /**
     * Register any application services.
     */
    public function register()
    {
        // 
    }
}
